]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/lib/Target/X86/X86ISelLowering.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / 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 "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   // If the input is a buildvector just emit a smaller one.
89   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
90     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
91                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
92
93   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
94   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95                                VecIdx);
96
97   return Result;
98 }
99
100 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
101 /// sets things up to match to an AVX VINSERTF128 instruction or a
102 /// simple superregister reference.  Idx is an index in the 128 bits
103 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering INSERT_VECTOR_ELT operations easier.
105 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
106                                   unsigned IdxVal, SelectionDAG &DAG,
107                                   DebugLoc dl) {
108   // Inserting UNDEF is Result
109   if (Vec.getOpcode() == ISD::UNDEF)
110     return Result;
111
112   EVT VT = Vec.getValueType();
113   assert(VT.is128BitVector() && "Unexpected vector size!");
114
115   EVT ElVT = VT.getVectorElementType();
116   EVT ResultVT = Result.getValueType();
117
118   // Insert the relevant 128 bits.
119   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
120
121   // This is the index of the first element of the 128-bit chunk
122   // we want.
123   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
124                                * ElemsPerChunk);
125
126   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
127   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
128                      VecIdx);
129 }
130
131 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
132 /// instructions. This is used because creating CONCAT_VECTOR nodes of
133 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
134 /// large BUILD_VECTORS.
135 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
136                                    unsigned NumElems, SelectionDAG &DAG,
137                                    DebugLoc dl) {
138   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
139   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
140 }
141
142 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
143   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
144   bool is64Bit = Subtarget->is64Bit();
145
146   if (Subtarget->isTargetEnvMacho()) {
147     if (is64Bit)
148       return new X86_64MachoTargetObjectFile();
149     return new TargetLoweringObjectFileMachO();
150   }
151
152   if (Subtarget->isTargetLinux())
153     return new X86LinuxTargetObjectFile();
154   if (Subtarget->isTargetELF())
155     return new TargetLoweringObjectFileELF();
156   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
157     return new TargetLoweringObjectFileCOFF();
158   llvm_unreachable("unknown subtarget type");
159 }
160
161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
162   : TargetLowering(TM, createTLOF(TM)) {
163   Subtarget = &TM.getSubtarget<X86Subtarget>();
164   X86ScalarSSEf64 = Subtarget->hasSSE2();
165   X86ScalarSSEf32 = Subtarget->hasSSE1();
166   RegInfo = TM.getRegisterInfo();
167   TD = getDataLayout();
168
169   resetOperationActions();
170 }
171
172 void X86TargetLowering::resetOperationActions() {
173   const TargetMachine &TM = getTargetMachine();
174   static bool FirstTimeThrough = true;
175
176   // If none of the target options have changed, then we don't need to reset the
177   // operation actions.
178   if (!FirstTimeThrough && TO == TM.Options) return;
179
180   if (!FirstTimeThrough) {
181     // Reinitialize the actions.
182     initActions();
183     FirstTimeThrough = false;
184   }
185
186   TO = TM.Options;
187
188   // Set up the TargetLowering object.
189   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
190
191   // X86 is weird, it always uses i8 for shift amounts and setcc results.
192   setBooleanContents(ZeroOrOneBooleanContent);
193   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
194   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
195
196   // For 64-bit since we have so many registers use the ILP scheduler, for
197   // 32-bit code use the register pressure specific scheduling.
198   // For Atom, always use ILP scheduling.
199   if (Subtarget->isAtom())
200     setSchedulingPreference(Sched::ILP);
201   else if (Subtarget->is64Bit())
202     setSchedulingPreference(Sched::ILP);
203   else
204     setSchedulingPreference(Sched::RegPressure);
205   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
206
207   // Bypass expensive divides on Atom when compiling with O2
208   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
209     addBypassSlowDiv(32, 8);
210     if (Subtarget->is64Bit())
211       addBypassSlowDiv(64, 16);
212   }
213
214   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
215     // Setup Windows compiler runtime calls.
216     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
217     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
218     setLibcallName(RTLIB::SREM_I64, "_allrem");
219     setLibcallName(RTLIB::UREM_I64, "_aullrem");
220     setLibcallName(RTLIB::MUL_I64, "_allmul");
221     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
222     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
223     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
224     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
225     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
226
227     // The _ftol2 runtime function has an unusual calling conv, which
228     // is modeled by a special pseudo-instruction.
229     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
230     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
231     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
232     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
233   }
234
235   if (Subtarget->isTargetDarwin()) {
236     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
237     setUseUnderscoreSetJmp(false);
238     setUseUnderscoreLongJmp(false);
239   } else if (Subtarget->isTargetMingw()) {
240     // MS runtime is weird: it exports _setjmp, but longjmp!
241     setUseUnderscoreSetJmp(true);
242     setUseUnderscoreLongJmp(false);
243   } else {
244     setUseUnderscoreSetJmp(true);
245     setUseUnderscoreLongJmp(true);
246   }
247
248   // Set up the register classes.
249   addRegisterClass(MVT::i8, &X86::GR8RegClass);
250   addRegisterClass(MVT::i16, &X86::GR16RegClass);
251   addRegisterClass(MVT::i32, &X86::GR32RegClass);
252   if (Subtarget->is64Bit())
253     addRegisterClass(MVT::i64, &X86::GR64RegClass);
254
255   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
256
257   // We don't accept any truncstore of integer registers.
258   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
259   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
260   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
261   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
262   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
263   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
264
265   // SETOEQ and SETUNE require checking two conditions.
266   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
267   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
268   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
269   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
270   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
271   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
272
273   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
274   // operation.
275   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
276   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
277   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
278
279   if (Subtarget->is64Bit()) {
280     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
281     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
282   } else if (!TM.Options.UseSoftFloat) {
283     // We have an algorithm for SSE2->double, and we turn this into a
284     // 64-bit FILD followed by conditional FADD for other targets.
285     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
286     // We have an algorithm for SSE2, and we turn this into a 64-bit
287     // FILD for other targets.
288     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
289   }
290
291   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
294   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
295
296   if (!TM.Options.UseSoftFloat) {
297     // SSE has no i16 to fp conversion, only i32
298     if (X86ScalarSSEf32) {
299       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
300       // f32 and f64 cases are Legal, f80 case is not
301       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
302     } else {
303       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
304       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
305     }
306   } else {
307     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
308     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
309   }
310
311   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
312   // are Legal, f80 is custom lowered.
313   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
314   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
315
316   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
317   // this operation.
318   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
319   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
320
321   if (X86ScalarSSEf32) {
322     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
323     // f32 and f64 cases are Legal, f80 case is not
324     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
325   } else {
326     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
327     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
328   }
329
330   // Handle FP_TO_UINT by promoting the destination to a larger signed
331   // conversion.
332   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
333   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
334   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
335
336   if (Subtarget->is64Bit()) {
337     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
338     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
339   } else if (!TM.Options.UseSoftFloat) {
340     // Since AVX is a superset of SSE3, only check for SSE here.
341     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
342       // Expand FP_TO_UINT into a select.
343       // FIXME: We would like to use a Custom expander here eventually to do
344       // the optimal thing for SSE vs. the default expansion in the legalizer.
345       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
346     else
347       // With SSE3 we can use fisttpll to convert to a signed i64; without
348       // SSE, we're stuck with a fistpll.
349       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
350   }
351
352   if (isTargetFTOL()) {
353     // Use the _ftol2 runtime function, which has a pseudo-instruction
354     // to handle its weird calling convention.
355     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
356   }
357
358   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
359   if (!X86ScalarSSEf64) {
360     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
361     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
364       // Without SSE, i64->f64 goes through memory.
365       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
366     }
367   }
368
369   // Scalar integer divide and remainder are lowered to use operations that
370   // produce two results, to match the available instructions. This exposes
371   // the two-result form to trivial CSE, which is able to combine x/y and x%y
372   // into a single instruction.
373   //
374   // Scalar integer multiply-high is also lowered to use two-result
375   // operations, to match the available instructions. However, plain multiply
376   // (low) operations are left as Legal, as there are single-result
377   // instructions for this in x86. Using the two-result multiply instructions
378   // when both high and low results are needed must be arranged by dagcombine.
379   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
380     MVT VT = IntVTs[i];
381     setOperationAction(ISD::MULHS, VT, Expand);
382     setOperationAction(ISD::MULHU, VT, Expand);
383     setOperationAction(ISD::SDIV, VT, Expand);
384     setOperationAction(ISD::UDIV, VT, Expand);
385     setOperationAction(ISD::SREM, VT, Expand);
386     setOperationAction(ISD::UREM, VT, Expand);
387
388     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
389     setOperationAction(ISD::ADDC, VT, Custom);
390     setOperationAction(ISD::ADDE, VT, Custom);
391     setOperationAction(ISD::SUBC, VT, Custom);
392     setOperationAction(ISD::SUBE, VT, Custom);
393   }
394
395   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
396   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
397   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
398   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
399   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
400   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
401   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
402   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
403   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
404   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
405   if (Subtarget->is64Bit())
406     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
408   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
409   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
410   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
411   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
412   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
413   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
414   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
415
416   // Promote the i8 variants and force them on up to i32 which has a shorter
417   // encoding.
418   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
419   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
420   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
421   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
422   if (Subtarget->hasBMI()) {
423     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
424     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
425     if (Subtarget->is64Bit())
426       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
427   } else {
428     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
429     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
430     if (Subtarget->is64Bit())
431       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
432   }
433
434   if (Subtarget->hasLZCNT()) {
435     // When promoting the i8 variants, force them to i32 for a shorter
436     // encoding.
437     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
438     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
439     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
440     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
441     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
442     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
443     if (Subtarget->is64Bit())
444       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
445   } else {
446     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
447     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
448     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
449     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
450     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
451     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
452     if (Subtarget->is64Bit()) {
453       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
454       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
455     }
456   }
457
458   if (Subtarget->hasPOPCNT()) {
459     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
460   } else {
461     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
462     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
463     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
464     if (Subtarget->is64Bit())
465       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
466   }
467
468   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
469   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
470
471   // These should be promoted to a larger select which is supported.
472   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
473   // X86 wants to expand cmov itself.
474   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
475   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
476   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
477   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
478   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
479   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
480   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
481   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
482   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
483   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
484   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
485   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
486   if (Subtarget->is64Bit()) {
487     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
488     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
489   }
490   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
491   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
492   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
493   // support continuation, user-level threading, and etc.. As a result, no
494   // other SjLj exception interfaces are implemented and please don't build
495   // your own exception handling based on them.
496   // LLVM/Clang supports zero-cost DWARF exception handling.
497   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
498   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
499
500   // Darwin ABI issue.
501   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
502   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
503   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
504   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
505   if (Subtarget->is64Bit())
506     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
507   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
508   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
509   if (Subtarget->is64Bit()) {
510     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
511     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
512     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
513     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
514     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
515   }
516   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
517   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
518   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
519   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
520   if (Subtarget->is64Bit()) {
521     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
522     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
523     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
524   }
525
526   if (Subtarget->hasSSE1())
527     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
528
529   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
530
531   // Expand certain atomics
532   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
533     MVT VT = IntVTs[i];
534     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
535     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
536     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
537   }
538
539   if (!Subtarget->is64Bit()) {
540     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
541     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
542     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
543     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
544     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
545     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
546     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
547     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
548     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
549     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
550     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
551     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
552   }
553
554   if (Subtarget->hasCmpxchg16b()) {
555     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
556   }
557
558   // FIXME - use subtarget debug flags
559   if (!Subtarget->isTargetDarwin() &&
560       !Subtarget->isTargetELF() &&
561       !Subtarget->isTargetCygMing()) {
562     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
563   }
564
565   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
566   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
567   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
568   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
569   if (Subtarget->is64Bit()) {
570     setExceptionPointerRegister(X86::RAX);
571     setExceptionSelectorRegister(X86::RDX);
572   } else {
573     setExceptionPointerRegister(X86::EAX);
574     setExceptionSelectorRegister(X86::EDX);
575   }
576   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
577   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
578
579   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
580   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
581
582   setOperationAction(ISD::TRAP, MVT::Other, Legal);
583   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
584
585   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
586   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
587   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
588   if (Subtarget->is64Bit()) {
589     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
590     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
591   } else {
592     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
593     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
594   }
595
596   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
597   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
598
599   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
600     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
601                        MVT::i64 : MVT::i32, Custom);
602   else if (TM.Options.EnableSegmentedStacks)
603     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
604                        MVT::i64 : MVT::i32, Custom);
605   else
606     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
607                        MVT::i64 : MVT::i32, Expand);
608
609   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
610     // f32 and f64 use SSE.
611     // Set up the FP register classes.
612     addRegisterClass(MVT::f32, &X86::FR32RegClass);
613     addRegisterClass(MVT::f64, &X86::FR64RegClass);
614
615     // Use ANDPD to simulate FABS.
616     setOperationAction(ISD::FABS , MVT::f64, Custom);
617     setOperationAction(ISD::FABS , MVT::f32, Custom);
618
619     // Use XORP to simulate FNEG.
620     setOperationAction(ISD::FNEG , MVT::f64, Custom);
621     setOperationAction(ISD::FNEG , MVT::f32, Custom);
622
623     // Use ANDPD and ORPD to simulate FCOPYSIGN.
624     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
625     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
626
627     // Lower this to FGETSIGNx86 plus an AND.
628     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
629     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
630
631     // We don't support sin/cos/fmod
632     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
633     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
634     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
635     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
636     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
637     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
638
639     // Expand FP immediates into loads from the stack, except for the special
640     // cases we handle.
641     addLegalFPImmediate(APFloat(+0.0)); // xorpd
642     addLegalFPImmediate(APFloat(+0.0f)); // xorps
643   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
644     // Use SSE for f32, x87 for f64.
645     // Set up the FP register classes.
646     addRegisterClass(MVT::f32, &X86::FR32RegClass);
647     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
648
649     // Use ANDPS to simulate FABS.
650     setOperationAction(ISD::FABS , MVT::f32, Custom);
651
652     // Use XORP to simulate FNEG.
653     setOperationAction(ISD::FNEG , MVT::f32, Custom);
654
655     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
656
657     // Use ANDPS and ORPS to simulate FCOPYSIGN.
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660
661     // We don't support sin/cos/fmod
662     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
663     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
664     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
665
666     // Special cases we handle for FP constants.
667     addLegalFPImmediate(APFloat(+0.0f)); // xorps
668     addLegalFPImmediate(APFloat(+0.0)); // FLD0
669     addLegalFPImmediate(APFloat(+1.0)); // FLD1
670     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672
673     if (!TM.Options.UnsafeFPMath) {
674       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
675       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
676       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
677     }
678   } else if (!TM.Options.UseSoftFloat) {
679     // f32 and f64 in x87.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
683
684     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
685     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
686     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
687     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
688
689     if (!TM.Options.UnsafeFPMath) {
690       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
691       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
693       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
694       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
695       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
696     }
697     addLegalFPImmediate(APFloat(+0.0)); // FLD0
698     addLegalFPImmediate(APFloat(+1.0)); // FLD1
699     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
700     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
701     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
702     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
703     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
704     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
705   }
706
707   // We don't support FMA.
708   setOperationAction(ISD::FMA, MVT::f64, Expand);
709   setOperationAction(ISD::FMA, MVT::f32, Expand);
710
711   // Long double always uses X87.
712   if (!TM.Options.UseSoftFloat) {
713     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
714     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
716     {
717       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
718       addLegalFPImmediate(TmpFlt);  // FLD0
719       TmpFlt.changeSign();
720       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
721
722       bool ignored;
723       APFloat TmpFlt2(+1.0);
724       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
725                       &ignored);
726       addLegalFPImmediate(TmpFlt2);  // FLD1
727       TmpFlt2.changeSign();
728       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
729     }
730
731     if (!TM.Options.UnsafeFPMath) {
732       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
733       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
734       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
735     }
736
737     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
738     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
739     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
740     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
741     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
742     setOperationAction(ISD::FMA, MVT::f80, Expand);
743   }
744
745   // Always use a library call for pow.
746   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
747   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
748   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
749
750   setOperationAction(ISD::FLOG, MVT::f80, Expand);
751   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
752   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
753   setOperationAction(ISD::FEXP, MVT::f80, Expand);
754   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
755
756   // First set operation action for all vector types to either promote
757   // (for widening) or expand (for scalarization). Then we will selectively
758   // turn on ones that can be effectively codegen'd.
759   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
760            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
761     MVT VT = (MVT::SimpleValueType)i;
762     setOperationAction(ISD::ADD , VT, Expand);
763     setOperationAction(ISD::SUB , VT, Expand);
764     setOperationAction(ISD::FADD, VT, Expand);
765     setOperationAction(ISD::FNEG, VT, Expand);
766     setOperationAction(ISD::FSUB, VT, Expand);
767     setOperationAction(ISD::MUL , VT, Expand);
768     setOperationAction(ISD::FMUL, VT, Expand);
769     setOperationAction(ISD::SDIV, VT, Expand);
770     setOperationAction(ISD::UDIV, VT, Expand);
771     setOperationAction(ISD::FDIV, VT, Expand);
772     setOperationAction(ISD::SREM, VT, Expand);
773     setOperationAction(ISD::UREM, VT, Expand);
774     setOperationAction(ISD::LOAD, VT, Expand);
775     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
776     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
777     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
778     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
779     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
780     setOperationAction(ISD::FABS, VT, Expand);
781     setOperationAction(ISD::FSIN, VT, Expand);
782     setOperationAction(ISD::FSINCOS, VT, Expand);
783     setOperationAction(ISD::FCOS, VT, Expand);
784     setOperationAction(ISD::FSINCOS, VT, Expand);
785     setOperationAction(ISD::FREM, VT, Expand);
786     setOperationAction(ISD::FMA,  VT, Expand);
787     setOperationAction(ISD::FPOWI, VT, Expand);
788     setOperationAction(ISD::FSQRT, VT, Expand);
789     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
790     setOperationAction(ISD::FFLOOR, VT, Expand);
791     setOperationAction(ISD::FCEIL, VT, Expand);
792     setOperationAction(ISD::FTRUNC, VT, Expand);
793     setOperationAction(ISD::FRINT, VT, Expand);
794     setOperationAction(ISD::FNEARBYINT, VT, Expand);
795     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
796     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
797     setOperationAction(ISD::SDIVREM, VT, Expand);
798     setOperationAction(ISD::UDIVREM, VT, Expand);
799     setOperationAction(ISD::FPOW, VT, Expand);
800     setOperationAction(ISD::CTPOP, VT, Expand);
801     setOperationAction(ISD::CTTZ, VT, Expand);
802     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
803     setOperationAction(ISD::CTLZ, VT, Expand);
804     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
805     setOperationAction(ISD::SHL, VT, Expand);
806     setOperationAction(ISD::SRA, VT, Expand);
807     setOperationAction(ISD::SRL, VT, Expand);
808     setOperationAction(ISD::ROTL, VT, Expand);
809     setOperationAction(ISD::ROTR, VT, Expand);
810     setOperationAction(ISD::BSWAP, VT, Expand);
811     setOperationAction(ISD::SETCC, VT, Expand);
812     setOperationAction(ISD::FLOG, VT, Expand);
813     setOperationAction(ISD::FLOG2, VT, Expand);
814     setOperationAction(ISD::FLOG10, VT, Expand);
815     setOperationAction(ISD::FEXP, VT, Expand);
816     setOperationAction(ISD::FEXP2, VT, Expand);
817     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
818     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
819     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
820     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
821     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
822     setOperationAction(ISD::TRUNCATE, VT, Expand);
823     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
824     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
825     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
826     setOperationAction(ISD::VSELECT, VT, Expand);
827     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
828              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
829       setTruncStoreAction(VT,
830                           (MVT::SimpleValueType)InnerVT, Expand);
831     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
832     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
833     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
834   }
835
836   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
837   // with -msoft-float, disable use of MMX as well.
838   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
839     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
840     // No operations on x86mmx supported, everything uses intrinsics.
841   }
842
843   // MMX-sized vectors (other than x86mmx) are expected to be expanded
844   // into smaller operations.
845   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
846   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
847   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
848   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
849   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
850   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
851   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
852   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
853   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
854   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
855   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
856   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
857   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
858   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
859   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
860   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
861   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
862   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
863   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
864   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
865   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
866   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
867   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
868   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
869   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
870   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
871   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
872   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
873   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
874
875   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
876     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
877
878     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
879     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
880     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
881     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
882     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
883     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
884     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
885     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
886     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
888     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
889     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
890   }
891
892   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
893     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
894
895     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
896     // registers cannot be used even for integer operations.
897     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
898     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
899     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
900     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
901
902     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
903     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
904     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
905     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
906     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
907     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
908     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
909     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
910     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
911     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
912     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
913     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
919     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
920
921     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
922     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
923     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
924     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
925
926     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
927     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
928     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
929     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
930     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
931
932     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
933     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
934       MVT VT = (MVT::SimpleValueType)i;
935       // Do not attempt to custom lower non-power-of-2 vectors
936       if (!isPowerOf2_32(VT.getVectorNumElements()))
937         continue;
938       // Do not attempt to custom lower non-128-bit vectors
939       if (!VT.is128BitVector())
940         continue;
941       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
942       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
943       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
944     }
945
946     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
947     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
948     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
949     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
950     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
951     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
952
953     if (Subtarget->is64Bit()) {
954       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
955       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
956     }
957
958     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
959     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
960       MVT VT = (MVT::SimpleValueType)i;
961
962       // Do not attempt to promote non-128-bit vectors
963       if (!VT.is128BitVector())
964         continue;
965
966       setOperationAction(ISD::AND,    VT, Promote);
967       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
968       setOperationAction(ISD::OR,     VT, Promote);
969       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
970       setOperationAction(ISD::XOR,    VT, Promote);
971       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
972       setOperationAction(ISD::LOAD,   VT, Promote);
973       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
974       setOperationAction(ISD::SELECT, VT, Promote);
975       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
976     }
977
978     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
979
980     // Custom lower v2i64 and v2f64 selects.
981     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
983     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
984     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
985
986     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
987     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
988
989     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
990     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
991     // As there is no 64-bit GPR available, we need build a special custom
992     // sequence to convert from v2i32 to v2f32.
993     if (!Subtarget->is64Bit())
994       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
995
996     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
997     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
998
999     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1000   }
1001
1002   if (Subtarget->hasSSE41()) {
1003     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1004     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1005     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1006     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1007     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1008     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1009     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1010     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1011     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1012     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1013
1014     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1015     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1016     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1017     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1018     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1019     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1020     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1021     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1022     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1023     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1024
1025     // FIXME: Do we need to handle scalar-to-vector here?
1026     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1027
1028     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1029     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1030     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1031     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1032     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1033
1034     // i8 and i16 vectors are custom , because the source register and source
1035     // source memory operand types are not the same width.  f32 vectors are
1036     // custom since the immediate controlling the insert encodes additional
1037     // information.
1038     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1039     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1040     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1041     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1042
1043     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1044     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1045     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1046     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1047
1048     // FIXME: these should be Legal but thats only for the case where
1049     // the index is constant.  For now custom expand to deal with that.
1050     if (Subtarget->is64Bit()) {
1051       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1052       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1053     }
1054   }
1055
1056   if (Subtarget->hasSSE2()) {
1057     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1058     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1059
1060     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1061     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1062
1063     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1064     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1065
1066     // In the customized shift lowering, the legal cases in AVX2 will be
1067     // recognized.
1068     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1069     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1070
1071     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1072     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1073
1074     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1075
1076     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1077     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1078   }
1079
1080   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1081     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1082     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1083     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1084     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1085     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1086     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1087
1088     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1089     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1090     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1091
1092     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1093     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1094     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1095     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1096     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1097     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1098     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1099     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1100     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1101     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1102     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1103     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1104
1105     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1106     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1107     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1108     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1109     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1110     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1111     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1112     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1113     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1114     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1115     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1116     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1117
1118     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1119     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1120
1121     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1122
1123     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1124     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1125     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1126     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1127
1128     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1129     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1130     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1131
1132     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1133
1134     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1135     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1136
1137     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1138     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1139
1140     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1141     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1142
1143     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1144
1145     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1146     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1147     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1148     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1149
1150     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1151     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1152     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1153
1154     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1155     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1156     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1157     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1158
1159     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1160     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1161     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1162     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1163     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1164     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1165
1166     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1167       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1169       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1170       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1171       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1172       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1173     }
1174
1175     if (Subtarget->hasInt256()) {
1176       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1178       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1179       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1180
1181       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1183       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1184       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1185
1186       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1187       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1188       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1189       // Don't lower v32i8 because there is no 128-bit byte mul
1190
1191       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1192
1193       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1194     } else {
1195       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1197       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1198       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1199
1200       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1202       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1203       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1204
1205       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1206       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1207       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1208       // Don't lower v32i8 because there is no 128-bit byte mul
1209     }
1210
1211     // In the customized shift lowering, the legal cases in AVX2 will be
1212     // recognized.
1213     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1214     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1215
1216     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1217     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1218
1219     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1220
1221     // Custom lower several nodes for 256-bit types.
1222     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1223              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1224       MVT VT = (MVT::SimpleValueType)i;
1225
1226       // Extract subvector is special because the value type
1227       // (result) is 128-bit but the source is 256-bit wide.
1228       if (VT.is128BitVector())
1229         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1230
1231       // Do not attempt to custom lower other non-256-bit vectors
1232       if (!VT.is256BitVector())
1233         continue;
1234
1235       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1236       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1237       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1238       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1239       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1240       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1241       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1242     }
1243
1244     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1245     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1246       MVT VT = (MVT::SimpleValueType)i;
1247
1248       // Do not attempt to promote non-256-bit vectors
1249       if (!VT.is256BitVector())
1250         continue;
1251
1252       setOperationAction(ISD::AND,    VT, Promote);
1253       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1254       setOperationAction(ISD::OR,     VT, Promote);
1255       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1256       setOperationAction(ISD::XOR,    VT, Promote);
1257       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1258       setOperationAction(ISD::LOAD,   VT, Promote);
1259       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1260       setOperationAction(ISD::SELECT, VT, Promote);
1261       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1262     }
1263   }
1264
1265   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1266   // of this type with custom code.
1267   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1268            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1269     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1270                        Custom);
1271   }
1272
1273   // We want to custom lower some of our intrinsics.
1274   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1275   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1276
1277   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1278   // handle type legalization for these operations here.
1279   //
1280   // FIXME: We really should do custom legalization for addition and
1281   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1282   // than generic legalization for 64-bit multiplication-with-overflow, though.
1283   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1284     // Add/Sub/Mul with overflow operations are custom lowered.
1285     MVT VT = IntVTs[i];
1286     setOperationAction(ISD::SADDO, VT, Custom);
1287     setOperationAction(ISD::UADDO, VT, Custom);
1288     setOperationAction(ISD::SSUBO, VT, Custom);
1289     setOperationAction(ISD::USUBO, VT, Custom);
1290     setOperationAction(ISD::SMULO, VT, Custom);
1291     setOperationAction(ISD::UMULO, VT, Custom);
1292   }
1293
1294   // There are no 8-bit 3-address imul/mul instructions
1295   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1296   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1297
1298   if (!Subtarget->is64Bit()) {
1299     // These libcalls are not available in 32-bit.
1300     setLibcallName(RTLIB::SHL_I128, 0);
1301     setLibcallName(RTLIB::SRL_I128, 0);
1302     setLibcallName(RTLIB::SRA_I128, 0);
1303   }
1304
1305   // Combine sin / cos into one node or libcall if possible.
1306   if (Subtarget->hasSinCos()) {
1307     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1308     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1309     if (Subtarget->isTargetDarwin()) {
1310       // For MacOSX, we don't want to the normal expansion of a libcall to
1311       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1312       // traffic.
1313       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1314       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1315     }
1316   }
1317
1318   // We have target-specific dag combine patterns for the following nodes:
1319   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1320   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1321   setTargetDAGCombine(ISD::VSELECT);
1322   setTargetDAGCombine(ISD::SELECT);
1323   setTargetDAGCombine(ISD::SHL);
1324   setTargetDAGCombine(ISD::SRA);
1325   setTargetDAGCombine(ISD::SRL);
1326   setTargetDAGCombine(ISD::OR);
1327   setTargetDAGCombine(ISD::AND);
1328   setTargetDAGCombine(ISD::ADD);
1329   setTargetDAGCombine(ISD::FADD);
1330   setTargetDAGCombine(ISD::FSUB);
1331   setTargetDAGCombine(ISD::FMA);
1332   setTargetDAGCombine(ISD::SUB);
1333   setTargetDAGCombine(ISD::LOAD);
1334   setTargetDAGCombine(ISD::STORE);
1335   setTargetDAGCombine(ISD::ZERO_EXTEND);
1336   setTargetDAGCombine(ISD::ANY_EXTEND);
1337   setTargetDAGCombine(ISD::SIGN_EXTEND);
1338   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1339   setTargetDAGCombine(ISD::TRUNCATE);
1340   setTargetDAGCombine(ISD::SINT_TO_FP);
1341   setTargetDAGCombine(ISD::SETCC);
1342   if (Subtarget->is64Bit())
1343     setTargetDAGCombine(ISD::MUL);
1344   setTargetDAGCombine(ISD::XOR);
1345
1346   computeRegisterProperties();
1347
1348   // On Darwin, -Os means optimize for size without hurting performance,
1349   // do not reduce the limit.
1350   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1351   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1352   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1353   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1354   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1355   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1356   setPrefLoopAlignment(4); // 2^4 bytes.
1357
1358   // Predictable cmov don't hurt on atom because it's in-order.
1359   PredictableSelectIsExpensive = !Subtarget->isAtom();
1360
1361   setPrefFunctionAlignment(4); // 2^4 bytes.
1362 }
1363
1364 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1365   if (!VT.isVector()) return MVT::i8;
1366   return VT.changeVectorElementTypeToInteger();
1367 }
1368
1369 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1370 /// the desired ByVal argument alignment.
1371 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1372   if (MaxAlign == 16)
1373     return;
1374   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1375     if (VTy->getBitWidth() == 128)
1376       MaxAlign = 16;
1377   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1378     unsigned EltAlign = 0;
1379     getMaxByValAlign(ATy->getElementType(), EltAlign);
1380     if (EltAlign > MaxAlign)
1381       MaxAlign = EltAlign;
1382   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1383     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1384       unsigned EltAlign = 0;
1385       getMaxByValAlign(STy->getElementType(i), EltAlign);
1386       if (EltAlign > MaxAlign)
1387         MaxAlign = EltAlign;
1388       if (MaxAlign == 16)
1389         break;
1390     }
1391   }
1392 }
1393
1394 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1395 /// function arguments in the caller parameter area. For X86, aggregates
1396 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1397 /// are at 4-byte boundaries.
1398 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1399   if (Subtarget->is64Bit()) {
1400     // Max of 8 and alignment of type.
1401     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1402     if (TyAlign > 8)
1403       return TyAlign;
1404     return 8;
1405   }
1406
1407   unsigned Align = 4;
1408   if (Subtarget->hasSSE1())
1409     getMaxByValAlign(Ty, Align);
1410   return Align;
1411 }
1412
1413 /// getOptimalMemOpType - Returns the target specific optimal type for load
1414 /// and store operations as a result of memset, memcpy, and memmove
1415 /// lowering. If DstAlign is zero that means it's safe to destination
1416 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1417 /// means there isn't a need to check it against alignment requirement,
1418 /// probably because the source does not need to be loaded. If 'IsMemset' is
1419 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1420 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1421 /// source is constant so it does not need to be loaded.
1422 /// It returns EVT::Other if the type should be determined using generic
1423 /// target-independent logic.
1424 EVT
1425 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1426                                        unsigned DstAlign, unsigned SrcAlign,
1427                                        bool IsMemset, bool ZeroMemset,
1428                                        bool MemcpyStrSrc,
1429                                        MachineFunction &MF) const {
1430   const Function *F = MF.getFunction();
1431   if ((!IsMemset || ZeroMemset) &&
1432       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1433                                        Attribute::NoImplicitFloat)) {
1434     if (Size >= 16 &&
1435         (Subtarget->isUnalignedMemAccessFast() ||
1436          ((DstAlign == 0 || DstAlign >= 16) &&
1437           (SrcAlign == 0 || SrcAlign >= 16)))) {
1438       if (Size >= 32) {
1439         if (Subtarget->hasInt256())
1440           return MVT::v8i32;
1441         if (Subtarget->hasFp256())
1442           return MVT::v8f32;
1443       }
1444       if (Subtarget->hasSSE2())
1445         return MVT::v4i32;
1446       if (Subtarget->hasSSE1())
1447         return MVT::v4f32;
1448     } else if (!MemcpyStrSrc && Size >= 8 &&
1449                !Subtarget->is64Bit() &&
1450                Subtarget->hasSSE2()) {
1451       // Do not use f64 to lower memcpy if source is string constant. It's
1452       // better to use i32 to avoid the loads.
1453       return MVT::f64;
1454     }
1455   }
1456   if (Subtarget->is64Bit() && Size >= 8)
1457     return MVT::i64;
1458   return MVT::i32;
1459 }
1460
1461 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1462   if (VT == MVT::f32)
1463     return X86ScalarSSEf32;
1464   else if (VT == MVT::f64)
1465     return X86ScalarSSEf64;
1466   return true;
1467 }
1468
1469 bool
1470 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1471   if (Fast)
1472     *Fast = Subtarget->isUnalignedMemAccessFast();
1473   return true;
1474 }
1475
1476 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1477 /// current function.  The returned value is a member of the
1478 /// MachineJumpTableInfo::JTEntryKind enum.
1479 unsigned X86TargetLowering::getJumpTableEncoding() const {
1480   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1481   // symbol.
1482   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1483       Subtarget->isPICStyleGOT())
1484     return MachineJumpTableInfo::EK_Custom32;
1485
1486   // Otherwise, use the normal jump table encoding heuristics.
1487   return TargetLowering::getJumpTableEncoding();
1488 }
1489
1490 const MCExpr *
1491 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1492                                              const MachineBasicBlock *MBB,
1493                                              unsigned uid,MCContext &Ctx) const{
1494   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1495          Subtarget->isPICStyleGOT());
1496   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1497   // entries.
1498   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1499                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1500 }
1501
1502 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1503 /// jumptable.
1504 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1505                                                     SelectionDAG &DAG) const {
1506   if (!Subtarget->is64Bit())
1507     // This doesn't have DebugLoc associated with it, but is not really the
1508     // same as a Register.
1509     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1510   return Table;
1511 }
1512
1513 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1514 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1515 /// MCExpr.
1516 const MCExpr *X86TargetLowering::
1517 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1518                              MCContext &Ctx) const {
1519   // X86-64 uses RIP relative addressing based on the jump table label.
1520   if (Subtarget->isPICStyleRIPRel())
1521     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1522
1523   // Otherwise, the reference is relative to the PIC base.
1524   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1525 }
1526
1527 // FIXME: Why this routine is here? Move to RegInfo!
1528 std::pair<const TargetRegisterClass*, uint8_t>
1529 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1530   const TargetRegisterClass *RRC = 0;
1531   uint8_t Cost = 1;
1532   switch (VT.SimpleTy) {
1533   default:
1534     return TargetLowering::findRepresentativeClass(VT);
1535   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1536     RRC = Subtarget->is64Bit() ?
1537       (const TargetRegisterClass*)&X86::GR64RegClass :
1538       (const TargetRegisterClass*)&X86::GR32RegClass;
1539     break;
1540   case MVT::x86mmx:
1541     RRC = &X86::VR64RegClass;
1542     break;
1543   case MVT::f32: case MVT::f64:
1544   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1545   case MVT::v4f32: case MVT::v2f64:
1546   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1547   case MVT::v4f64:
1548     RRC = &X86::VR128RegClass;
1549     break;
1550   }
1551   return std::make_pair(RRC, Cost);
1552 }
1553
1554 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1555                                                unsigned &Offset) const {
1556   if (!Subtarget->isTargetLinux())
1557     return false;
1558
1559   if (Subtarget->is64Bit()) {
1560     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1561     Offset = 0x28;
1562     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1563       AddressSpace = 256;
1564     else
1565       AddressSpace = 257;
1566   } else {
1567     // %gs:0x14 on i386
1568     Offset = 0x14;
1569     AddressSpace = 256;
1570   }
1571   return true;
1572 }
1573
1574 //===----------------------------------------------------------------------===//
1575 //               Return Value Calling Convention Implementation
1576 //===----------------------------------------------------------------------===//
1577
1578 #include "X86GenCallingConv.inc"
1579
1580 bool
1581 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1582                                   MachineFunction &MF, bool isVarArg,
1583                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1584                         LLVMContext &Context) const {
1585   SmallVector<CCValAssign, 16> RVLocs;
1586   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1587                  RVLocs, Context);
1588   return CCInfo.CheckReturn(Outs, RetCC_X86);
1589 }
1590
1591 SDValue
1592 X86TargetLowering::LowerReturn(SDValue Chain,
1593                                CallingConv::ID CallConv, bool isVarArg,
1594                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1595                                const SmallVectorImpl<SDValue> &OutVals,
1596                                DebugLoc dl, SelectionDAG &DAG) const {
1597   MachineFunction &MF = DAG.getMachineFunction();
1598   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1599
1600   SmallVector<CCValAssign, 16> RVLocs;
1601   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1602                  RVLocs, *DAG.getContext());
1603   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1604
1605   SDValue Flag;
1606   SmallVector<SDValue, 6> RetOps;
1607   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1608   // Operand #1 = Bytes To Pop
1609   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1610                    MVT::i16));
1611
1612   // Copy the result values into the output registers.
1613   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1614     CCValAssign &VA = RVLocs[i];
1615     assert(VA.isRegLoc() && "Can only return in registers!");
1616     SDValue ValToCopy = OutVals[i];
1617     EVT ValVT = ValToCopy.getValueType();
1618
1619     // Promote values to the appropriate types
1620     if (VA.getLocInfo() == CCValAssign::SExt)
1621       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1622     else if (VA.getLocInfo() == CCValAssign::ZExt)
1623       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1624     else if (VA.getLocInfo() == CCValAssign::AExt)
1625       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1626     else if (VA.getLocInfo() == CCValAssign::BCvt)
1627       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1628
1629     // If this is x86-64, and we disabled SSE, we can't return FP values,
1630     // or SSE or MMX vectors.
1631     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1632          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1633           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1634       report_fatal_error("SSE register return with SSE disabled");
1635     }
1636     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1637     // llvm-gcc has never done it right and no one has noticed, so this
1638     // should be OK for now.
1639     if (ValVT == MVT::f64 &&
1640         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1641       report_fatal_error("SSE2 register return with SSE2 disabled");
1642
1643     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1644     // the RET instruction and handled by the FP Stackifier.
1645     if (VA.getLocReg() == X86::ST0 ||
1646         VA.getLocReg() == X86::ST1) {
1647       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1648       // change the value to the FP stack register class.
1649       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1650         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1651       RetOps.push_back(ValToCopy);
1652       // Don't emit a copytoreg.
1653       continue;
1654     }
1655
1656     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1657     // which is returned in RAX / RDX.
1658     if (Subtarget->is64Bit()) {
1659       if (ValVT == MVT::x86mmx) {
1660         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1661           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1662           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1663                                   ValToCopy);
1664           // If we don't have SSE2 available, convert to v4f32 so the generated
1665           // register is legal.
1666           if (!Subtarget->hasSSE2())
1667             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1668         }
1669       }
1670     }
1671
1672     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1673     Flag = Chain.getValue(1);
1674     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1675   }
1676
1677   // The x86-64 ABIs require that for returning structs by value we copy
1678   // the sret argument into %rax/%eax (depending on ABI) for the return.
1679   // Win32 requires us to put the sret argument to %eax as well.
1680   // We saved the argument into a virtual register in the entry block,
1681   // so now we copy the value out and into %rax/%eax.
1682   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1683       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1684     MachineFunction &MF = DAG.getMachineFunction();
1685     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1686     unsigned Reg = FuncInfo->getSRetReturnReg();
1687     assert(Reg &&
1688            "SRetReturnReg should have been set in LowerFormalArguments().");
1689     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1690
1691     unsigned RetValReg
1692         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1693           X86::RAX : X86::EAX;
1694     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1695     Flag = Chain.getValue(1);
1696
1697     // RAX/EAX now acts like a return value.
1698     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1699   }
1700
1701   RetOps[0] = Chain;  // Update chain.
1702
1703   // Add the flag if we have it.
1704   if (Flag.getNode())
1705     RetOps.push_back(Flag);
1706
1707   return DAG.getNode(X86ISD::RET_FLAG, dl,
1708                      MVT::Other, &RetOps[0], RetOps.size());
1709 }
1710
1711 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1712   if (N->getNumValues() != 1)
1713     return false;
1714   if (!N->hasNUsesOfValue(1, 0))
1715     return false;
1716
1717   SDValue TCChain = Chain;
1718   SDNode *Copy = *N->use_begin();
1719   if (Copy->getOpcode() == ISD::CopyToReg) {
1720     // If the copy has a glue operand, we conservatively assume it isn't safe to
1721     // perform a tail call.
1722     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1723       return false;
1724     TCChain = Copy->getOperand(0);
1725   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1726     return false;
1727
1728   bool HasRet = false;
1729   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1730        UI != UE; ++UI) {
1731     if (UI->getOpcode() != X86ISD::RET_FLAG)
1732       return false;
1733     HasRet = true;
1734   }
1735
1736   if (!HasRet)
1737     return false;
1738
1739   Chain = TCChain;
1740   return true;
1741 }
1742
1743 MVT
1744 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1745                                             ISD::NodeType ExtendKind) const {
1746   MVT ReturnMVT;
1747   // TODO: Is this also valid on 32-bit?
1748   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1749     ReturnMVT = MVT::i8;
1750   else
1751     ReturnMVT = MVT::i32;
1752
1753   MVT MinVT = getRegisterType(ReturnMVT);
1754   return VT.bitsLT(MinVT) ? MinVT : VT;
1755 }
1756
1757 /// LowerCallResult - Lower the result values of a call into the
1758 /// appropriate copies out of appropriate physical registers.
1759 ///
1760 SDValue
1761 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1762                                    CallingConv::ID CallConv, bool isVarArg,
1763                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1764                                    DebugLoc dl, SelectionDAG &DAG,
1765                                    SmallVectorImpl<SDValue> &InVals) const {
1766
1767   // Assign locations to each value returned by this call.
1768   SmallVector<CCValAssign, 16> RVLocs;
1769   bool Is64Bit = Subtarget->is64Bit();
1770   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1771                  getTargetMachine(), RVLocs, *DAG.getContext());
1772   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1773
1774   // Copy all of the result registers out of their specified physreg.
1775   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1776     CCValAssign &VA = RVLocs[i];
1777     EVT CopyVT = VA.getValVT();
1778
1779     // If this is x86-64, and we disabled SSE, we can't return FP values
1780     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1781         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1782       report_fatal_error("SSE register return with SSE disabled");
1783     }
1784
1785     SDValue Val;
1786
1787     // If this is a call to a function that returns an fp value on the floating
1788     // point stack, we must guarantee the value is popped from the stack, so
1789     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1790     // if the return value is not used. We use the FpPOP_RETVAL instruction
1791     // instead.
1792     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1793       // If we prefer to use the value in xmm registers, copy it out as f80 and
1794       // use a truncate to move it from fp stack reg to xmm reg.
1795       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1796       SDValue Ops[] = { Chain, InFlag };
1797       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1798                                          MVT::Other, MVT::Glue, Ops), 1);
1799       Val = Chain.getValue(0);
1800
1801       // Round the f80 to the right size, which also moves it to the appropriate
1802       // xmm register.
1803       if (CopyVT != VA.getValVT())
1804         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1805                           // This truncation won't change the value.
1806                           DAG.getIntPtrConstant(1));
1807     } else {
1808       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1809                                  CopyVT, InFlag).getValue(1);
1810       Val = Chain.getValue(0);
1811     }
1812     InFlag = Chain.getValue(2);
1813     InVals.push_back(Val);
1814   }
1815
1816   return Chain;
1817 }
1818
1819 //===----------------------------------------------------------------------===//
1820 //                C & StdCall & Fast Calling Convention implementation
1821 //===----------------------------------------------------------------------===//
1822 //  StdCall calling convention seems to be standard for many Windows' API
1823 //  routines and around. It differs from C calling convention just a little:
1824 //  callee should clean up the stack, not caller. Symbols should be also
1825 //  decorated in some fancy way :) It doesn't support any vector arguments.
1826 //  For info on fast calling convention see Fast Calling Convention (tail call)
1827 //  implementation LowerX86_32FastCCCallTo.
1828
1829 /// CallIsStructReturn - Determines whether a call uses struct return
1830 /// semantics.
1831 enum StructReturnType {
1832   NotStructReturn,
1833   RegStructReturn,
1834   StackStructReturn
1835 };
1836 static StructReturnType
1837 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1838   if (Outs.empty())
1839     return NotStructReturn;
1840
1841   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1842   if (!Flags.isSRet())
1843     return NotStructReturn;
1844   if (Flags.isInReg())
1845     return RegStructReturn;
1846   return StackStructReturn;
1847 }
1848
1849 /// ArgsAreStructReturn - Determines whether a function uses struct
1850 /// return semantics.
1851 static StructReturnType
1852 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1853   if (Ins.empty())
1854     return NotStructReturn;
1855
1856   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1857   if (!Flags.isSRet())
1858     return NotStructReturn;
1859   if (Flags.isInReg())
1860     return RegStructReturn;
1861   return StackStructReturn;
1862 }
1863
1864 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1865 /// by "Src" to address "Dst" with size and alignment information specified by
1866 /// the specific parameter attribute. The copy will be passed as a byval
1867 /// function parameter.
1868 static SDValue
1869 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1870                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1871                           DebugLoc dl) {
1872   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1873
1874   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1875                        /*isVolatile*/false, /*AlwaysInline=*/true,
1876                        MachinePointerInfo(), MachinePointerInfo());
1877 }
1878
1879 /// IsTailCallConvention - Return true if the calling convention is one that
1880 /// supports tail call optimization.
1881 static bool IsTailCallConvention(CallingConv::ID CC) {
1882   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1883           CC == CallingConv::HiPE);
1884 }
1885
1886 /// \brief Return true if the calling convention is a C calling convention.
1887 static bool IsCCallConvention(CallingConv::ID CC) {
1888   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
1889           CC == CallingConv::X86_64_SysV);
1890 }
1891
1892 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1893   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1894     return false;
1895
1896   CallSite CS(CI);
1897   CallingConv::ID CalleeCC = CS.getCallingConv();
1898   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
1899     return false;
1900
1901   return true;
1902 }
1903
1904 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1905 /// a tailcall target by changing its ABI.
1906 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1907                                    bool GuaranteedTailCallOpt) {
1908   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1909 }
1910
1911 SDValue
1912 X86TargetLowering::LowerMemArgument(SDValue Chain,
1913                                     CallingConv::ID CallConv,
1914                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1915                                     DebugLoc dl, SelectionDAG &DAG,
1916                                     const CCValAssign &VA,
1917                                     MachineFrameInfo *MFI,
1918                                     unsigned i) const {
1919   // Create the nodes corresponding to a load from this parameter slot.
1920   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1921   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1922                               getTargetMachine().Options.GuaranteedTailCallOpt);
1923   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1924   EVT ValVT;
1925
1926   // If value is passed by pointer we have address passed instead of the value
1927   // itself.
1928   if (VA.getLocInfo() == CCValAssign::Indirect)
1929     ValVT = VA.getLocVT();
1930   else
1931     ValVT = VA.getValVT();
1932
1933   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1934   // changed with more analysis.
1935   // In case of tail call optimization mark all arguments mutable. Since they
1936   // could be overwritten by lowering of arguments in case of a tail call.
1937   if (Flags.isByVal()) {
1938     unsigned Bytes = Flags.getByValSize();
1939     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1940     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1941     return DAG.getFrameIndex(FI, getPointerTy());
1942   } else {
1943     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1944                                     VA.getLocMemOffset(), isImmutable);
1945     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1946     return DAG.getLoad(ValVT, dl, Chain, FIN,
1947                        MachinePointerInfo::getFixedStack(FI),
1948                        false, false, false, 0);
1949   }
1950 }
1951
1952 SDValue
1953 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1954                                         CallingConv::ID CallConv,
1955                                         bool isVarArg,
1956                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1957                                         DebugLoc dl,
1958                                         SelectionDAG &DAG,
1959                                         SmallVectorImpl<SDValue> &InVals)
1960                                           const {
1961   MachineFunction &MF = DAG.getMachineFunction();
1962   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1963
1964   const Function* Fn = MF.getFunction();
1965   if (Fn->hasExternalLinkage() &&
1966       Subtarget->isTargetCygMing() &&
1967       Fn->getName() == "main")
1968     FuncInfo->setForceFramePointer(true);
1969
1970   MachineFrameInfo *MFI = MF.getFrameInfo();
1971   bool Is64Bit = Subtarget->is64Bit();
1972   bool IsWindows = Subtarget->isTargetWindows();
1973   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
1974
1975   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1976          "Var args not supported with calling convention fastcc, ghc or hipe");
1977
1978   // Assign locations to all of the incoming arguments.
1979   SmallVector<CCValAssign, 16> ArgLocs;
1980   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1981                  ArgLocs, *DAG.getContext());
1982
1983   // Allocate shadow area for Win64
1984   if (IsWin64)
1985     CCInfo.AllocateStack(32, 8);
1986
1987   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1988
1989   unsigned LastVal = ~0U;
1990   SDValue ArgValue;
1991   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1992     CCValAssign &VA = ArgLocs[i];
1993     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1994     // places.
1995     assert(VA.getValNo() != LastVal &&
1996            "Don't support value assigned to multiple locs yet");
1997     (void)LastVal;
1998     LastVal = VA.getValNo();
1999
2000     if (VA.isRegLoc()) {
2001       EVT RegVT = VA.getLocVT();
2002       const TargetRegisterClass *RC;
2003       if (RegVT == MVT::i32)
2004         RC = &X86::GR32RegClass;
2005       else if (Is64Bit && RegVT == MVT::i64)
2006         RC = &X86::GR64RegClass;
2007       else if (RegVT == MVT::f32)
2008         RC = &X86::FR32RegClass;
2009       else if (RegVT == MVT::f64)
2010         RC = &X86::FR64RegClass;
2011       else if (RegVT.is256BitVector())
2012         RC = &X86::VR256RegClass;
2013       else if (RegVT.is128BitVector())
2014         RC = &X86::VR128RegClass;
2015       else if (RegVT == MVT::x86mmx)
2016         RC = &X86::VR64RegClass;
2017       else
2018         llvm_unreachable("Unknown argument type!");
2019
2020       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2021       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2022
2023       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2024       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2025       // right size.
2026       if (VA.getLocInfo() == CCValAssign::SExt)
2027         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2028                                DAG.getValueType(VA.getValVT()));
2029       else if (VA.getLocInfo() == CCValAssign::ZExt)
2030         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2031                                DAG.getValueType(VA.getValVT()));
2032       else if (VA.getLocInfo() == CCValAssign::BCvt)
2033         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2034
2035       if (VA.isExtInLoc()) {
2036         // Handle MMX values passed in XMM regs.
2037         if (RegVT.isVector())
2038           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2039         else
2040           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2041       }
2042     } else {
2043       assert(VA.isMemLoc());
2044       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2045     }
2046
2047     // If value is passed via pointer - do a load.
2048     if (VA.getLocInfo() == CCValAssign::Indirect)
2049       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2050                              MachinePointerInfo(), false, false, false, 0);
2051
2052     InVals.push_back(ArgValue);
2053   }
2054
2055   // The x86-64 ABIs require that for returning structs by value we copy
2056   // the sret argument into %rax/%eax (depending on ABI) for the return.
2057   // Win32 requires us to put the sret argument to %eax as well.
2058   // Save the argument into a virtual register so that we can access it
2059   // from the return points.
2060   if (MF.getFunction()->hasStructRetAttr() &&
2061       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2062     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2063     unsigned Reg = FuncInfo->getSRetReturnReg();
2064     if (!Reg) {
2065       MVT PtrTy = getPointerTy();
2066       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2067       FuncInfo->setSRetReturnReg(Reg);
2068     }
2069     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2070     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2071   }
2072
2073   unsigned StackSize = CCInfo.getNextStackOffset();
2074   // Align stack specially for tail calls.
2075   if (FuncIsMadeTailCallSafe(CallConv,
2076                              MF.getTarget().Options.GuaranteedTailCallOpt))
2077     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2078
2079   // If the function takes variable number of arguments, make a frame index for
2080   // the start of the first vararg value... for expansion of llvm.va_start.
2081   if (isVarArg) {
2082     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2083                     CallConv != CallingConv::X86_ThisCall)) {
2084       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2085     }
2086     if (Is64Bit) {
2087       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2088
2089       // FIXME: We should really autogenerate these arrays
2090       static const uint16_t GPR64ArgRegsWin64[] = {
2091         X86::RCX, X86::RDX, X86::R8,  X86::R9
2092       };
2093       static const uint16_t GPR64ArgRegs64Bit[] = {
2094         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2095       };
2096       static const uint16_t XMMArgRegs64Bit[] = {
2097         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2098         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2099       };
2100       const uint16_t *GPR64ArgRegs;
2101       unsigned NumXMMRegs = 0;
2102
2103       if (IsWin64) {
2104         // The XMM registers which might contain var arg parameters are shadowed
2105         // in their paired GPR.  So we only need to save the GPR to their home
2106         // slots.
2107         TotalNumIntRegs = 4;
2108         GPR64ArgRegs = GPR64ArgRegsWin64;
2109       } else {
2110         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2111         GPR64ArgRegs = GPR64ArgRegs64Bit;
2112
2113         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2114                                                 TotalNumXMMRegs);
2115       }
2116       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2117                                                        TotalNumIntRegs);
2118
2119       bool NoImplicitFloatOps = Fn->getAttributes().
2120         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2121       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2122              "SSE register cannot be used when SSE is disabled!");
2123       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2124                NoImplicitFloatOps) &&
2125              "SSE register cannot be used when SSE is disabled!");
2126       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2127           !Subtarget->hasSSE1())
2128         // Kernel mode asks for SSE to be disabled, so don't push them
2129         // on the stack.
2130         TotalNumXMMRegs = 0;
2131
2132       if (IsWin64) {
2133         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2134         // Get to the caller-allocated home save location.  Add 8 to account
2135         // for the return address.
2136         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2137         FuncInfo->setRegSaveFrameIndex(
2138           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2139         // Fixup to set vararg frame on shadow area (4 x i64).
2140         if (NumIntRegs < 4)
2141           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2142       } else {
2143         // For X86-64, if there are vararg parameters that are passed via
2144         // registers, then we must store them to their spots on the stack so
2145         // they may be loaded by deferencing the result of va_next.
2146         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2147         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2148         FuncInfo->setRegSaveFrameIndex(
2149           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2150                                false));
2151       }
2152
2153       // Store the integer parameter registers.
2154       SmallVector<SDValue, 8> MemOps;
2155       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2156                                         getPointerTy());
2157       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2158       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2159         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2160                                   DAG.getIntPtrConstant(Offset));
2161         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2162                                      &X86::GR64RegClass);
2163         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2164         SDValue Store =
2165           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2166                        MachinePointerInfo::getFixedStack(
2167                          FuncInfo->getRegSaveFrameIndex(), Offset),
2168                        false, false, 0);
2169         MemOps.push_back(Store);
2170         Offset += 8;
2171       }
2172
2173       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2174         // Now store the XMM (fp + vector) parameter registers.
2175         SmallVector<SDValue, 11> SaveXMMOps;
2176         SaveXMMOps.push_back(Chain);
2177
2178         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2179         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2180         SaveXMMOps.push_back(ALVal);
2181
2182         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2183                                FuncInfo->getRegSaveFrameIndex()));
2184         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2185                                FuncInfo->getVarArgsFPOffset()));
2186
2187         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2188           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2189                                        &X86::VR128RegClass);
2190           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2191           SaveXMMOps.push_back(Val);
2192         }
2193         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2194                                      MVT::Other,
2195                                      &SaveXMMOps[0], SaveXMMOps.size()));
2196       }
2197
2198       if (!MemOps.empty())
2199         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2200                             &MemOps[0], MemOps.size());
2201     }
2202   }
2203
2204   // Some CCs need callee pop.
2205   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2206                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2207     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2208   } else {
2209     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2210     // If this is an sret function, the return should pop the hidden pointer.
2211     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2212         argsAreStructReturn(Ins) == StackStructReturn)
2213       FuncInfo->setBytesToPopOnReturn(4);
2214   }
2215
2216   if (!Is64Bit) {
2217     // RegSaveFrameIndex is X86-64 only.
2218     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2219     if (CallConv == CallingConv::X86_FastCall ||
2220         CallConv == CallingConv::X86_ThisCall)
2221       // fastcc functions can't have varargs.
2222       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2223   }
2224
2225   FuncInfo->setArgumentStackSize(StackSize);
2226
2227   return Chain;
2228 }
2229
2230 SDValue
2231 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2232                                     SDValue StackPtr, SDValue Arg,
2233                                     DebugLoc dl, SelectionDAG &DAG,
2234                                     const CCValAssign &VA,
2235                                     ISD::ArgFlagsTy Flags) const {
2236   unsigned LocMemOffset = VA.getLocMemOffset();
2237   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2238   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2239   if (Flags.isByVal())
2240     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2241
2242   return DAG.getStore(Chain, dl, Arg, PtrOff,
2243                       MachinePointerInfo::getStack(LocMemOffset),
2244                       false, false, 0);
2245 }
2246
2247 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2248 /// optimization is performed and it is required.
2249 SDValue
2250 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2251                                            SDValue &OutRetAddr, SDValue Chain,
2252                                            bool IsTailCall, bool Is64Bit,
2253                                            int FPDiff, DebugLoc dl) const {
2254   // Adjust the Return address stack slot.
2255   EVT VT = getPointerTy();
2256   OutRetAddr = getReturnAddressFrameIndex(DAG);
2257
2258   // Load the "old" Return address.
2259   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2260                            false, false, false, 0);
2261   return SDValue(OutRetAddr.getNode(), 1);
2262 }
2263
2264 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2265 /// optimization is performed and it is required (FPDiff!=0).
2266 static SDValue
2267 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2268                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2269                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2270   // Store the return address to the appropriate stack slot.
2271   if (!FPDiff) return Chain;
2272   // Calculate the new stack slot for the return address.
2273   int NewReturnAddrFI =
2274     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2275   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2276   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2277                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2278                        false, false, 0);
2279   return Chain;
2280 }
2281
2282 SDValue
2283 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2284                              SmallVectorImpl<SDValue> &InVals) const {
2285   SelectionDAG &DAG                     = CLI.DAG;
2286   DebugLoc &dl                          = CLI.DL;
2287   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2288   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2289   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2290   SDValue Chain                         = CLI.Chain;
2291   SDValue Callee                        = CLI.Callee;
2292   CallingConv::ID CallConv              = CLI.CallConv;
2293   bool &isTailCall                      = CLI.IsTailCall;
2294   bool isVarArg                         = CLI.IsVarArg;
2295
2296   MachineFunction &MF = DAG.getMachineFunction();
2297   bool Is64Bit        = Subtarget->is64Bit();
2298   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2299   bool IsWindows      = Subtarget->isTargetWindows();
2300   StructReturnType SR = callIsStructReturn(Outs);
2301   bool IsSibcall      = false;
2302
2303   if (MF.getTarget().Options.DisableTailCalls)
2304     isTailCall = false;
2305
2306   if (isTailCall) {
2307     // Check if it's really possible to do a tail call.
2308     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2309                     isVarArg, SR != NotStructReturn,
2310                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2311                     Outs, OutVals, Ins, DAG);
2312
2313     // Sibcalls are automatically detected tailcalls which do not require
2314     // ABI changes.
2315     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2316       IsSibcall = true;
2317
2318     if (isTailCall)
2319       ++NumTailCalls;
2320   }
2321
2322   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2323          "Var args not supported with calling convention fastcc, ghc or hipe");
2324
2325   // Analyze operands of the call, assigning locations to each operand.
2326   SmallVector<CCValAssign, 16> ArgLocs;
2327   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2328                  ArgLocs, *DAG.getContext());
2329
2330   // Allocate shadow area for Win64
2331   if (IsWin64)
2332     CCInfo.AllocateStack(32, 8);
2333
2334   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2335
2336   // Get a count of how many bytes are to be pushed on the stack.
2337   unsigned NumBytes = CCInfo.getNextStackOffset();
2338   if (IsSibcall)
2339     // This is a sibcall. The memory operands are available in caller's
2340     // own caller's stack.
2341     NumBytes = 0;
2342   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2343            IsTailCallConvention(CallConv))
2344     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2345
2346   int FPDiff = 0;
2347   if (isTailCall && !IsSibcall) {
2348     // Lower arguments at fp - stackoffset + fpdiff.
2349     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2350     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2351
2352     FPDiff = NumBytesCallerPushed - NumBytes;
2353
2354     // Set the delta of movement of the returnaddr stackslot.
2355     // But only set if delta is greater than previous delta.
2356     if (FPDiff < X86Info->getTCReturnAddrDelta())
2357       X86Info->setTCReturnAddrDelta(FPDiff);
2358   }
2359
2360   if (!IsSibcall)
2361     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2362
2363   SDValue RetAddrFrIdx;
2364   // Load return address for tail calls.
2365   if (isTailCall && FPDiff)
2366     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2367                                     Is64Bit, FPDiff, dl);
2368
2369   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2370   SmallVector<SDValue, 8> MemOpChains;
2371   SDValue StackPtr;
2372
2373   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2374   // of tail call optimization arguments are handle later.
2375   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2376     CCValAssign &VA = ArgLocs[i];
2377     EVT RegVT = VA.getLocVT();
2378     SDValue Arg = OutVals[i];
2379     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2380     bool isByVal = Flags.isByVal();
2381
2382     // Promote the value if needed.
2383     switch (VA.getLocInfo()) {
2384     default: llvm_unreachable("Unknown loc info!");
2385     case CCValAssign::Full: break;
2386     case CCValAssign::SExt:
2387       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2388       break;
2389     case CCValAssign::ZExt:
2390       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2391       break;
2392     case CCValAssign::AExt:
2393       if (RegVT.is128BitVector()) {
2394         // Special case: passing MMX values in XMM registers.
2395         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2396         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2397         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2398       } else
2399         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2400       break;
2401     case CCValAssign::BCvt:
2402       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2403       break;
2404     case CCValAssign::Indirect: {
2405       // Store the argument.
2406       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2407       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2408       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2409                            MachinePointerInfo::getFixedStack(FI),
2410                            false, false, 0);
2411       Arg = SpillSlot;
2412       break;
2413     }
2414     }
2415
2416     if (VA.isRegLoc()) {
2417       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2418       if (isVarArg && IsWin64) {
2419         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2420         // shadow reg if callee is a varargs function.
2421         unsigned ShadowReg = 0;
2422         switch (VA.getLocReg()) {
2423         case X86::XMM0: ShadowReg = X86::RCX; break;
2424         case X86::XMM1: ShadowReg = X86::RDX; break;
2425         case X86::XMM2: ShadowReg = X86::R8; break;
2426         case X86::XMM3: ShadowReg = X86::R9; break;
2427         }
2428         if (ShadowReg)
2429           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2430       }
2431     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2432       assert(VA.isMemLoc());
2433       if (StackPtr.getNode() == 0)
2434         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2435                                       getPointerTy());
2436       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2437                                              dl, DAG, VA, Flags));
2438     }
2439   }
2440
2441   if (!MemOpChains.empty())
2442     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2443                         &MemOpChains[0], MemOpChains.size());
2444
2445   if (Subtarget->isPICStyleGOT()) {
2446     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2447     // GOT pointer.
2448     if (!isTailCall) {
2449       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2450                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2451     } else {
2452       // If we are tail calling and generating PIC/GOT style code load the
2453       // address of the callee into ECX. The value in ecx is used as target of
2454       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2455       // for tail calls on PIC/GOT architectures. Normally we would just put the
2456       // address of GOT into ebx and then call target@PLT. But for tail calls
2457       // ebx would be restored (since ebx is callee saved) before jumping to the
2458       // target@PLT.
2459
2460       // Note: The actual moving to ECX is done further down.
2461       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2462       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2463           !G->getGlobal()->hasProtectedVisibility())
2464         Callee = LowerGlobalAddress(Callee, DAG);
2465       else if (isa<ExternalSymbolSDNode>(Callee))
2466         Callee = LowerExternalSymbol(Callee, DAG);
2467     }
2468   }
2469
2470   if (Is64Bit && isVarArg && !IsWin64) {
2471     // From AMD64 ABI document:
2472     // For calls that may call functions that use varargs or stdargs
2473     // (prototype-less calls or calls to functions containing ellipsis (...) in
2474     // the declaration) %al is used as hidden argument to specify the number
2475     // of SSE registers used. The contents of %al do not need to match exactly
2476     // the number of registers, but must be an ubound on the number of SSE
2477     // registers used and is in the range 0 - 8 inclusive.
2478
2479     // Count the number of XMM registers allocated.
2480     static const uint16_t XMMArgRegs[] = {
2481       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2482       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2483     };
2484     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2485     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2486            && "SSE registers cannot be used when SSE is disabled");
2487
2488     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2489                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2490   }
2491
2492   // For tail calls lower the arguments to the 'real' stack slot.
2493   if (isTailCall) {
2494     // Force all the incoming stack arguments to be loaded from the stack
2495     // before any new outgoing arguments are stored to the stack, because the
2496     // outgoing stack slots may alias the incoming argument stack slots, and
2497     // the alias isn't otherwise explicit. This is slightly more conservative
2498     // than necessary, because it means that each store effectively depends
2499     // on every argument instead of just those arguments it would clobber.
2500     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2501
2502     SmallVector<SDValue, 8> MemOpChains2;
2503     SDValue FIN;
2504     int FI = 0;
2505     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2506       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2507         CCValAssign &VA = ArgLocs[i];
2508         if (VA.isRegLoc())
2509           continue;
2510         assert(VA.isMemLoc());
2511         SDValue Arg = OutVals[i];
2512         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2513         // Create frame index.
2514         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2515         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2516         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2517         FIN = DAG.getFrameIndex(FI, getPointerTy());
2518
2519         if (Flags.isByVal()) {
2520           // Copy relative to framepointer.
2521           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2522           if (StackPtr.getNode() == 0)
2523             StackPtr = DAG.getCopyFromReg(Chain, dl,
2524                                           RegInfo->getStackRegister(),
2525                                           getPointerTy());
2526           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2527
2528           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2529                                                            ArgChain,
2530                                                            Flags, DAG, dl));
2531         } else {
2532           // Store relative to framepointer.
2533           MemOpChains2.push_back(
2534             DAG.getStore(ArgChain, dl, Arg, FIN,
2535                          MachinePointerInfo::getFixedStack(FI),
2536                          false, false, 0));
2537         }
2538       }
2539     }
2540
2541     if (!MemOpChains2.empty())
2542       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2543                           &MemOpChains2[0], MemOpChains2.size());
2544
2545     // Store the return address to the appropriate stack slot.
2546     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2547                                      getPointerTy(), RegInfo->getSlotSize(),
2548                                      FPDiff, dl);
2549   }
2550
2551   // Build a sequence of copy-to-reg nodes chained together with token chain
2552   // and flag operands which copy the outgoing args into registers.
2553   SDValue InFlag;
2554   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2555     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2556                              RegsToPass[i].second, InFlag);
2557     InFlag = Chain.getValue(1);
2558   }
2559
2560   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2561     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2562     // In the 64-bit large code model, we have to make all calls
2563     // through a register, since the call instruction's 32-bit
2564     // pc-relative offset may not be large enough to hold the whole
2565     // address.
2566   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2567     // If the callee is a GlobalAddress node (quite common, every direct call
2568     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2569     // it.
2570
2571     // We should use extra load for direct calls to dllimported functions in
2572     // non-JIT mode.
2573     const GlobalValue *GV = G->getGlobal();
2574     if (!GV->hasDLLImportLinkage()) {
2575       unsigned char OpFlags = 0;
2576       bool ExtraLoad = false;
2577       unsigned WrapperKind = ISD::DELETED_NODE;
2578
2579       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2580       // external symbols most go through the PLT in PIC mode.  If the symbol
2581       // has hidden or protected visibility, or if it is static or local, then
2582       // we don't need to use the PLT - we can directly call it.
2583       if (Subtarget->isTargetELF() &&
2584           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2585           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2586         OpFlags = X86II::MO_PLT;
2587       } else if (Subtarget->isPICStyleStubAny() &&
2588                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2589                  (!Subtarget->getTargetTriple().isMacOSX() ||
2590                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2591         // PC-relative references to external symbols should go through $stub,
2592         // unless we're building with the leopard linker or later, which
2593         // automatically synthesizes these stubs.
2594         OpFlags = X86II::MO_DARWIN_STUB;
2595       } else if (Subtarget->isPICStyleRIPRel() &&
2596                  isa<Function>(GV) &&
2597                  cast<Function>(GV)->getAttributes().
2598                    hasAttribute(AttributeSet::FunctionIndex,
2599                                 Attribute::NonLazyBind)) {
2600         // If the function is marked as non-lazy, generate an indirect call
2601         // which loads from the GOT directly. This avoids runtime overhead
2602         // at the cost of eager binding (and one extra byte of encoding).
2603         OpFlags = X86II::MO_GOTPCREL;
2604         WrapperKind = X86ISD::WrapperRIP;
2605         ExtraLoad = true;
2606       }
2607
2608       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2609                                           G->getOffset(), OpFlags);
2610
2611       // Add a wrapper if needed.
2612       if (WrapperKind != ISD::DELETED_NODE)
2613         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2614       // Add extra indirection if needed.
2615       if (ExtraLoad)
2616         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2617                              MachinePointerInfo::getGOT(),
2618                              false, false, false, 0);
2619     }
2620   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2621     unsigned char OpFlags = 0;
2622
2623     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2624     // external symbols should go through the PLT.
2625     if (Subtarget->isTargetELF() &&
2626         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2627       OpFlags = X86II::MO_PLT;
2628     } else if (Subtarget->isPICStyleStubAny() &&
2629                (!Subtarget->getTargetTriple().isMacOSX() ||
2630                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2631       // PC-relative references to external symbols should go through $stub,
2632       // unless we're building with the leopard linker or later, which
2633       // automatically synthesizes these stubs.
2634       OpFlags = X86II::MO_DARWIN_STUB;
2635     }
2636
2637     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2638                                          OpFlags);
2639   }
2640
2641   // Returns a chain & a flag for retval copy to use.
2642   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2643   SmallVector<SDValue, 8> Ops;
2644
2645   if (!IsSibcall && isTailCall) {
2646     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2647                            DAG.getIntPtrConstant(0, true), InFlag);
2648     InFlag = Chain.getValue(1);
2649   }
2650
2651   Ops.push_back(Chain);
2652   Ops.push_back(Callee);
2653
2654   if (isTailCall)
2655     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2656
2657   // Add argument registers to the end of the list so that they are known live
2658   // into the call.
2659   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2660     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2661                                   RegsToPass[i].second.getValueType()));
2662
2663   // Add a register mask operand representing the call-preserved registers.
2664   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2665   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2666   assert(Mask && "Missing call preserved mask for calling convention");
2667   Ops.push_back(DAG.getRegisterMask(Mask));
2668
2669   if (InFlag.getNode())
2670     Ops.push_back(InFlag);
2671
2672   if (isTailCall) {
2673     // We used to do:
2674     //// If this is the first return lowered for this function, add the regs
2675     //// to the liveout set for the function.
2676     // This isn't right, although it's probably harmless on x86; liveouts
2677     // should be computed from returns not tail calls.  Consider a void
2678     // function making a tail call to a function returning int.
2679     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2680   }
2681
2682   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2683   InFlag = Chain.getValue(1);
2684
2685   // Create the CALLSEQ_END node.
2686   unsigned NumBytesForCalleeToPush;
2687   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2688                        getTargetMachine().Options.GuaranteedTailCallOpt))
2689     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2690   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2691            SR == StackStructReturn)
2692     // If this is a call to a struct-return function, the callee
2693     // pops the hidden struct pointer, so we have to push it back.
2694     // This is common for Darwin/X86, Linux & Mingw32 targets.
2695     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2696     NumBytesForCalleeToPush = 4;
2697   else
2698     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2699
2700   // Returns a flag for retval copy to use.
2701   if (!IsSibcall) {
2702     Chain = DAG.getCALLSEQ_END(Chain,
2703                                DAG.getIntPtrConstant(NumBytes, true),
2704                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2705                                                      true),
2706                                InFlag);
2707     InFlag = Chain.getValue(1);
2708   }
2709
2710   // Handle result values, copying them out of physregs into vregs that we
2711   // return.
2712   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2713                          Ins, dl, DAG, InVals);
2714 }
2715
2716 //===----------------------------------------------------------------------===//
2717 //                Fast Calling Convention (tail call) implementation
2718 //===----------------------------------------------------------------------===//
2719
2720 //  Like std call, callee cleans arguments, convention except that ECX is
2721 //  reserved for storing the tail called function address. Only 2 registers are
2722 //  free for argument passing (inreg). Tail call optimization is performed
2723 //  provided:
2724 //                * tailcallopt is enabled
2725 //                * caller/callee are fastcc
2726 //  On X86_64 architecture with GOT-style position independent code only local
2727 //  (within module) calls are supported at the moment.
2728 //  To keep the stack aligned according to platform abi the function
2729 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2730 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2731 //  If a tail called function callee has more arguments than the caller the
2732 //  caller needs to make sure that there is room to move the RETADDR to. This is
2733 //  achieved by reserving an area the size of the argument delta right after the
2734 //  original REtADDR, but before the saved framepointer or the spilled registers
2735 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2736 //  stack layout:
2737 //    arg1
2738 //    arg2
2739 //    RETADDR
2740 //    [ new RETADDR
2741 //      move area ]
2742 //    (possible EBP)
2743 //    ESI
2744 //    EDI
2745 //    local1 ..
2746
2747 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2748 /// for a 16 byte align requirement.
2749 unsigned
2750 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2751                                                SelectionDAG& DAG) const {
2752   MachineFunction &MF = DAG.getMachineFunction();
2753   const TargetMachine &TM = MF.getTarget();
2754   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2755   unsigned StackAlignment = TFI.getStackAlignment();
2756   uint64_t AlignMask = StackAlignment - 1;
2757   int64_t Offset = StackSize;
2758   unsigned SlotSize = RegInfo->getSlotSize();
2759   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2760     // Number smaller than 12 so just add the difference.
2761     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2762   } else {
2763     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2764     Offset = ((~AlignMask) & Offset) + StackAlignment +
2765       (StackAlignment-SlotSize);
2766   }
2767   return Offset;
2768 }
2769
2770 /// MatchingStackOffset - Return true if the given stack call argument is
2771 /// already available in the same position (relatively) of the caller's
2772 /// incoming argument stack.
2773 static
2774 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2775                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2776                          const X86InstrInfo *TII) {
2777   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2778   int FI = INT_MAX;
2779   if (Arg.getOpcode() == ISD::CopyFromReg) {
2780     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2781     if (!TargetRegisterInfo::isVirtualRegister(VR))
2782       return false;
2783     MachineInstr *Def = MRI->getVRegDef(VR);
2784     if (!Def)
2785       return false;
2786     if (!Flags.isByVal()) {
2787       if (!TII->isLoadFromStackSlot(Def, FI))
2788         return false;
2789     } else {
2790       unsigned Opcode = Def->getOpcode();
2791       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2792           Def->getOperand(1).isFI()) {
2793         FI = Def->getOperand(1).getIndex();
2794         Bytes = Flags.getByValSize();
2795       } else
2796         return false;
2797     }
2798   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2799     if (Flags.isByVal())
2800       // ByVal argument is passed in as a pointer but it's now being
2801       // dereferenced. e.g.
2802       // define @foo(%struct.X* %A) {
2803       //   tail call @bar(%struct.X* byval %A)
2804       // }
2805       return false;
2806     SDValue Ptr = Ld->getBasePtr();
2807     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2808     if (!FINode)
2809       return false;
2810     FI = FINode->getIndex();
2811   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2812     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2813     FI = FINode->getIndex();
2814     Bytes = Flags.getByValSize();
2815   } else
2816     return false;
2817
2818   assert(FI != INT_MAX);
2819   if (!MFI->isFixedObjectIndex(FI))
2820     return false;
2821   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2822 }
2823
2824 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2825 /// for tail call optimization. Targets which want to do tail call
2826 /// optimization should implement this function.
2827 bool
2828 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2829                                                      CallingConv::ID CalleeCC,
2830                                                      bool isVarArg,
2831                                                      bool isCalleeStructRet,
2832                                                      bool isCallerStructRet,
2833                                                      Type *RetTy,
2834                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2835                                     const SmallVectorImpl<SDValue> &OutVals,
2836                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2837                                                      SelectionDAG &DAG) const {
2838   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2839     return false;
2840
2841   // If -tailcallopt is specified, make fastcc functions tail-callable.
2842   const MachineFunction &MF = DAG.getMachineFunction();
2843   const Function *CallerF = MF.getFunction();
2844
2845   // If the function return type is x86_fp80 and the callee return type is not,
2846   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2847   // perform a tailcall optimization here.
2848   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2849     return false;
2850
2851   CallingConv::ID CallerCC = CallerF->getCallingConv();
2852   bool CCMatch = CallerCC == CalleeCC;
2853   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
2854   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
2855
2856   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2857     if (IsTailCallConvention(CalleeCC) && CCMatch)
2858       return true;
2859     return false;
2860   }
2861
2862   // Look for obvious safe cases to perform tail call optimization that do not
2863   // require ABI changes. This is what gcc calls sibcall.
2864
2865   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2866   // emit a special epilogue.
2867   if (RegInfo->needsStackRealignment(MF))
2868     return false;
2869
2870   // Also avoid sibcall optimization if either caller or callee uses struct
2871   // return semantics.
2872   if (isCalleeStructRet || isCallerStructRet)
2873     return false;
2874
2875   // An stdcall caller is expected to clean up its arguments; the callee
2876   // isn't going to do that.
2877   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2878     return false;
2879
2880   // Do not sibcall optimize vararg calls unless all arguments are passed via
2881   // registers.
2882   if (isVarArg && !Outs.empty()) {
2883
2884     // Optimizing for varargs on Win64 is unlikely to be safe without
2885     // additional testing.
2886     if (IsCalleeWin64 || IsCallerWin64)
2887       return false;
2888
2889     SmallVector<CCValAssign, 16> ArgLocs;
2890     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2891                    getTargetMachine(), ArgLocs, *DAG.getContext());
2892
2893     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2894     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2895       if (!ArgLocs[i].isRegLoc())
2896         return false;
2897   }
2898
2899   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2900   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2901   // this into a sibcall.
2902   bool Unused = false;
2903   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2904     if (!Ins[i].Used) {
2905       Unused = true;
2906       break;
2907     }
2908   }
2909   if (Unused) {
2910     SmallVector<CCValAssign, 16> RVLocs;
2911     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2912                    getTargetMachine(), RVLocs, *DAG.getContext());
2913     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2914     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2915       CCValAssign &VA = RVLocs[i];
2916       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2917         return false;
2918     }
2919   }
2920
2921   // If the calling conventions do not match, then we'd better make sure the
2922   // results are returned in the same way as what the caller expects.
2923   if (!CCMatch) {
2924     SmallVector<CCValAssign, 16> RVLocs1;
2925     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2926                     getTargetMachine(), RVLocs1, *DAG.getContext());
2927     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2928
2929     SmallVector<CCValAssign, 16> RVLocs2;
2930     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2931                     getTargetMachine(), RVLocs2, *DAG.getContext());
2932     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2933
2934     if (RVLocs1.size() != RVLocs2.size())
2935       return false;
2936     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2937       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2938         return false;
2939       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2940         return false;
2941       if (RVLocs1[i].isRegLoc()) {
2942         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2943           return false;
2944       } else {
2945         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2946           return false;
2947       }
2948     }
2949   }
2950
2951   // If the callee takes no arguments then go on to check the results of the
2952   // call.
2953   if (!Outs.empty()) {
2954     // Check if stack adjustment is needed. For now, do not do this if any
2955     // argument is passed on the stack.
2956     SmallVector<CCValAssign, 16> ArgLocs;
2957     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2958                    getTargetMachine(), ArgLocs, *DAG.getContext());
2959
2960     // Allocate shadow area for Win64
2961     if (IsCalleeWin64)
2962       CCInfo.AllocateStack(32, 8);
2963
2964     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2965     if (CCInfo.getNextStackOffset()) {
2966       MachineFunction &MF = DAG.getMachineFunction();
2967       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2968         return false;
2969
2970       // Check if the arguments are already laid out in the right way as
2971       // the caller's fixed stack objects.
2972       MachineFrameInfo *MFI = MF.getFrameInfo();
2973       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2974       const X86InstrInfo *TII =
2975         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2976       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2977         CCValAssign &VA = ArgLocs[i];
2978         SDValue Arg = OutVals[i];
2979         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2980         if (VA.getLocInfo() == CCValAssign::Indirect)
2981           return false;
2982         if (!VA.isRegLoc()) {
2983           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2984                                    MFI, MRI, TII))
2985             return false;
2986         }
2987       }
2988     }
2989
2990     // If the tailcall address may be in a register, then make sure it's
2991     // possible to register allocate for it. In 32-bit, the call address can
2992     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2993     // callee-saved registers are restored. These happen to be the same
2994     // registers used to pass 'inreg' arguments so watch out for those.
2995     if (!Subtarget->is64Bit() &&
2996         ((!isa<GlobalAddressSDNode>(Callee) &&
2997           !isa<ExternalSymbolSDNode>(Callee)) ||
2998          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2999       unsigned NumInRegs = 0;
3000       // In PIC we need an extra register to formulate the address computation
3001       // for the callee.
3002       unsigned MaxInRegs =
3003           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3004
3005       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3006         CCValAssign &VA = ArgLocs[i];
3007         if (!VA.isRegLoc())
3008           continue;
3009         unsigned Reg = VA.getLocReg();
3010         switch (Reg) {
3011         default: break;
3012         case X86::EAX: case X86::EDX: case X86::ECX:
3013           if (++NumInRegs == MaxInRegs)
3014             return false;
3015           break;
3016         }
3017       }
3018     }
3019   }
3020
3021   return true;
3022 }
3023
3024 FastISel *
3025 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3026                                   const TargetLibraryInfo *libInfo) const {
3027   return X86::createFastISel(funcInfo, libInfo);
3028 }
3029
3030 //===----------------------------------------------------------------------===//
3031 //                           Other Lowering Hooks
3032 //===----------------------------------------------------------------------===//
3033
3034 static bool MayFoldLoad(SDValue Op) {
3035   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3036 }
3037
3038 static bool MayFoldIntoStore(SDValue Op) {
3039   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3040 }
3041
3042 static bool isTargetShuffle(unsigned Opcode) {
3043   switch(Opcode) {
3044   default: return false;
3045   case X86ISD::PSHUFD:
3046   case X86ISD::PSHUFHW:
3047   case X86ISD::PSHUFLW:
3048   case X86ISD::SHUFP:
3049   case X86ISD::PALIGNR:
3050   case X86ISD::MOVLHPS:
3051   case X86ISD::MOVLHPD:
3052   case X86ISD::MOVHLPS:
3053   case X86ISD::MOVLPS:
3054   case X86ISD::MOVLPD:
3055   case X86ISD::MOVSHDUP:
3056   case X86ISD::MOVSLDUP:
3057   case X86ISD::MOVDDUP:
3058   case X86ISD::MOVSS:
3059   case X86ISD::MOVSD:
3060   case X86ISD::UNPCKL:
3061   case X86ISD::UNPCKH:
3062   case X86ISD::VPERMILP:
3063   case X86ISD::VPERM2X128:
3064   case X86ISD::VPERMI:
3065     return true;
3066   }
3067 }
3068
3069 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3070                                     SDValue V1, SelectionDAG &DAG) {
3071   switch(Opc) {
3072   default: llvm_unreachable("Unknown x86 shuffle node");
3073   case X86ISD::MOVSHDUP:
3074   case X86ISD::MOVSLDUP:
3075   case X86ISD::MOVDDUP:
3076     return DAG.getNode(Opc, dl, VT, V1);
3077   }
3078 }
3079
3080 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3081                                     SDValue V1, unsigned TargetMask,
3082                                     SelectionDAG &DAG) {
3083   switch(Opc) {
3084   default: llvm_unreachable("Unknown x86 shuffle node");
3085   case X86ISD::PSHUFD:
3086   case X86ISD::PSHUFHW:
3087   case X86ISD::PSHUFLW:
3088   case X86ISD::VPERMILP:
3089   case X86ISD::VPERMI:
3090     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3091   }
3092 }
3093
3094 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3095                                     SDValue V1, SDValue V2, unsigned TargetMask,
3096                                     SelectionDAG &DAG) {
3097   switch(Opc) {
3098   default: llvm_unreachable("Unknown x86 shuffle node");
3099   case X86ISD::PALIGNR:
3100   case X86ISD::SHUFP:
3101   case X86ISD::VPERM2X128:
3102     return DAG.getNode(Opc, dl, VT, V1, V2,
3103                        DAG.getConstant(TargetMask, MVT::i8));
3104   }
3105 }
3106
3107 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3108                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3109   switch(Opc) {
3110   default: llvm_unreachable("Unknown x86 shuffle node");
3111   case X86ISD::MOVLHPS:
3112   case X86ISD::MOVLHPD:
3113   case X86ISD::MOVHLPS:
3114   case X86ISD::MOVLPS:
3115   case X86ISD::MOVLPD:
3116   case X86ISD::MOVSS:
3117   case X86ISD::MOVSD:
3118   case X86ISD::UNPCKL:
3119   case X86ISD::UNPCKH:
3120     return DAG.getNode(Opc, dl, VT, V1, V2);
3121   }
3122 }
3123
3124 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3125   MachineFunction &MF = DAG.getMachineFunction();
3126   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3127   int ReturnAddrIndex = FuncInfo->getRAIndex();
3128
3129   if (ReturnAddrIndex == 0) {
3130     // Set up a frame object for the return address.
3131     unsigned SlotSize = RegInfo->getSlotSize();
3132     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3133                                                            false);
3134     FuncInfo->setRAIndex(ReturnAddrIndex);
3135   }
3136
3137   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3138 }
3139
3140 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3141                                        bool hasSymbolicDisplacement) {
3142   // Offset should fit into 32 bit immediate field.
3143   if (!isInt<32>(Offset))
3144     return false;
3145
3146   // If we don't have a symbolic displacement - we don't have any extra
3147   // restrictions.
3148   if (!hasSymbolicDisplacement)
3149     return true;
3150
3151   // FIXME: Some tweaks might be needed for medium code model.
3152   if (M != CodeModel::Small && M != CodeModel::Kernel)
3153     return false;
3154
3155   // For small code model we assume that latest object is 16MB before end of 31
3156   // bits boundary. We may also accept pretty large negative constants knowing
3157   // that all objects are in the positive half of address space.
3158   if (M == CodeModel::Small && Offset < 16*1024*1024)
3159     return true;
3160
3161   // For kernel code model we know that all object resist in the negative half
3162   // of 32bits address space. We may not accept negative offsets, since they may
3163   // be just off and we may accept pretty large positive ones.
3164   if (M == CodeModel::Kernel && Offset > 0)
3165     return true;
3166
3167   return false;
3168 }
3169
3170 /// isCalleePop - Determines whether the callee is required to pop its
3171 /// own arguments. Callee pop is necessary to support tail calls.
3172 bool X86::isCalleePop(CallingConv::ID CallingConv,
3173                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3174   if (IsVarArg)
3175     return false;
3176
3177   switch (CallingConv) {
3178   default:
3179     return false;
3180   case CallingConv::X86_StdCall:
3181     return !is64Bit;
3182   case CallingConv::X86_FastCall:
3183     return !is64Bit;
3184   case CallingConv::X86_ThisCall:
3185     return !is64Bit;
3186   case CallingConv::Fast:
3187     return TailCallOpt;
3188   case CallingConv::GHC:
3189     return TailCallOpt;
3190   case CallingConv::HiPE:
3191     return TailCallOpt;
3192   }
3193 }
3194
3195 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3196 /// specific condition code, returning the condition code and the LHS/RHS of the
3197 /// comparison to make.
3198 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3199                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3200   if (!isFP) {
3201     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3202       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3203         // X > -1   -> X == 0, jump !sign.
3204         RHS = DAG.getConstant(0, RHS.getValueType());
3205         return X86::COND_NS;
3206       }
3207       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3208         // X < 0   -> X == 0, jump on sign.
3209         return X86::COND_S;
3210       }
3211       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3212         // X < 1   -> X <= 0
3213         RHS = DAG.getConstant(0, RHS.getValueType());
3214         return X86::COND_LE;
3215       }
3216     }
3217
3218     switch (SetCCOpcode) {
3219     default: llvm_unreachable("Invalid integer condition!");
3220     case ISD::SETEQ:  return X86::COND_E;
3221     case ISD::SETGT:  return X86::COND_G;
3222     case ISD::SETGE:  return X86::COND_GE;
3223     case ISD::SETLT:  return X86::COND_L;
3224     case ISD::SETLE:  return X86::COND_LE;
3225     case ISD::SETNE:  return X86::COND_NE;
3226     case ISD::SETULT: return X86::COND_B;
3227     case ISD::SETUGT: return X86::COND_A;
3228     case ISD::SETULE: return X86::COND_BE;
3229     case ISD::SETUGE: return X86::COND_AE;
3230     }
3231   }
3232
3233   // First determine if it is required or is profitable to flip the operands.
3234
3235   // If LHS is a foldable load, but RHS is not, flip the condition.
3236   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3237       !ISD::isNON_EXTLoad(RHS.getNode())) {
3238     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3239     std::swap(LHS, RHS);
3240   }
3241
3242   switch (SetCCOpcode) {
3243   default: break;
3244   case ISD::SETOLT:
3245   case ISD::SETOLE:
3246   case ISD::SETUGT:
3247   case ISD::SETUGE:
3248     std::swap(LHS, RHS);
3249     break;
3250   }
3251
3252   // On a floating point condition, the flags are set as follows:
3253   // ZF  PF  CF   op
3254   //  0 | 0 | 0 | X > Y
3255   //  0 | 0 | 1 | X < Y
3256   //  1 | 0 | 0 | X == Y
3257   //  1 | 1 | 1 | unordered
3258   switch (SetCCOpcode) {
3259   default: llvm_unreachable("Condcode should be pre-legalized away");
3260   case ISD::SETUEQ:
3261   case ISD::SETEQ:   return X86::COND_E;
3262   case ISD::SETOLT:              // flipped
3263   case ISD::SETOGT:
3264   case ISD::SETGT:   return X86::COND_A;
3265   case ISD::SETOLE:              // flipped
3266   case ISD::SETOGE:
3267   case ISD::SETGE:   return X86::COND_AE;
3268   case ISD::SETUGT:              // flipped
3269   case ISD::SETULT:
3270   case ISD::SETLT:   return X86::COND_B;
3271   case ISD::SETUGE:              // flipped
3272   case ISD::SETULE:
3273   case ISD::SETLE:   return X86::COND_BE;
3274   case ISD::SETONE:
3275   case ISD::SETNE:   return X86::COND_NE;
3276   case ISD::SETUO:   return X86::COND_P;
3277   case ISD::SETO:    return X86::COND_NP;
3278   case ISD::SETOEQ:
3279   case ISD::SETUNE:  return X86::COND_INVALID;
3280   }
3281 }
3282
3283 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3284 /// code. Current x86 isa includes the following FP cmov instructions:
3285 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3286 static bool hasFPCMov(unsigned X86CC) {
3287   switch (X86CC) {
3288   default:
3289     return false;
3290   case X86::COND_B:
3291   case X86::COND_BE:
3292   case X86::COND_E:
3293   case X86::COND_P:
3294   case X86::COND_A:
3295   case X86::COND_AE:
3296   case X86::COND_NE:
3297   case X86::COND_NP:
3298     return true;
3299   }
3300 }
3301
3302 /// isFPImmLegal - Returns true if the target can instruction select the
3303 /// specified FP immediate natively. If false, the legalizer will
3304 /// materialize the FP immediate as a load from a constant pool.
3305 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3306   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3307     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3308       return true;
3309   }
3310   return false;
3311 }
3312
3313 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3314 /// the specified range (L, H].
3315 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3316   return (Val < 0) || (Val >= Low && Val < Hi);
3317 }
3318
3319 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3320 /// specified value.
3321 static bool isUndefOrEqual(int Val, int CmpVal) {
3322   return (Val < 0 || Val == CmpVal);
3323 }
3324
3325 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3326 /// from position Pos and ending in Pos+Size, falls within the specified
3327 /// sequential range (L, L+Pos]. or is undef.
3328 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3329                                        unsigned Pos, unsigned Size, int Low) {
3330   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3331     if (!isUndefOrEqual(Mask[i], Low))
3332       return false;
3333   return true;
3334 }
3335
3336 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3337 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3338 /// the second operand.
3339 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3340   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3341     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3342   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3343     return (Mask[0] < 2 && Mask[1] < 2);
3344   return false;
3345 }
3346
3347 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3348 /// is suitable for input to PSHUFHW.
3349 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3350   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3351     return false;
3352
3353   // Lower quadword copied in order or undef.
3354   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3355     return false;
3356
3357   // Upper quadword shuffled.
3358   for (unsigned i = 4; i != 8; ++i)
3359     if (!isUndefOrInRange(Mask[i], 4, 8))
3360       return false;
3361
3362   if (VT == MVT::v16i16) {
3363     // Lower quadword copied in order or undef.
3364     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3365       return false;
3366
3367     // Upper quadword shuffled.
3368     for (unsigned i = 12; i != 16; ++i)
3369       if (!isUndefOrInRange(Mask[i], 12, 16))
3370         return false;
3371   }
3372
3373   return true;
3374 }
3375
3376 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3377 /// is suitable for input to PSHUFLW.
3378 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3379   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3380     return false;
3381
3382   // Upper quadword copied in order.
3383   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3384     return false;
3385
3386   // Lower quadword shuffled.
3387   for (unsigned i = 0; i != 4; ++i)
3388     if (!isUndefOrInRange(Mask[i], 0, 4))
3389       return false;
3390
3391   if (VT == MVT::v16i16) {
3392     // Upper quadword copied in order.
3393     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3394       return false;
3395
3396     // Lower quadword shuffled.
3397     for (unsigned i = 8; i != 12; ++i)
3398       if (!isUndefOrInRange(Mask[i], 8, 12))
3399         return false;
3400   }
3401
3402   return true;
3403 }
3404
3405 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3406 /// is suitable for input to PALIGNR.
3407 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3408                           const X86Subtarget *Subtarget) {
3409   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3410       (VT.is256BitVector() && !Subtarget->hasInt256()))
3411     return false;
3412
3413   unsigned NumElts = VT.getVectorNumElements();
3414   unsigned NumLanes = VT.getSizeInBits()/128;
3415   unsigned NumLaneElts = NumElts/NumLanes;
3416
3417   // Do not handle 64-bit element shuffles with palignr.
3418   if (NumLaneElts == 2)
3419     return false;
3420
3421   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3422     unsigned i;
3423     for (i = 0; i != NumLaneElts; ++i) {
3424       if (Mask[i+l] >= 0)
3425         break;
3426     }
3427
3428     // Lane is all undef, go to next lane
3429     if (i == NumLaneElts)
3430       continue;
3431
3432     int Start = Mask[i+l];
3433
3434     // Make sure its in this lane in one of the sources
3435     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3436         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3437       return false;
3438
3439     // If not lane 0, then we must match lane 0
3440     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3441       return false;
3442
3443     // Correct second source to be contiguous with first source
3444     if (Start >= (int)NumElts)
3445       Start -= NumElts - NumLaneElts;
3446
3447     // Make sure we're shifting in the right direction.
3448     if (Start <= (int)(i+l))
3449       return false;
3450
3451     Start -= i;
3452
3453     // Check the rest of the elements to see if they are consecutive.
3454     for (++i; i != NumLaneElts; ++i) {
3455       int Idx = Mask[i+l];
3456
3457       // Make sure its in this lane
3458       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3459           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3460         return false;
3461
3462       // If not lane 0, then we must match lane 0
3463       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3464         return false;
3465
3466       if (Idx >= (int)NumElts)
3467         Idx -= NumElts - NumLaneElts;
3468
3469       if (!isUndefOrEqual(Idx, Start+i))
3470         return false;
3471
3472     }
3473   }
3474
3475   return true;
3476 }
3477
3478 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3479 /// the two vector operands have swapped position.
3480 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3481                                      unsigned NumElems) {
3482   for (unsigned i = 0; i != NumElems; ++i) {
3483     int idx = Mask[i];
3484     if (idx < 0)
3485       continue;
3486     else if (idx < (int)NumElems)
3487       Mask[i] = idx + NumElems;
3488     else
3489       Mask[i] = idx - NumElems;
3490   }
3491 }
3492
3493 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3494 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3495 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3496 /// reverse of what x86 shuffles want.
3497 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3498                         bool Commuted = false) {
3499   if (!HasFp256 && VT.is256BitVector())
3500     return false;
3501
3502   unsigned NumElems = VT.getVectorNumElements();
3503   unsigned NumLanes = VT.getSizeInBits()/128;
3504   unsigned NumLaneElems = NumElems/NumLanes;
3505
3506   if (NumLaneElems != 2 && NumLaneElems != 4)
3507     return false;
3508
3509   // VSHUFPSY divides the resulting vector into 4 chunks.
3510   // The sources are also splitted into 4 chunks, and each destination
3511   // chunk must come from a different source chunk.
3512   //
3513   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3514   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3515   //
3516   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3517   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3518   //
3519   // VSHUFPDY divides the resulting vector into 4 chunks.
3520   // The sources are also splitted into 4 chunks, and each destination
3521   // chunk must come from a different source chunk.
3522   //
3523   //  SRC1 =>      X3       X2       X1       X0
3524   //  SRC2 =>      Y3       Y2       Y1       Y0
3525   //
3526   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3527   //
3528   unsigned HalfLaneElems = NumLaneElems/2;
3529   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3530     for (unsigned i = 0; i != NumLaneElems; ++i) {
3531       int Idx = Mask[i+l];
3532       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3533       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3534         return false;
3535       // For VSHUFPSY, the mask of the second half must be the same as the
3536       // first but with the appropriate offsets. This works in the same way as
3537       // VPERMILPS works with masks.
3538       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3539         continue;
3540       if (!isUndefOrEqual(Idx, Mask[i]+l))
3541         return false;
3542     }
3543   }
3544
3545   return true;
3546 }
3547
3548 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3549 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3550 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3551   if (!VT.is128BitVector())
3552     return false;
3553
3554   unsigned NumElems = VT.getVectorNumElements();
3555
3556   if (NumElems != 4)
3557     return false;
3558
3559   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3560   return isUndefOrEqual(Mask[0], 6) &&
3561          isUndefOrEqual(Mask[1], 7) &&
3562          isUndefOrEqual(Mask[2], 2) &&
3563          isUndefOrEqual(Mask[3], 3);
3564 }
3565
3566 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3567 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3568 /// <2, 3, 2, 3>
3569 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3570   if (!VT.is128BitVector())
3571     return false;
3572
3573   unsigned NumElems = VT.getVectorNumElements();
3574
3575   if (NumElems != 4)
3576     return false;
3577
3578   return isUndefOrEqual(Mask[0], 2) &&
3579          isUndefOrEqual(Mask[1], 3) &&
3580          isUndefOrEqual(Mask[2], 2) &&
3581          isUndefOrEqual(Mask[3], 3);
3582 }
3583
3584 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3585 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3586 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3587   if (!VT.is128BitVector())
3588     return false;
3589
3590   unsigned NumElems = VT.getVectorNumElements();
3591
3592   if (NumElems != 2 && NumElems != 4)
3593     return false;
3594
3595   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3596     if (!isUndefOrEqual(Mask[i], i + NumElems))
3597       return false;
3598
3599   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3600     if (!isUndefOrEqual(Mask[i], i))
3601       return false;
3602
3603   return true;
3604 }
3605
3606 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3607 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3608 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3609   if (!VT.is128BitVector())
3610     return false;
3611
3612   unsigned NumElems = VT.getVectorNumElements();
3613
3614   if (NumElems != 2 && NumElems != 4)
3615     return false;
3616
3617   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3618     if (!isUndefOrEqual(Mask[i], i))
3619       return false;
3620
3621   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3622     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3623       return false;
3624
3625   return true;
3626 }
3627
3628 //
3629 // Some special combinations that can be optimized.
3630 //
3631 static
3632 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3633                                SelectionDAG &DAG) {
3634   MVT VT = SVOp->getValueType(0).getSimpleVT();
3635   DebugLoc dl = SVOp->getDebugLoc();
3636
3637   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3638     return SDValue();
3639
3640   ArrayRef<int> Mask = SVOp->getMask();
3641
3642   // These are the special masks that may be optimized.
3643   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3644   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3645   bool MatchEvenMask = true;
3646   bool MatchOddMask  = true;
3647   for (int i=0; i<8; ++i) {
3648     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3649       MatchEvenMask = false;
3650     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3651       MatchOddMask = false;
3652   }
3653
3654   if (!MatchEvenMask && !MatchOddMask)
3655     return SDValue();
3656
3657   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3658
3659   SDValue Op0 = SVOp->getOperand(0);
3660   SDValue Op1 = SVOp->getOperand(1);
3661
3662   if (MatchEvenMask) {
3663     // Shift the second operand right to 32 bits.
3664     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3665     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3666   } else {
3667     // Shift the first operand left to 32 bits.
3668     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3669     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3670   }
3671   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3672   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3673 }
3674
3675 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3676 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3677 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3678                          bool HasInt256, bool V2IsSplat = false) {
3679   unsigned NumElts = VT.getVectorNumElements();
3680
3681   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3682          "Unsupported vector type for unpckh");
3683
3684   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3685       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3686     return false;
3687
3688   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3689   // independently on 128-bit lanes.
3690   unsigned NumLanes = VT.getSizeInBits()/128;
3691   unsigned NumLaneElts = NumElts/NumLanes;
3692
3693   for (unsigned l = 0; l != NumLanes; ++l) {
3694     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3695          i != (l+1)*NumLaneElts;
3696          i += 2, ++j) {
3697       int BitI  = Mask[i];
3698       int BitI1 = Mask[i+1];
3699       if (!isUndefOrEqual(BitI, j))
3700         return false;
3701       if (V2IsSplat) {
3702         if (!isUndefOrEqual(BitI1, NumElts))
3703           return false;
3704       } else {
3705         if (!isUndefOrEqual(BitI1, j + NumElts))
3706           return false;
3707       }
3708     }
3709   }
3710
3711   return true;
3712 }
3713
3714 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3715 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3716 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3717                          bool HasInt256, bool V2IsSplat = false) {
3718   unsigned NumElts = VT.getVectorNumElements();
3719
3720   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3721          "Unsupported vector type for unpckh");
3722
3723   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3724       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3725     return false;
3726
3727   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3728   // independently on 128-bit lanes.
3729   unsigned NumLanes = VT.getSizeInBits()/128;
3730   unsigned NumLaneElts = NumElts/NumLanes;
3731
3732   for (unsigned l = 0; l != NumLanes; ++l) {
3733     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3734          i != (l+1)*NumLaneElts; i += 2, ++j) {
3735       int BitI  = Mask[i];
3736       int BitI1 = Mask[i+1];
3737       if (!isUndefOrEqual(BitI, j))
3738         return false;
3739       if (V2IsSplat) {
3740         if (isUndefOrEqual(BitI1, NumElts))
3741           return false;
3742       } else {
3743         if (!isUndefOrEqual(BitI1, j+NumElts))
3744           return false;
3745       }
3746     }
3747   }
3748   return true;
3749 }
3750
3751 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3752 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3753 /// <0, 0, 1, 1>
3754 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3755   unsigned NumElts = VT.getVectorNumElements();
3756   bool Is256BitVec = VT.is256BitVector();
3757
3758   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3759          "Unsupported vector type for unpckh");
3760
3761   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3762       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3763     return false;
3764
3765   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3766   // FIXME: Need a better way to get rid of this, there's no latency difference
3767   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3768   // the former later. We should also remove the "_undef" special mask.
3769   if (NumElts == 4 && Is256BitVec)
3770     return false;
3771
3772   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3773   // independently on 128-bit lanes.
3774   unsigned NumLanes = VT.getSizeInBits()/128;
3775   unsigned NumLaneElts = NumElts/NumLanes;
3776
3777   for (unsigned l = 0; l != NumLanes; ++l) {
3778     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3779          i != (l+1)*NumLaneElts;
3780          i += 2, ++j) {
3781       int BitI  = Mask[i];
3782       int BitI1 = Mask[i+1];
3783
3784       if (!isUndefOrEqual(BitI, j))
3785         return false;
3786       if (!isUndefOrEqual(BitI1, j))
3787         return false;
3788     }
3789   }
3790
3791   return true;
3792 }
3793
3794 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3795 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3796 /// <2, 2, 3, 3>
3797 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3798   unsigned NumElts = VT.getVectorNumElements();
3799
3800   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3801          "Unsupported vector type for unpckh");
3802
3803   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3804       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3805     return false;
3806
3807   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3808   // independently on 128-bit lanes.
3809   unsigned NumLanes = VT.getSizeInBits()/128;
3810   unsigned NumLaneElts = NumElts/NumLanes;
3811
3812   for (unsigned l = 0; l != NumLanes; ++l) {
3813     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3814          i != (l+1)*NumLaneElts; i += 2, ++j) {
3815       int BitI  = Mask[i];
3816       int BitI1 = Mask[i+1];
3817       if (!isUndefOrEqual(BitI, j))
3818         return false;
3819       if (!isUndefOrEqual(BitI1, j))
3820         return false;
3821     }
3822   }
3823   return true;
3824 }
3825
3826 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3827 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3828 /// MOVSD, and MOVD, i.e. setting the lowest element.
3829 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3830   if (VT.getVectorElementType().getSizeInBits() < 32)
3831     return false;
3832   if (!VT.is128BitVector())
3833     return false;
3834
3835   unsigned NumElts = VT.getVectorNumElements();
3836
3837   if (!isUndefOrEqual(Mask[0], NumElts))
3838     return false;
3839
3840   for (unsigned i = 1; i != NumElts; ++i)
3841     if (!isUndefOrEqual(Mask[i], i))
3842       return false;
3843
3844   return true;
3845 }
3846
3847 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3848 /// as permutations between 128-bit chunks or halves. As an example: this
3849 /// shuffle bellow:
3850 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3851 /// The first half comes from the second half of V1 and the second half from the
3852 /// the second half of V2.
3853 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3854   if (!HasFp256 || !VT.is256BitVector())
3855     return false;
3856
3857   // The shuffle result is divided into half A and half B. In total the two
3858   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3859   // B must come from C, D, E or F.
3860   unsigned HalfSize = VT.getVectorNumElements()/2;
3861   bool MatchA = false, MatchB = false;
3862
3863   // Check if A comes from one of C, D, E, F.
3864   for (unsigned Half = 0; Half != 4; ++Half) {
3865     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3866       MatchA = true;
3867       break;
3868     }
3869   }
3870
3871   // Check if B comes from one of C, D, E, F.
3872   for (unsigned Half = 0; Half != 4; ++Half) {
3873     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3874       MatchB = true;
3875       break;
3876     }
3877   }
3878
3879   return MatchA && MatchB;
3880 }
3881
3882 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3883 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3884 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3885   MVT VT = SVOp->getValueType(0).getSimpleVT();
3886
3887   unsigned HalfSize = VT.getVectorNumElements()/2;
3888
3889   unsigned FstHalf = 0, SndHalf = 0;
3890   for (unsigned i = 0; i < HalfSize; ++i) {
3891     if (SVOp->getMaskElt(i) > 0) {
3892       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3893       break;
3894     }
3895   }
3896   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3897     if (SVOp->getMaskElt(i) > 0) {
3898       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3899       break;
3900     }
3901   }
3902
3903   return (FstHalf | (SndHalf << 4));
3904 }
3905
3906 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3907 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3908 /// Note that VPERMIL mask matching is different depending whether theunderlying
3909 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3910 /// to the same elements of the low, but to the higher half of the source.
3911 /// In VPERMILPD the two lanes could be shuffled independently of each other
3912 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3913 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3914   if (!HasFp256)
3915     return false;
3916
3917   unsigned NumElts = VT.getVectorNumElements();
3918   // Only match 256-bit with 32/64-bit types
3919   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3920     return false;
3921
3922   unsigned NumLanes = VT.getSizeInBits()/128;
3923   unsigned LaneSize = NumElts/NumLanes;
3924   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3925     for (unsigned i = 0; i != LaneSize; ++i) {
3926       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3927         return false;
3928       if (NumElts != 8 || l == 0)
3929         continue;
3930       // VPERMILPS handling
3931       if (Mask[i] < 0)
3932         continue;
3933       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3934         return false;
3935     }
3936   }
3937
3938   return true;
3939 }
3940
3941 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3942 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3943 /// element of vector 2 and the other elements to come from vector 1 in order.
3944 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3945                                bool V2IsSplat = false, bool V2IsUndef = false) {
3946   if (!VT.is128BitVector())
3947     return false;
3948
3949   unsigned NumOps = VT.getVectorNumElements();
3950   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3951     return false;
3952
3953   if (!isUndefOrEqual(Mask[0], 0))
3954     return false;
3955
3956   for (unsigned i = 1; i != NumOps; ++i)
3957     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3958           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3959           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3960       return false;
3961
3962   return true;
3963 }
3964
3965 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3966 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3967 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3968 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3969                            const X86Subtarget *Subtarget) {
3970   if (!Subtarget->hasSSE3())
3971     return false;
3972
3973   unsigned NumElems = VT.getVectorNumElements();
3974
3975   if ((VT.is128BitVector() && NumElems != 4) ||
3976       (VT.is256BitVector() && NumElems != 8))
3977     return false;
3978
3979   // "i+1" is the value the indexed mask element must have
3980   for (unsigned i = 0; i != NumElems; i += 2)
3981     if (!isUndefOrEqual(Mask[i], i+1) ||
3982         !isUndefOrEqual(Mask[i+1], i+1))
3983       return false;
3984
3985   return true;
3986 }
3987
3988 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3989 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3990 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3991 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3992                            const X86Subtarget *Subtarget) {
3993   if (!Subtarget->hasSSE3())
3994     return false;
3995
3996   unsigned NumElems = VT.getVectorNumElements();
3997
3998   if ((VT.is128BitVector() && NumElems != 4) ||
3999       (VT.is256BitVector() && NumElems != 8))
4000     return false;
4001
4002   // "i" is the value the indexed mask element must have
4003   for (unsigned i = 0; i != NumElems; i += 2)
4004     if (!isUndefOrEqual(Mask[i], i) ||
4005         !isUndefOrEqual(Mask[i+1], i))
4006       return false;
4007
4008   return true;
4009 }
4010
4011 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4012 /// specifies a shuffle of elements that is suitable for input to 256-bit
4013 /// version of MOVDDUP.
4014 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4015   if (!HasFp256 || !VT.is256BitVector())
4016     return false;
4017
4018   unsigned NumElts = VT.getVectorNumElements();
4019   if (NumElts != 4)
4020     return false;
4021
4022   for (unsigned i = 0; i != NumElts/2; ++i)
4023     if (!isUndefOrEqual(Mask[i], 0))
4024       return false;
4025   for (unsigned i = NumElts/2; i != NumElts; ++i)
4026     if (!isUndefOrEqual(Mask[i], NumElts/2))
4027       return false;
4028   return true;
4029 }
4030
4031 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4032 /// specifies a shuffle of elements that is suitable for input to 128-bit
4033 /// version of MOVDDUP.
4034 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4035   if (!VT.is128BitVector())
4036     return false;
4037
4038   unsigned e = VT.getVectorNumElements() / 2;
4039   for (unsigned i = 0; i != e; ++i)
4040     if (!isUndefOrEqual(Mask[i], i))
4041       return false;
4042   for (unsigned i = 0; i != e; ++i)
4043     if (!isUndefOrEqual(Mask[e+i], i))
4044       return false;
4045   return true;
4046 }
4047
4048 /// isVEXTRACTF128Index - Return true if the specified
4049 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4050 /// suitable for input to VEXTRACTF128.
4051 bool X86::isVEXTRACTF128Index(SDNode *N) {
4052   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4053     return false;
4054
4055   // The index should be aligned on a 128-bit boundary.
4056   uint64_t Index =
4057     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4058
4059   MVT VT = N->getValueType(0).getSimpleVT();
4060   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4061   bool Result = (Index * ElSize) % 128 == 0;
4062
4063   return Result;
4064 }
4065
4066 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4067 /// operand specifies a subvector insert that is suitable for input to
4068 /// VINSERTF128.
4069 bool X86::isVINSERTF128Index(SDNode *N) {
4070   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4071     return false;
4072
4073   // The index should be aligned on a 128-bit boundary.
4074   uint64_t Index =
4075     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4076
4077   MVT VT = N->getValueType(0).getSimpleVT();
4078   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4079   bool Result = (Index * ElSize) % 128 == 0;
4080
4081   return Result;
4082 }
4083
4084 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4085 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4086 /// Handles 128-bit and 256-bit.
4087 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4088   MVT VT = N->getValueType(0).getSimpleVT();
4089
4090   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4091          "Unsupported vector type for PSHUF/SHUFP");
4092
4093   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4094   // independently on 128-bit lanes.
4095   unsigned NumElts = VT.getVectorNumElements();
4096   unsigned NumLanes = VT.getSizeInBits()/128;
4097   unsigned NumLaneElts = NumElts/NumLanes;
4098
4099   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4100          "Only supports 2 or 4 elements per lane");
4101
4102   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4103   unsigned Mask = 0;
4104   for (unsigned i = 0; i != NumElts; ++i) {
4105     int Elt = N->getMaskElt(i);
4106     if (Elt < 0) continue;
4107     Elt &= NumLaneElts - 1;
4108     unsigned ShAmt = (i << Shift) % 8;
4109     Mask |= Elt << ShAmt;
4110   }
4111
4112   return Mask;
4113 }
4114
4115 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4116 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4117 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4118   MVT VT = N->getValueType(0).getSimpleVT();
4119
4120   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4121          "Unsupported vector type for PSHUFHW");
4122
4123   unsigned NumElts = VT.getVectorNumElements();
4124
4125   unsigned Mask = 0;
4126   for (unsigned l = 0; l != NumElts; l += 8) {
4127     // 8 nodes per lane, but we only care about the last 4.
4128     for (unsigned i = 0; i < 4; ++i) {
4129       int Elt = N->getMaskElt(l+i+4);
4130       if (Elt < 0) continue;
4131       Elt &= 0x3; // only 2-bits.
4132       Mask |= Elt << (i * 2);
4133     }
4134   }
4135
4136   return Mask;
4137 }
4138
4139 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4140 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4141 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4142   MVT VT = N->getValueType(0).getSimpleVT();
4143
4144   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4145          "Unsupported vector type for PSHUFHW");
4146
4147   unsigned NumElts = VT.getVectorNumElements();
4148
4149   unsigned Mask = 0;
4150   for (unsigned l = 0; l != NumElts; l += 8) {
4151     // 8 nodes per lane, but we only care about the first 4.
4152     for (unsigned i = 0; i < 4; ++i) {
4153       int Elt = N->getMaskElt(l+i);
4154       if (Elt < 0) continue;
4155       Elt &= 0x3; // only 2-bits
4156       Mask |= Elt << (i * 2);
4157     }
4158   }
4159
4160   return Mask;
4161 }
4162
4163 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4164 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4165 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4166   MVT VT = SVOp->getValueType(0).getSimpleVT();
4167   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4168
4169   unsigned NumElts = VT.getVectorNumElements();
4170   unsigned NumLanes = VT.getSizeInBits()/128;
4171   unsigned NumLaneElts = NumElts/NumLanes;
4172
4173   int Val = 0;
4174   unsigned i;
4175   for (i = 0; i != NumElts; ++i) {
4176     Val = SVOp->getMaskElt(i);
4177     if (Val >= 0)
4178       break;
4179   }
4180   if (Val >= (int)NumElts)
4181     Val -= NumElts - NumLaneElts;
4182
4183   assert(Val - i > 0 && "PALIGNR imm should be positive");
4184   return (Val - i) * EltSize;
4185 }
4186
4187 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4188 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4189 /// instructions.
4190 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4191   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4192     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4193
4194   uint64_t Index =
4195     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4196
4197   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4198   MVT ElVT = VecVT.getVectorElementType();
4199
4200   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4201   return Index / NumElemsPerChunk;
4202 }
4203
4204 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4205 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4206 /// instructions.
4207 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4208   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4209     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4210
4211   uint64_t Index =
4212     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4213
4214   MVT VecVT = N->getValueType(0).getSimpleVT();
4215   MVT ElVT = VecVT.getVectorElementType();
4216
4217   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4218   return Index / NumElemsPerChunk;
4219 }
4220
4221 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4222 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4223 /// Handles 256-bit.
4224 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4225   MVT VT = N->getValueType(0).getSimpleVT();
4226
4227   unsigned NumElts = VT.getVectorNumElements();
4228
4229   assert((VT.is256BitVector() && NumElts == 4) &&
4230          "Unsupported vector type for VPERMQ/VPERMPD");
4231
4232   unsigned Mask = 0;
4233   for (unsigned i = 0; i != NumElts; ++i) {
4234     int Elt = N->getMaskElt(i);
4235     if (Elt < 0)
4236       continue;
4237     Mask |= Elt << (i*2);
4238   }
4239
4240   return Mask;
4241 }
4242 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4243 /// constant +0.0.
4244 bool X86::isZeroNode(SDValue Elt) {
4245   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4246     return CN->isNullValue();
4247   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4248     return CFP->getValueAPF().isPosZero();
4249   return false;
4250 }
4251
4252 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4253 /// their permute mask.
4254 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4255                                     SelectionDAG &DAG) {
4256   MVT VT = SVOp->getValueType(0).getSimpleVT();
4257   unsigned NumElems = VT.getVectorNumElements();
4258   SmallVector<int, 8> MaskVec;
4259
4260   for (unsigned i = 0; i != NumElems; ++i) {
4261     int Idx = SVOp->getMaskElt(i);
4262     if (Idx >= 0) {
4263       if (Idx < (int)NumElems)
4264         Idx += NumElems;
4265       else
4266         Idx -= NumElems;
4267     }
4268     MaskVec.push_back(Idx);
4269   }
4270   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4271                               SVOp->getOperand(0), &MaskVec[0]);
4272 }
4273
4274 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4275 /// match movhlps. The lower half elements should come from upper half of
4276 /// V1 (and in order), and the upper half elements should come from the upper
4277 /// half of V2 (and in order).
4278 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4279   if (!VT.is128BitVector())
4280     return false;
4281   if (VT.getVectorNumElements() != 4)
4282     return false;
4283   for (unsigned i = 0, e = 2; i != e; ++i)
4284     if (!isUndefOrEqual(Mask[i], i+2))
4285       return false;
4286   for (unsigned i = 2; i != 4; ++i)
4287     if (!isUndefOrEqual(Mask[i], i+4))
4288       return false;
4289   return true;
4290 }
4291
4292 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4293 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4294 /// required.
4295 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4296   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4297     return false;
4298   N = N->getOperand(0).getNode();
4299   if (!ISD::isNON_EXTLoad(N))
4300     return false;
4301   if (LD)
4302     *LD = cast<LoadSDNode>(N);
4303   return true;
4304 }
4305
4306 // Test whether the given value is a vector value which will be legalized
4307 // into a load.
4308 static bool WillBeConstantPoolLoad(SDNode *N) {
4309   if (N->getOpcode() != ISD::BUILD_VECTOR)
4310     return false;
4311
4312   // Check for any non-constant elements.
4313   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4314     switch (N->getOperand(i).getNode()->getOpcode()) {
4315     case ISD::UNDEF:
4316     case ISD::ConstantFP:
4317     case ISD::Constant:
4318       break;
4319     default:
4320       return false;
4321     }
4322
4323   // Vectors of all-zeros and all-ones are materialized with special
4324   // instructions rather than being loaded.
4325   return !ISD::isBuildVectorAllZeros(N) &&
4326          !ISD::isBuildVectorAllOnes(N);
4327 }
4328
4329 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4330 /// match movlp{s|d}. The lower half elements should come from lower half of
4331 /// V1 (and in order), and the upper half elements should come from the upper
4332 /// half of V2 (and in order). And since V1 will become the source of the
4333 /// MOVLP, it must be either a vector load or a scalar load to vector.
4334 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4335                                ArrayRef<int> Mask, EVT VT) {
4336   if (!VT.is128BitVector())
4337     return false;
4338
4339   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4340     return false;
4341   // Is V2 is a vector load, don't do this transformation. We will try to use
4342   // load folding shufps op.
4343   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4344     return false;
4345
4346   unsigned NumElems = VT.getVectorNumElements();
4347
4348   if (NumElems != 2 && NumElems != 4)
4349     return false;
4350   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4351     if (!isUndefOrEqual(Mask[i], i))
4352       return false;
4353   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4354     if (!isUndefOrEqual(Mask[i], i+NumElems))
4355       return false;
4356   return true;
4357 }
4358
4359 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4360 /// all the same.
4361 static bool isSplatVector(SDNode *N) {
4362   if (N->getOpcode() != ISD::BUILD_VECTOR)
4363     return false;
4364
4365   SDValue SplatValue = N->getOperand(0);
4366   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4367     if (N->getOperand(i) != SplatValue)
4368       return false;
4369   return true;
4370 }
4371
4372 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4373 /// to an zero vector.
4374 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4375 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4376   SDValue V1 = N->getOperand(0);
4377   SDValue V2 = N->getOperand(1);
4378   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4379   for (unsigned i = 0; i != NumElems; ++i) {
4380     int Idx = N->getMaskElt(i);
4381     if (Idx >= (int)NumElems) {
4382       unsigned Opc = V2.getOpcode();
4383       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4384         continue;
4385       if (Opc != ISD::BUILD_VECTOR ||
4386           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4387         return false;
4388     } else if (Idx >= 0) {
4389       unsigned Opc = V1.getOpcode();
4390       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4391         continue;
4392       if (Opc != ISD::BUILD_VECTOR ||
4393           !X86::isZeroNode(V1.getOperand(Idx)))
4394         return false;
4395     }
4396   }
4397   return true;
4398 }
4399
4400 /// getZeroVector - Returns a vector of specified type with all zero elements.
4401 ///
4402 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4403                              SelectionDAG &DAG, DebugLoc dl) {
4404   assert(VT.isVector() && "Expected a vector type");
4405
4406   // Always build SSE zero vectors as <4 x i32> bitcasted
4407   // to their dest type. This ensures they get CSE'd.
4408   SDValue Vec;
4409   if (VT.is128BitVector()) {  // SSE
4410     if (Subtarget->hasSSE2()) {  // SSE2
4411       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4412       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4413     } else { // SSE1
4414       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4415       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4416     }
4417   } else if (VT.is256BitVector()) { // AVX
4418     if (Subtarget->hasInt256()) { // AVX2
4419       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4420       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4421       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4422                         array_lengthof(Ops));
4423     } else {
4424       // 256-bit logic and arithmetic instructions in AVX are all
4425       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4426       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4427       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4428       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4429                         array_lengthof(Ops));
4430     }
4431   } else
4432     llvm_unreachable("Unexpected vector type");
4433
4434   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4435 }
4436
4437 /// getOnesVector - Returns a vector of specified type with all bits set.
4438 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4439 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4440 /// Then bitcast to their original type, ensuring they get CSE'd.
4441 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4442                              DebugLoc dl) {
4443   assert(VT.isVector() && "Expected a vector type");
4444
4445   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4446   SDValue Vec;
4447   if (VT.is256BitVector()) {
4448     if (HasInt256) { // AVX2
4449       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4450       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4451                         array_lengthof(Ops));
4452     } else { // AVX
4453       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4454       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4455     }
4456   } else if (VT.is128BitVector()) {
4457     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4458   } else
4459     llvm_unreachable("Unexpected vector type");
4460
4461   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4462 }
4463
4464 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4465 /// that point to V2 points to its first element.
4466 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4467   for (unsigned i = 0; i != NumElems; ++i) {
4468     if (Mask[i] > (int)NumElems) {
4469       Mask[i] = NumElems;
4470     }
4471   }
4472 }
4473
4474 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4475 /// operation of specified width.
4476 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4477                        SDValue V2) {
4478   unsigned NumElems = VT.getVectorNumElements();
4479   SmallVector<int, 8> Mask;
4480   Mask.push_back(NumElems);
4481   for (unsigned i = 1; i != NumElems; ++i)
4482     Mask.push_back(i);
4483   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4484 }
4485
4486 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4487 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4488                           SDValue V2) {
4489   unsigned NumElems = VT.getVectorNumElements();
4490   SmallVector<int, 8> Mask;
4491   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4492     Mask.push_back(i);
4493     Mask.push_back(i + NumElems);
4494   }
4495   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4496 }
4497
4498 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4499 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4500                           SDValue V2) {
4501   unsigned NumElems = VT.getVectorNumElements();
4502   SmallVector<int, 8> Mask;
4503   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4504     Mask.push_back(i + Half);
4505     Mask.push_back(i + NumElems + Half);
4506   }
4507   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4508 }
4509
4510 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4511 // a generic shuffle instruction because the target has no such instructions.
4512 // Generate shuffles which repeat i16 and i8 several times until they can be
4513 // represented by v4f32 and then be manipulated by target suported shuffles.
4514 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4515   EVT VT = V.getValueType();
4516   int NumElems = VT.getVectorNumElements();
4517   DebugLoc dl = V.getDebugLoc();
4518
4519   while (NumElems > 4) {
4520     if (EltNo < NumElems/2) {
4521       V = getUnpackl(DAG, dl, VT, V, V);
4522     } else {
4523       V = getUnpackh(DAG, dl, VT, V, V);
4524       EltNo -= NumElems/2;
4525     }
4526     NumElems >>= 1;
4527   }
4528   return V;
4529 }
4530
4531 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4532 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4533   EVT VT = V.getValueType();
4534   DebugLoc dl = V.getDebugLoc();
4535
4536   if (VT.is128BitVector()) {
4537     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4538     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4539     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4540                              &SplatMask[0]);
4541   } else if (VT.is256BitVector()) {
4542     // To use VPERMILPS to splat scalars, the second half of indicies must
4543     // refer to the higher part, which is a duplication of the lower one,
4544     // because VPERMILPS can only handle in-lane permutations.
4545     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4546                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4547
4548     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4549     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4550                              &SplatMask[0]);
4551   } else
4552     llvm_unreachable("Vector size not supported");
4553
4554   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4555 }
4556
4557 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4558 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4559   EVT SrcVT = SV->getValueType(0);
4560   SDValue V1 = SV->getOperand(0);
4561   DebugLoc dl = SV->getDebugLoc();
4562
4563   int EltNo = SV->getSplatIndex();
4564   int NumElems = SrcVT.getVectorNumElements();
4565   bool Is256BitVec = SrcVT.is256BitVector();
4566
4567   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4568          "Unknown how to promote splat for type");
4569
4570   // Extract the 128-bit part containing the splat element and update
4571   // the splat element index when it refers to the higher register.
4572   if (Is256BitVec) {
4573     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4574     if (EltNo >= NumElems/2)
4575       EltNo -= NumElems/2;
4576   }
4577
4578   // All i16 and i8 vector types can't be used directly by a generic shuffle
4579   // instruction because the target has no such instruction. Generate shuffles
4580   // which repeat i16 and i8 several times until they fit in i32, and then can
4581   // be manipulated by target suported shuffles.
4582   EVT EltVT = SrcVT.getVectorElementType();
4583   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4584     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4585
4586   // Recreate the 256-bit vector and place the same 128-bit vector
4587   // into the low and high part. This is necessary because we want
4588   // to use VPERM* to shuffle the vectors
4589   if (Is256BitVec) {
4590     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4591   }
4592
4593   return getLegalSplat(DAG, V1, EltNo);
4594 }
4595
4596 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4597 /// vector of zero or undef vector.  This produces a shuffle where the low
4598 /// element of V2 is swizzled into the zero/undef vector, landing at element
4599 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4600 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4601                                            bool IsZero,
4602                                            const X86Subtarget *Subtarget,
4603                                            SelectionDAG &DAG) {
4604   EVT VT = V2.getValueType();
4605   SDValue V1 = IsZero
4606     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4607   unsigned NumElems = VT.getVectorNumElements();
4608   SmallVector<int, 16> MaskVec;
4609   for (unsigned i = 0; i != NumElems; ++i)
4610     // If this is the insertion idx, put the low elt of V2 here.
4611     MaskVec.push_back(i == Idx ? NumElems : i);
4612   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4613 }
4614
4615 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4616 /// target specific opcode. Returns true if the Mask could be calculated.
4617 /// Sets IsUnary to true if only uses one source.
4618 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4619                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4620   unsigned NumElems = VT.getVectorNumElements();
4621   SDValue ImmN;
4622
4623   IsUnary = false;
4624   switch(N->getOpcode()) {
4625   case X86ISD::SHUFP:
4626     ImmN = N->getOperand(N->getNumOperands()-1);
4627     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4628     break;
4629   case X86ISD::UNPCKH:
4630     DecodeUNPCKHMask(VT, Mask);
4631     break;
4632   case X86ISD::UNPCKL:
4633     DecodeUNPCKLMask(VT, Mask);
4634     break;
4635   case X86ISD::MOVHLPS:
4636     DecodeMOVHLPSMask(NumElems, Mask);
4637     break;
4638   case X86ISD::MOVLHPS:
4639     DecodeMOVLHPSMask(NumElems, Mask);
4640     break;
4641   case X86ISD::PALIGNR:
4642     ImmN = N->getOperand(N->getNumOperands()-1);
4643     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4644     break;
4645   case X86ISD::PSHUFD:
4646   case X86ISD::VPERMILP:
4647     ImmN = N->getOperand(N->getNumOperands()-1);
4648     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4649     IsUnary = true;
4650     break;
4651   case X86ISD::PSHUFHW:
4652     ImmN = N->getOperand(N->getNumOperands()-1);
4653     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4654     IsUnary = true;
4655     break;
4656   case X86ISD::PSHUFLW:
4657     ImmN = N->getOperand(N->getNumOperands()-1);
4658     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4659     IsUnary = true;
4660     break;
4661   case X86ISD::VPERMI:
4662     ImmN = N->getOperand(N->getNumOperands()-1);
4663     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4664     IsUnary = true;
4665     break;
4666   case X86ISD::MOVSS:
4667   case X86ISD::MOVSD: {
4668     // The index 0 always comes from the first element of the second source,
4669     // this is why MOVSS and MOVSD are used in the first place. The other
4670     // elements come from the other positions of the first source vector
4671     Mask.push_back(NumElems);
4672     for (unsigned i = 1; i != NumElems; ++i) {
4673       Mask.push_back(i);
4674     }
4675     break;
4676   }
4677   case X86ISD::VPERM2X128:
4678     ImmN = N->getOperand(N->getNumOperands()-1);
4679     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4680     if (Mask.empty()) return false;
4681     break;
4682   case X86ISD::MOVDDUP:
4683   case X86ISD::MOVLHPD:
4684   case X86ISD::MOVLPD:
4685   case X86ISD::MOVLPS:
4686   case X86ISD::MOVSHDUP:
4687   case X86ISD::MOVSLDUP:
4688     // Not yet implemented
4689     return false;
4690   default: llvm_unreachable("unknown target shuffle node");
4691   }
4692
4693   return true;
4694 }
4695
4696 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4697 /// element of the result of the vector shuffle.
4698 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4699                                    unsigned Depth) {
4700   if (Depth == 6)
4701     return SDValue();  // Limit search depth.
4702
4703   SDValue V = SDValue(N, 0);
4704   EVT VT = V.getValueType();
4705   unsigned Opcode = V.getOpcode();
4706
4707   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4708   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4709     int Elt = SV->getMaskElt(Index);
4710
4711     if (Elt < 0)
4712       return DAG.getUNDEF(VT.getVectorElementType());
4713
4714     unsigned NumElems = VT.getVectorNumElements();
4715     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4716                                          : SV->getOperand(1);
4717     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4718   }
4719
4720   // Recurse into target specific vector shuffles to find scalars.
4721   if (isTargetShuffle(Opcode)) {
4722     MVT ShufVT = V.getValueType().getSimpleVT();
4723     unsigned NumElems = ShufVT.getVectorNumElements();
4724     SmallVector<int, 16> ShuffleMask;
4725     bool IsUnary;
4726
4727     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4728       return SDValue();
4729
4730     int Elt = ShuffleMask[Index];
4731     if (Elt < 0)
4732       return DAG.getUNDEF(ShufVT.getVectorElementType());
4733
4734     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4735                                          : N->getOperand(1);
4736     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4737                                Depth+1);
4738   }
4739
4740   // Actual nodes that may contain scalar elements
4741   if (Opcode == ISD::BITCAST) {
4742     V = V.getOperand(0);
4743     EVT SrcVT = V.getValueType();
4744     unsigned NumElems = VT.getVectorNumElements();
4745
4746     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4747       return SDValue();
4748   }
4749
4750   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4751     return (Index == 0) ? V.getOperand(0)
4752                         : DAG.getUNDEF(VT.getVectorElementType());
4753
4754   if (V.getOpcode() == ISD::BUILD_VECTOR)
4755     return V.getOperand(Index);
4756
4757   return SDValue();
4758 }
4759
4760 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4761 /// shuffle operation which come from a consecutively from a zero. The
4762 /// search can start in two different directions, from left or right.
4763 static
4764 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4765                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4766   unsigned i;
4767   for (i = 0; i != NumElems; ++i) {
4768     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4769     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4770     if (!(Elt.getNode() &&
4771          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4772       break;
4773   }
4774
4775   return i;
4776 }
4777
4778 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4779 /// correspond consecutively to elements from one of the vector operands,
4780 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4781 static
4782 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4783                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4784                               unsigned NumElems, unsigned &OpNum) {
4785   bool SeenV1 = false;
4786   bool SeenV2 = false;
4787
4788   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4789     int Idx = SVOp->getMaskElt(i);
4790     // Ignore undef indicies
4791     if (Idx < 0)
4792       continue;
4793
4794     if (Idx < (int)NumElems)
4795       SeenV1 = true;
4796     else
4797       SeenV2 = true;
4798
4799     // Only accept consecutive elements from the same vector
4800     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4801       return false;
4802   }
4803
4804   OpNum = SeenV1 ? 0 : 1;
4805   return true;
4806 }
4807
4808 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4809 /// logical left shift of a vector.
4810 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4811                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4812   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4813   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4814               false /* check zeros from right */, DAG);
4815   unsigned OpSrc;
4816
4817   if (!NumZeros)
4818     return false;
4819
4820   // Considering the elements in the mask that are not consecutive zeros,
4821   // check if they consecutively come from only one of the source vectors.
4822   //
4823   //               V1 = {X, A, B, C}     0
4824   //                         \  \  \    /
4825   //   vector_shuffle V1, V2 <1, 2, 3, X>
4826   //
4827   if (!isShuffleMaskConsecutive(SVOp,
4828             0,                   // Mask Start Index
4829             NumElems-NumZeros,   // Mask End Index(exclusive)
4830             NumZeros,            // Where to start looking in the src vector
4831             NumElems,            // Number of elements in vector
4832             OpSrc))              // Which source operand ?
4833     return false;
4834
4835   isLeft = false;
4836   ShAmt = NumZeros;
4837   ShVal = SVOp->getOperand(OpSrc);
4838   return true;
4839 }
4840
4841 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4842 /// logical left shift of a vector.
4843 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4844                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4845   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4846   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4847               true /* check zeros from left */, DAG);
4848   unsigned OpSrc;
4849
4850   if (!NumZeros)
4851     return false;
4852
4853   // Considering the elements in the mask that are not consecutive zeros,
4854   // check if they consecutively come from only one of the source vectors.
4855   //
4856   //                           0    { A, B, X, X } = V2
4857   //                          / \    /  /
4858   //   vector_shuffle V1, V2 <X, X, 4, 5>
4859   //
4860   if (!isShuffleMaskConsecutive(SVOp,
4861             NumZeros,     // Mask Start Index
4862             NumElems,     // Mask End Index(exclusive)
4863             0,            // Where to start looking in the src vector
4864             NumElems,     // Number of elements in vector
4865             OpSrc))       // Which source operand ?
4866     return false;
4867
4868   isLeft = true;
4869   ShAmt = NumZeros;
4870   ShVal = SVOp->getOperand(OpSrc);
4871   return true;
4872 }
4873
4874 /// isVectorShift - Returns true if the shuffle can be implemented as a
4875 /// logical left or right shift of a vector.
4876 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4877                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4878   // Although the logic below support any bitwidth size, there are no
4879   // shift instructions which handle more than 128-bit vectors.
4880   if (!SVOp->getValueType(0).is128BitVector())
4881     return false;
4882
4883   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4884       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4885     return true;
4886
4887   return false;
4888 }
4889
4890 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4891 ///
4892 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4893                                        unsigned NumNonZero, unsigned NumZero,
4894                                        SelectionDAG &DAG,
4895                                        const X86Subtarget* Subtarget,
4896                                        const TargetLowering &TLI) {
4897   if (NumNonZero > 8)
4898     return SDValue();
4899
4900   DebugLoc dl = Op.getDebugLoc();
4901   SDValue V(0, 0);
4902   bool First = true;
4903   for (unsigned i = 0; i < 16; ++i) {
4904     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4905     if (ThisIsNonZero && First) {
4906       if (NumZero)
4907         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4908       else
4909         V = DAG.getUNDEF(MVT::v8i16);
4910       First = false;
4911     }
4912
4913     if ((i & 1) != 0) {
4914       SDValue ThisElt(0, 0), LastElt(0, 0);
4915       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4916       if (LastIsNonZero) {
4917         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4918                               MVT::i16, Op.getOperand(i-1));
4919       }
4920       if (ThisIsNonZero) {
4921         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4922         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4923                               ThisElt, DAG.getConstant(8, MVT::i8));
4924         if (LastIsNonZero)
4925           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4926       } else
4927         ThisElt = LastElt;
4928
4929       if (ThisElt.getNode())
4930         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4931                         DAG.getIntPtrConstant(i/2));
4932     }
4933   }
4934
4935   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4936 }
4937
4938 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4939 ///
4940 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4941                                      unsigned NumNonZero, unsigned NumZero,
4942                                      SelectionDAG &DAG,
4943                                      const X86Subtarget* Subtarget,
4944                                      const TargetLowering &TLI) {
4945   if (NumNonZero > 4)
4946     return SDValue();
4947
4948   DebugLoc dl = Op.getDebugLoc();
4949   SDValue V(0, 0);
4950   bool First = true;
4951   for (unsigned i = 0; i < 8; ++i) {
4952     bool isNonZero = (NonZeros & (1 << i)) != 0;
4953     if (isNonZero) {
4954       if (First) {
4955         if (NumZero)
4956           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4957         else
4958           V = DAG.getUNDEF(MVT::v8i16);
4959         First = false;
4960       }
4961       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4962                       MVT::v8i16, V, Op.getOperand(i),
4963                       DAG.getIntPtrConstant(i));
4964     }
4965   }
4966
4967   return V;
4968 }
4969
4970 /// getVShift - Return a vector logical shift node.
4971 ///
4972 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4973                          unsigned NumBits, SelectionDAG &DAG,
4974                          const TargetLowering &TLI, DebugLoc dl) {
4975   assert(VT.is128BitVector() && "Unknown type for VShift");
4976   EVT ShVT = MVT::v2i64;
4977   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4978   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4979   return DAG.getNode(ISD::BITCAST, dl, VT,
4980                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4981                              DAG.getConstant(NumBits,
4982                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4983 }
4984
4985 SDValue
4986 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4987                                           SelectionDAG &DAG) const {
4988
4989   // Check if the scalar load can be widened into a vector load. And if
4990   // the address is "base + cst" see if the cst can be "absorbed" into
4991   // the shuffle mask.
4992   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4993     SDValue Ptr = LD->getBasePtr();
4994     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4995       return SDValue();
4996     EVT PVT = LD->getValueType(0);
4997     if (PVT != MVT::i32 && PVT != MVT::f32)
4998       return SDValue();
4999
5000     int FI = -1;
5001     int64_t Offset = 0;
5002     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5003       FI = FINode->getIndex();
5004       Offset = 0;
5005     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5006                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5007       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5008       Offset = Ptr.getConstantOperandVal(1);
5009       Ptr = Ptr.getOperand(0);
5010     } else {
5011       return SDValue();
5012     }
5013
5014     // FIXME: 256-bit vector instructions don't require a strict alignment,
5015     // improve this code to support it better.
5016     unsigned RequiredAlign = VT.getSizeInBits()/8;
5017     SDValue Chain = LD->getChain();
5018     // Make sure the stack object alignment is at least 16 or 32.
5019     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5020     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5021       if (MFI->isFixedObjectIndex(FI)) {
5022         // Can't change the alignment. FIXME: It's possible to compute
5023         // the exact stack offset and reference FI + adjust offset instead.
5024         // If someone *really* cares about this. That's the way to implement it.
5025         return SDValue();
5026       } else {
5027         MFI->setObjectAlignment(FI, RequiredAlign);
5028       }
5029     }
5030
5031     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5032     // Ptr + (Offset & ~15).
5033     if (Offset < 0)
5034       return SDValue();
5035     if ((Offset % RequiredAlign) & 3)
5036       return SDValue();
5037     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5038     if (StartOffset)
5039       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5040                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5041
5042     int EltNo = (Offset - StartOffset) >> 2;
5043     unsigned NumElems = VT.getVectorNumElements();
5044
5045     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5046     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5047                              LD->getPointerInfo().getWithOffset(StartOffset),
5048                              false, false, false, 0);
5049
5050     SmallVector<int, 8> Mask;
5051     for (unsigned i = 0; i != NumElems; ++i)
5052       Mask.push_back(EltNo);
5053
5054     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5055   }
5056
5057   return SDValue();
5058 }
5059
5060 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5061 /// vector of type 'VT', see if the elements can be replaced by a single large
5062 /// load which has the same value as a build_vector whose operands are 'elts'.
5063 ///
5064 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5065 ///
5066 /// FIXME: we'd also like to handle the case where the last elements are zero
5067 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5068 /// There's even a handy isZeroNode for that purpose.
5069 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5070                                         DebugLoc &DL, SelectionDAG &DAG) {
5071   EVT EltVT = VT.getVectorElementType();
5072   unsigned NumElems = Elts.size();
5073
5074   LoadSDNode *LDBase = NULL;
5075   unsigned LastLoadedElt = -1U;
5076
5077   // For each element in the initializer, see if we've found a load or an undef.
5078   // If we don't find an initial load element, or later load elements are
5079   // non-consecutive, bail out.
5080   for (unsigned i = 0; i < NumElems; ++i) {
5081     SDValue Elt = Elts[i];
5082
5083     if (!Elt.getNode() ||
5084         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5085       return SDValue();
5086     if (!LDBase) {
5087       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5088         return SDValue();
5089       LDBase = cast<LoadSDNode>(Elt.getNode());
5090       LastLoadedElt = i;
5091       continue;
5092     }
5093     if (Elt.getOpcode() == ISD::UNDEF)
5094       continue;
5095
5096     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5097     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5098       return SDValue();
5099     LastLoadedElt = i;
5100   }
5101
5102   // If we have found an entire vector of loads and undefs, then return a large
5103   // load of the entire vector width starting at the base pointer.  If we found
5104   // consecutive loads for the low half, generate a vzext_load node.
5105   if (LastLoadedElt == NumElems - 1) {
5106     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5107       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5108                          LDBase->getPointerInfo(),
5109                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5110                          LDBase->isInvariant(), 0);
5111     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5112                        LDBase->getPointerInfo(),
5113                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5114                        LDBase->isInvariant(), LDBase->getAlignment());
5115   }
5116   if (NumElems == 4 && LastLoadedElt == 1 &&
5117       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5118     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5119     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5120     SDValue ResNode =
5121         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5122                                 array_lengthof(Ops), MVT::i64,
5123                                 LDBase->getPointerInfo(),
5124                                 LDBase->getAlignment(),
5125                                 false/*isVolatile*/, true/*ReadMem*/,
5126                                 false/*WriteMem*/);
5127
5128     // Make sure the newly-created LOAD is in the same position as LDBase in
5129     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5130     // update uses of LDBase's output chain to use the TokenFactor.
5131     if (LDBase->hasAnyUseOfValue(1)) {
5132       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5133                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5134       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5135       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5136                              SDValue(ResNode.getNode(), 1));
5137     }
5138
5139     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5140   }
5141   return SDValue();
5142 }
5143
5144 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5145 /// to generate a splat value for the following cases:
5146 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5147 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5148 /// a scalar load, or a constant.
5149 /// The VBROADCAST node is returned when a pattern is found,
5150 /// or SDValue() otherwise.
5151 SDValue
5152 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5153   if (!Subtarget->hasFp256())
5154     return SDValue();
5155
5156   MVT VT = Op.getValueType().getSimpleVT();
5157   DebugLoc dl = Op.getDebugLoc();
5158
5159   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5160          "Unsupported vector type for broadcast.");
5161
5162   SDValue Ld;
5163   bool ConstSplatVal;
5164
5165   switch (Op.getOpcode()) {
5166     default:
5167       // Unknown pattern found.
5168       return SDValue();
5169
5170     case ISD::BUILD_VECTOR: {
5171       // The BUILD_VECTOR node must be a splat.
5172       if (!isSplatVector(Op.getNode()))
5173         return SDValue();
5174
5175       Ld = Op.getOperand(0);
5176       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5177                      Ld.getOpcode() == ISD::ConstantFP);
5178
5179       // The suspected load node has several users. Make sure that all
5180       // of its users are from the BUILD_VECTOR node.
5181       // Constants may have multiple users.
5182       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5183         return SDValue();
5184       break;
5185     }
5186
5187     case ISD::VECTOR_SHUFFLE: {
5188       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5189
5190       // Shuffles must have a splat mask where the first element is
5191       // broadcasted.
5192       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5193         return SDValue();
5194
5195       SDValue Sc = Op.getOperand(0);
5196       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5197           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5198
5199         if (!Subtarget->hasInt256())
5200           return SDValue();
5201
5202         // Use the register form of the broadcast instruction available on AVX2.
5203         if (VT.is256BitVector())
5204           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5205         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5206       }
5207
5208       Ld = Sc.getOperand(0);
5209       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5210                        Ld.getOpcode() == ISD::ConstantFP);
5211
5212       // The scalar_to_vector node and the suspected
5213       // load node must have exactly one user.
5214       // Constants may have multiple users.
5215       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5216         return SDValue();
5217       break;
5218     }
5219   }
5220
5221   bool Is256 = VT.is256BitVector();
5222
5223   // Handle the broadcasting a single constant scalar from the constant pool
5224   // into a vector. On Sandybridge it is still better to load a constant vector
5225   // from the constant pool and not to broadcast it from a scalar.
5226   if (ConstSplatVal && Subtarget->hasInt256()) {
5227     EVT CVT = Ld.getValueType();
5228     assert(!CVT.isVector() && "Must not broadcast a vector type");
5229     unsigned ScalarSize = CVT.getSizeInBits();
5230
5231     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5232       const Constant *C = 0;
5233       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5234         C = CI->getConstantIntValue();
5235       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5236         C = CF->getConstantFPValue();
5237
5238       assert(C && "Invalid constant type");
5239
5240       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5241       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5242       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5243                        MachinePointerInfo::getConstantPool(),
5244                        false, false, false, Alignment);
5245
5246       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5247     }
5248   }
5249
5250   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5251   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5252
5253   // Handle AVX2 in-register broadcasts.
5254   if (!IsLoad && Subtarget->hasInt256() &&
5255       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5256     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5257
5258   // The scalar source must be a normal load.
5259   if (!IsLoad)
5260     return SDValue();
5261
5262   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5263     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5264
5265   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5266   // double since there is no vbroadcastsd xmm
5267   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5268     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5269       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5270   }
5271
5272   // Unsupported broadcast.
5273   return SDValue();
5274 }
5275
5276 SDValue
5277 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5278   EVT VT = Op.getValueType();
5279
5280   // Skip if insert_vec_elt is not supported.
5281   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5282     return SDValue();
5283
5284   DebugLoc DL = Op.getDebugLoc();
5285   unsigned NumElems = Op.getNumOperands();
5286
5287   SDValue VecIn1;
5288   SDValue VecIn2;
5289   SmallVector<unsigned, 4> InsertIndices;
5290   SmallVector<int, 8> Mask(NumElems, -1);
5291
5292   for (unsigned i = 0; i != NumElems; ++i) {
5293     unsigned Opc = Op.getOperand(i).getOpcode();
5294
5295     if (Opc == ISD::UNDEF)
5296       continue;
5297
5298     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5299       // Quit if more than 1 elements need inserting.
5300       if (InsertIndices.size() > 1)
5301         return SDValue();
5302
5303       InsertIndices.push_back(i);
5304       continue;
5305     }
5306
5307     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5308     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5309
5310     // Quit if extracted from vector of different type.
5311     if (ExtractedFromVec.getValueType() != VT)
5312       return SDValue();
5313
5314     // Quit if non-constant index.
5315     if (!isa<ConstantSDNode>(ExtIdx))
5316       return SDValue();
5317
5318     if (VecIn1.getNode() == 0)
5319       VecIn1 = ExtractedFromVec;
5320     else if (VecIn1 != ExtractedFromVec) {
5321       if (VecIn2.getNode() == 0)
5322         VecIn2 = ExtractedFromVec;
5323       else if (VecIn2 != ExtractedFromVec)
5324         // Quit if more than 2 vectors to shuffle
5325         return SDValue();
5326     }
5327
5328     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5329
5330     if (ExtractedFromVec == VecIn1)
5331       Mask[i] = Idx;
5332     else if (ExtractedFromVec == VecIn2)
5333       Mask[i] = Idx + NumElems;
5334   }
5335
5336   if (VecIn1.getNode() == 0)
5337     return SDValue();
5338
5339   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5340   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5341   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5342     unsigned Idx = InsertIndices[i];
5343     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5344                      DAG.getIntPtrConstant(Idx));
5345   }
5346
5347   return NV;
5348 }
5349
5350 SDValue
5351 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5352   DebugLoc dl = Op.getDebugLoc();
5353
5354   MVT VT = Op.getValueType().getSimpleVT();
5355   MVT ExtVT = VT.getVectorElementType();
5356   unsigned NumElems = Op.getNumOperands();
5357
5358   // Vectors containing all zeros can be matched by pxor and xorps later
5359   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5360     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5361     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5362     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5363       return Op;
5364
5365     return getZeroVector(VT, Subtarget, DAG, dl);
5366   }
5367
5368   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5369   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5370   // vpcmpeqd on 256-bit vectors.
5371   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5372     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5373       return Op;
5374
5375     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5376   }
5377
5378   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5379   if (Broadcast.getNode())
5380     return Broadcast;
5381
5382   unsigned EVTBits = ExtVT.getSizeInBits();
5383
5384   unsigned NumZero  = 0;
5385   unsigned NumNonZero = 0;
5386   unsigned NonZeros = 0;
5387   bool IsAllConstants = true;
5388   SmallSet<SDValue, 8> Values;
5389   for (unsigned i = 0; i < NumElems; ++i) {
5390     SDValue Elt = Op.getOperand(i);
5391     if (Elt.getOpcode() == ISD::UNDEF)
5392       continue;
5393     Values.insert(Elt);
5394     if (Elt.getOpcode() != ISD::Constant &&
5395         Elt.getOpcode() != ISD::ConstantFP)
5396       IsAllConstants = false;
5397     if (X86::isZeroNode(Elt))
5398       NumZero++;
5399     else {
5400       NonZeros |= (1 << i);
5401       NumNonZero++;
5402     }
5403   }
5404
5405   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5406   if (NumNonZero == 0)
5407     return DAG.getUNDEF(VT);
5408
5409   // Special case for single non-zero, non-undef, element.
5410   if (NumNonZero == 1) {
5411     unsigned Idx = CountTrailingZeros_32(NonZeros);
5412     SDValue Item = Op.getOperand(Idx);
5413
5414     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5415     // the value are obviously zero, truncate the value to i32 and do the
5416     // insertion that way.  Only do this if the value is non-constant or if the
5417     // value is a constant being inserted into element 0.  It is cheaper to do
5418     // a constant pool load than it is to do a movd + shuffle.
5419     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5420         (!IsAllConstants || Idx == 0)) {
5421       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5422         // Handle SSE only.
5423         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5424         EVT VecVT = MVT::v4i32;
5425         unsigned VecElts = 4;
5426
5427         // Truncate the value (which may itself be a constant) to i32, and
5428         // convert it to a vector with movd (S2V+shuffle to zero extend).
5429         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5430         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5431         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5432
5433         // Now we have our 32-bit value zero extended in the low element of
5434         // a vector.  If Idx != 0, swizzle it into place.
5435         if (Idx != 0) {
5436           SmallVector<int, 4> Mask;
5437           Mask.push_back(Idx);
5438           for (unsigned i = 1; i != VecElts; ++i)
5439             Mask.push_back(i);
5440           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5441                                       &Mask[0]);
5442         }
5443         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5444       }
5445     }
5446
5447     // If we have a constant or non-constant insertion into the low element of
5448     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5449     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5450     // depending on what the source datatype is.
5451     if (Idx == 0) {
5452       if (NumZero == 0)
5453         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5454
5455       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5456           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5457         if (VT.is256BitVector()) {
5458           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5459           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5460                              Item, DAG.getIntPtrConstant(0));
5461         }
5462         assert(VT.is128BitVector() && "Expected an SSE value type!");
5463         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5464         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5465         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5466       }
5467
5468       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5469         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5470         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5471         if (VT.is256BitVector()) {
5472           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5473           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5474         } else {
5475           assert(VT.is128BitVector() && "Expected an SSE value type!");
5476           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5477         }
5478         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5479       }
5480     }
5481
5482     // Is it a vector logical left shift?
5483     if (NumElems == 2 && Idx == 1 &&
5484         X86::isZeroNode(Op.getOperand(0)) &&
5485         !X86::isZeroNode(Op.getOperand(1))) {
5486       unsigned NumBits = VT.getSizeInBits();
5487       return getVShift(true, VT,
5488                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5489                                    VT, Op.getOperand(1)),
5490                        NumBits/2, DAG, *this, dl);
5491     }
5492
5493     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5494       return SDValue();
5495
5496     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5497     // is a non-constant being inserted into an element other than the low one,
5498     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5499     // movd/movss) to move this into the low element, then shuffle it into
5500     // place.
5501     if (EVTBits == 32) {
5502       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5503
5504       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5505       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5506       SmallVector<int, 8> MaskVec;
5507       for (unsigned i = 0; i != NumElems; ++i)
5508         MaskVec.push_back(i == Idx ? 0 : 1);
5509       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5510     }
5511   }
5512
5513   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5514   if (Values.size() == 1) {
5515     if (EVTBits == 32) {
5516       // Instead of a shuffle like this:
5517       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5518       // Check if it's possible to issue this instead.
5519       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5520       unsigned Idx = CountTrailingZeros_32(NonZeros);
5521       SDValue Item = Op.getOperand(Idx);
5522       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5523         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5524     }
5525     return SDValue();
5526   }
5527
5528   // A vector full of immediates; various special cases are already
5529   // handled, so this is best done with a single constant-pool load.
5530   if (IsAllConstants)
5531     return SDValue();
5532
5533   // For AVX-length vectors, build the individual 128-bit pieces and use
5534   // shuffles to put them in place.
5535   if (VT.is256BitVector()) {
5536     SmallVector<SDValue, 32> V;
5537     for (unsigned i = 0; i != NumElems; ++i)
5538       V.push_back(Op.getOperand(i));
5539
5540     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5541
5542     // Build both the lower and upper subvector.
5543     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5544     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5545                                 NumElems/2);
5546
5547     // Recreate the wider vector with the lower and upper part.
5548     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5549   }
5550
5551   // Let legalizer expand 2-wide build_vectors.
5552   if (EVTBits == 64) {
5553     if (NumNonZero == 1) {
5554       // One half is zero or undef.
5555       unsigned Idx = CountTrailingZeros_32(NonZeros);
5556       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5557                                  Op.getOperand(Idx));
5558       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5559     }
5560     return SDValue();
5561   }
5562
5563   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5564   if (EVTBits == 8 && NumElems == 16) {
5565     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5566                                         Subtarget, *this);
5567     if (V.getNode()) return V;
5568   }
5569
5570   if (EVTBits == 16 && NumElems == 8) {
5571     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5572                                       Subtarget, *this);
5573     if (V.getNode()) return V;
5574   }
5575
5576   // If element VT is == 32 bits, turn it into a number of shuffles.
5577   SmallVector<SDValue, 8> V(NumElems);
5578   if (NumElems == 4 && NumZero > 0) {
5579     for (unsigned i = 0; i < 4; ++i) {
5580       bool isZero = !(NonZeros & (1 << i));
5581       if (isZero)
5582         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5583       else
5584         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5585     }
5586
5587     for (unsigned i = 0; i < 2; ++i) {
5588       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5589         default: break;
5590         case 0:
5591           V[i] = V[i*2];  // Must be a zero vector.
5592           break;
5593         case 1:
5594           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5595           break;
5596         case 2:
5597           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5598           break;
5599         case 3:
5600           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5601           break;
5602       }
5603     }
5604
5605     bool Reverse1 = (NonZeros & 0x3) == 2;
5606     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5607     int MaskVec[] = {
5608       Reverse1 ? 1 : 0,
5609       Reverse1 ? 0 : 1,
5610       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5611       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5612     };
5613     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5614   }
5615
5616   if (Values.size() > 1 && VT.is128BitVector()) {
5617     // Check for a build vector of consecutive loads.
5618     for (unsigned i = 0; i < NumElems; ++i)
5619       V[i] = Op.getOperand(i);
5620
5621     // Check for elements which are consecutive loads.
5622     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5623     if (LD.getNode())
5624       return LD;
5625
5626     // Check for a build vector from mostly shuffle plus few inserting.
5627     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5628     if (Sh.getNode())
5629       return Sh;
5630
5631     // For SSE 4.1, use insertps to put the high elements into the low element.
5632     if (getSubtarget()->hasSSE41()) {
5633       SDValue Result;
5634       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5635         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5636       else
5637         Result = DAG.getUNDEF(VT);
5638
5639       for (unsigned i = 1; i < NumElems; ++i) {
5640         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5641         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5642                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5643       }
5644       return Result;
5645     }
5646
5647     // Otherwise, expand into a number of unpckl*, start by extending each of
5648     // our (non-undef) elements to the full vector width with the element in the
5649     // bottom slot of the vector (which generates no code for SSE).
5650     for (unsigned i = 0; i < NumElems; ++i) {
5651       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5652         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5653       else
5654         V[i] = DAG.getUNDEF(VT);
5655     }
5656
5657     // Next, we iteratively mix elements, e.g. for v4f32:
5658     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5659     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5660     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5661     unsigned EltStride = NumElems >> 1;
5662     while (EltStride != 0) {
5663       for (unsigned i = 0; i < EltStride; ++i) {
5664         // If V[i+EltStride] is undef and this is the first round of mixing,
5665         // then it is safe to just drop this shuffle: V[i] is already in the
5666         // right place, the one element (since it's the first round) being
5667         // inserted as undef can be dropped.  This isn't safe for successive
5668         // rounds because they will permute elements within both vectors.
5669         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5670             EltStride == NumElems/2)
5671           continue;
5672
5673         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5674       }
5675       EltStride >>= 1;
5676     }
5677     return V[0];
5678   }
5679   return SDValue();
5680 }
5681
5682 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5683 // to create 256-bit vectors from two other 128-bit ones.
5684 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5685   DebugLoc dl = Op.getDebugLoc();
5686   MVT ResVT = Op.getValueType().getSimpleVT();
5687
5688   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5689
5690   SDValue V1 = Op.getOperand(0);
5691   SDValue V2 = Op.getOperand(1);
5692   unsigned NumElems = ResVT.getVectorNumElements();
5693
5694   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5695 }
5696
5697 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5698   assert(Op.getNumOperands() == 2);
5699
5700   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5701   // from two other 128-bit ones.
5702   return LowerAVXCONCAT_VECTORS(Op, DAG);
5703 }
5704
5705 // Try to lower a shuffle node into a simple blend instruction.
5706 static SDValue
5707 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5708                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5709   SDValue V1 = SVOp->getOperand(0);
5710   SDValue V2 = SVOp->getOperand(1);
5711   DebugLoc dl = SVOp->getDebugLoc();
5712   MVT VT = SVOp->getValueType(0).getSimpleVT();
5713   MVT EltVT = VT.getVectorElementType();
5714   unsigned NumElems = VT.getVectorNumElements();
5715
5716   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5717     return SDValue();
5718   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5719     return SDValue();
5720
5721   // Check the mask for BLEND and build the value.
5722   unsigned MaskValue = 0;
5723   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5724   unsigned NumLanes = (NumElems-1)/8 + 1;
5725   unsigned NumElemsInLane = NumElems / NumLanes;
5726
5727   // Blend for v16i16 should be symetric for the both lanes.
5728   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5729
5730     int SndLaneEltIdx = (NumLanes == 2) ?
5731       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5732     int EltIdx = SVOp->getMaskElt(i);
5733
5734     if ((EltIdx < 0 || EltIdx == (int)i) &&
5735         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5736       continue;
5737
5738     if (((unsigned)EltIdx == (i + NumElems)) &&
5739         (SndLaneEltIdx < 0 ||
5740          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5741       MaskValue |= (1<<i);
5742     else
5743       return SDValue();
5744   }
5745
5746   // Convert i32 vectors to floating point if it is not AVX2.
5747   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5748   MVT BlendVT = VT;
5749   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5750     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5751                                NumElems);
5752     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5753     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5754   }
5755
5756   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5757                             DAG.getConstant(MaskValue, MVT::i32));
5758   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5759 }
5760
5761 // v8i16 shuffles - Prefer shuffles in the following order:
5762 // 1. [all]   pshuflw, pshufhw, optional move
5763 // 2. [ssse3] 1 x pshufb
5764 // 3. [ssse3] 2 x pshufb + 1 x por
5765 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5766 static SDValue
5767 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5768                          SelectionDAG &DAG) {
5769   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5770   SDValue V1 = SVOp->getOperand(0);
5771   SDValue V2 = SVOp->getOperand(1);
5772   DebugLoc dl = SVOp->getDebugLoc();
5773   SmallVector<int, 8> MaskVals;
5774
5775   // Determine if more than 1 of the words in each of the low and high quadwords
5776   // of the result come from the same quadword of one of the two inputs.  Undef
5777   // mask values count as coming from any quadword, for better codegen.
5778   unsigned LoQuad[] = { 0, 0, 0, 0 };
5779   unsigned HiQuad[] = { 0, 0, 0, 0 };
5780   std::bitset<4> InputQuads;
5781   for (unsigned i = 0; i < 8; ++i) {
5782     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5783     int EltIdx = SVOp->getMaskElt(i);
5784     MaskVals.push_back(EltIdx);
5785     if (EltIdx < 0) {
5786       ++Quad[0];
5787       ++Quad[1];
5788       ++Quad[2];
5789       ++Quad[3];
5790       continue;
5791     }
5792     ++Quad[EltIdx / 4];
5793     InputQuads.set(EltIdx / 4);
5794   }
5795
5796   int BestLoQuad = -1;
5797   unsigned MaxQuad = 1;
5798   for (unsigned i = 0; i < 4; ++i) {
5799     if (LoQuad[i] > MaxQuad) {
5800       BestLoQuad = i;
5801       MaxQuad = LoQuad[i];
5802     }
5803   }
5804
5805   int BestHiQuad = -1;
5806   MaxQuad = 1;
5807   for (unsigned i = 0; i < 4; ++i) {
5808     if (HiQuad[i] > MaxQuad) {
5809       BestHiQuad = i;
5810       MaxQuad = HiQuad[i];
5811     }
5812   }
5813
5814   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5815   // of the two input vectors, shuffle them into one input vector so only a
5816   // single pshufb instruction is necessary. If There are more than 2 input
5817   // quads, disable the next transformation since it does not help SSSE3.
5818   bool V1Used = InputQuads[0] || InputQuads[1];
5819   bool V2Used = InputQuads[2] || InputQuads[3];
5820   if (Subtarget->hasSSSE3()) {
5821     if (InputQuads.count() == 2 && V1Used && V2Used) {
5822       BestLoQuad = InputQuads[0] ? 0 : 1;
5823       BestHiQuad = InputQuads[2] ? 2 : 3;
5824     }
5825     if (InputQuads.count() > 2) {
5826       BestLoQuad = -1;
5827       BestHiQuad = -1;
5828     }
5829   }
5830
5831   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5832   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5833   // words from all 4 input quadwords.
5834   SDValue NewV;
5835   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5836     int MaskV[] = {
5837       BestLoQuad < 0 ? 0 : BestLoQuad,
5838       BestHiQuad < 0 ? 1 : BestHiQuad
5839     };
5840     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5841                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5842                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5843     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5844
5845     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5846     // source words for the shuffle, to aid later transformations.
5847     bool AllWordsInNewV = true;
5848     bool InOrder[2] = { true, true };
5849     for (unsigned i = 0; i != 8; ++i) {
5850       int idx = MaskVals[i];
5851       if (idx != (int)i)
5852         InOrder[i/4] = false;
5853       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5854         continue;
5855       AllWordsInNewV = false;
5856       break;
5857     }
5858
5859     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5860     if (AllWordsInNewV) {
5861       for (int i = 0; i != 8; ++i) {
5862         int idx = MaskVals[i];
5863         if (idx < 0)
5864           continue;
5865         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5866         if ((idx != i) && idx < 4)
5867           pshufhw = false;
5868         if ((idx != i) && idx > 3)
5869           pshuflw = false;
5870       }
5871       V1 = NewV;
5872       V2Used = false;
5873       BestLoQuad = 0;
5874       BestHiQuad = 1;
5875     }
5876
5877     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5878     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5879     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5880       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5881       unsigned TargetMask = 0;
5882       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5883                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5884       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5885       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5886                              getShufflePSHUFLWImmediate(SVOp);
5887       V1 = NewV.getOperand(0);
5888       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5889     }
5890   }
5891
5892   // Promote splats to a larger type which usually leads to more efficient code.
5893   // FIXME: Is this true if pshufb is available?
5894   if (SVOp->isSplat())
5895     return PromoteSplat(SVOp, DAG);
5896
5897   // If we have SSSE3, and all words of the result are from 1 input vector,
5898   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5899   // is present, fall back to case 4.
5900   if (Subtarget->hasSSSE3()) {
5901     SmallVector<SDValue,16> pshufbMask;
5902
5903     // If we have elements from both input vectors, set the high bit of the
5904     // shuffle mask element to zero out elements that come from V2 in the V1
5905     // mask, and elements that come from V1 in the V2 mask, so that the two
5906     // results can be OR'd together.
5907     bool TwoInputs = V1Used && V2Used;
5908     for (unsigned i = 0; i != 8; ++i) {
5909       int EltIdx = MaskVals[i] * 2;
5910       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5911       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5912       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5913       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5914     }
5915     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5916     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5917                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5918                                  MVT::v16i8, &pshufbMask[0], 16));
5919     if (!TwoInputs)
5920       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5921
5922     // Calculate the shuffle mask for the second input, shuffle it, and
5923     // OR it with the first shuffled input.
5924     pshufbMask.clear();
5925     for (unsigned i = 0; i != 8; ++i) {
5926       int EltIdx = MaskVals[i] * 2;
5927       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5928       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5929       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5930       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5931     }
5932     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5933     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5934                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5935                                  MVT::v16i8, &pshufbMask[0], 16));
5936     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5937     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5938   }
5939
5940   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5941   // and update MaskVals with new element order.
5942   std::bitset<8> InOrder;
5943   if (BestLoQuad >= 0) {
5944     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5945     for (int i = 0; i != 4; ++i) {
5946       int idx = MaskVals[i];
5947       if (idx < 0) {
5948         InOrder.set(i);
5949       } else if ((idx / 4) == BestLoQuad) {
5950         MaskV[i] = idx & 3;
5951         InOrder.set(i);
5952       }
5953     }
5954     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5955                                 &MaskV[0]);
5956
5957     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5958       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5959       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5960                                   NewV.getOperand(0),
5961                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5962     }
5963   }
5964
5965   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5966   // and update MaskVals with the new element order.
5967   if (BestHiQuad >= 0) {
5968     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5969     for (unsigned i = 4; i != 8; ++i) {
5970       int idx = MaskVals[i];
5971       if (idx < 0) {
5972         InOrder.set(i);
5973       } else if ((idx / 4) == BestHiQuad) {
5974         MaskV[i] = (idx & 3) + 4;
5975         InOrder.set(i);
5976       }
5977     }
5978     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5979                                 &MaskV[0]);
5980
5981     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5982       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5983       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5984                                   NewV.getOperand(0),
5985                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5986     }
5987   }
5988
5989   // In case BestHi & BestLo were both -1, which means each quadword has a word
5990   // from each of the four input quadwords, calculate the InOrder bitvector now
5991   // before falling through to the insert/extract cleanup.
5992   if (BestLoQuad == -1 && BestHiQuad == -1) {
5993     NewV = V1;
5994     for (int i = 0; i != 8; ++i)
5995       if (MaskVals[i] < 0 || MaskVals[i] == i)
5996         InOrder.set(i);
5997   }
5998
5999   // The other elements are put in the right place using pextrw and pinsrw.
6000   for (unsigned i = 0; i != 8; ++i) {
6001     if (InOrder[i])
6002       continue;
6003     int EltIdx = MaskVals[i];
6004     if (EltIdx < 0)
6005       continue;
6006     SDValue ExtOp = (EltIdx < 8) ?
6007       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6008                   DAG.getIntPtrConstant(EltIdx)) :
6009       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6010                   DAG.getIntPtrConstant(EltIdx - 8));
6011     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6012                        DAG.getIntPtrConstant(i));
6013   }
6014   return NewV;
6015 }
6016
6017 // v16i8 shuffles - Prefer shuffles in the following order:
6018 // 1. [ssse3] 1 x pshufb
6019 // 2. [ssse3] 2 x pshufb + 1 x por
6020 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6021 static
6022 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6023                                  SelectionDAG &DAG,
6024                                  const X86TargetLowering &TLI) {
6025   SDValue V1 = SVOp->getOperand(0);
6026   SDValue V2 = SVOp->getOperand(1);
6027   DebugLoc dl = SVOp->getDebugLoc();
6028   ArrayRef<int> MaskVals = SVOp->getMask();
6029
6030   // Promote splats to a larger type which usually leads to more efficient code.
6031   // FIXME: Is this true if pshufb is available?
6032   if (SVOp->isSplat())
6033     return PromoteSplat(SVOp, DAG);
6034
6035   // If we have SSSE3, case 1 is generated when all result bytes come from
6036   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6037   // present, fall back to case 3.
6038
6039   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6040   if (TLI.getSubtarget()->hasSSSE3()) {
6041     SmallVector<SDValue,16> pshufbMask;
6042
6043     // If all result elements are from one input vector, then only translate
6044     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6045     //
6046     // Otherwise, we have elements from both input vectors, and must zero out
6047     // elements that come from V2 in the first mask, and V1 in the second mask
6048     // so that we can OR them together.
6049     for (unsigned i = 0; i != 16; ++i) {
6050       int EltIdx = MaskVals[i];
6051       if (EltIdx < 0 || EltIdx >= 16)
6052         EltIdx = 0x80;
6053       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6054     }
6055     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6056                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6057                                  MVT::v16i8, &pshufbMask[0], 16));
6058
6059     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6060     // the 2nd operand if it's undefined or zero.
6061     if (V2.getOpcode() == ISD::UNDEF ||
6062         ISD::isBuildVectorAllZeros(V2.getNode()))
6063       return V1;
6064
6065     // Calculate the shuffle mask for the second input, shuffle it, and
6066     // OR it with the first shuffled input.
6067     pshufbMask.clear();
6068     for (unsigned i = 0; i != 16; ++i) {
6069       int EltIdx = MaskVals[i];
6070       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6071       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6072     }
6073     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6074                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6075                                  MVT::v16i8, &pshufbMask[0], 16));
6076     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6077   }
6078
6079   // No SSSE3 - Calculate in place words and then fix all out of place words
6080   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6081   // the 16 different words that comprise the two doublequadword input vectors.
6082   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6083   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6084   SDValue NewV = V1;
6085   for (int i = 0; i != 8; ++i) {
6086     int Elt0 = MaskVals[i*2];
6087     int Elt1 = MaskVals[i*2+1];
6088
6089     // This word of the result is all undef, skip it.
6090     if (Elt0 < 0 && Elt1 < 0)
6091       continue;
6092
6093     // This word of the result is already in the correct place, skip it.
6094     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6095       continue;
6096
6097     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6098     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6099     SDValue InsElt;
6100
6101     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6102     // using a single extract together, load it and store it.
6103     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6104       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6105                            DAG.getIntPtrConstant(Elt1 / 2));
6106       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6107                         DAG.getIntPtrConstant(i));
6108       continue;
6109     }
6110
6111     // If Elt1 is defined, extract it from the appropriate source.  If the
6112     // source byte is not also odd, shift the extracted word left 8 bits
6113     // otherwise clear the bottom 8 bits if we need to do an or.
6114     if (Elt1 >= 0) {
6115       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6116                            DAG.getIntPtrConstant(Elt1 / 2));
6117       if ((Elt1 & 1) == 0)
6118         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6119                              DAG.getConstant(8,
6120                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6121       else if (Elt0 >= 0)
6122         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6123                              DAG.getConstant(0xFF00, MVT::i16));
6124     }
6125     // If Elt0 is defined, extract it from the appropriate source.  If the
6126     // source byte is not also even, shift the extracted word right 8 bits. If
6127     // Elt1 was also defined, OR the extracted values together before
6128     // inserting them in the result.
6129     if (Elt0 >= 0) {
6130       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6131                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6132       if ((Elt0 & 1) != 0)
6133         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6134                               DAG.getConstant(8,
6135                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6136       else if (Elt1 >= 0)
6137         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6138                              DAG.getConstant(0x00FF, MVT::i16));
6139       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6140                          : InsElt0;
6141     }
6142     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6143                        DAG.getIntPtrConstant(i));
6144   }
6145   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6146 }
6147
6148 // v32i8 shuffles - Translate to VPSHUFB if possible.
6149 static
6150 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6151                                  const X86Subtarget *Subtarget,
6152                                  SelectionDAG &DAG) {
6153   MVT VT = SVOp->getValueType(0).getSimpleVT();
6154   SDValue V1 = SVOp->getOperand(0);
6155   SDValue V2 = SVOp->getOperand(1);
6156   DebugLoc dl = SVOp->getDebugLoc();
6157   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6158
6159   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6160   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6161   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6162
6163   // VPSHUFB may be generated if
6164   // (1) one of input vector is undefined or zeroinitializer.
6165   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6166   // And (2) the mask indexes don't cross the 128-bit lane.
6167   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6168       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6169     return SDValue();
6170
6171   if (V1IsAllZero && !V2IsAllZero) {
6172     CommuteVectorShuffleMask(MaskVals, 32);
6173     V1 = V2;
6174   }
6175   SmallVector<SDValue, 32> pshufbMask;
6176   for (unsigned i = 0; i != 32; i++) {
6177     int EltIdx = MaskVals[i];
6178     if (EltIdx < 0 || EltIdx >= 32)
6179       EltIdx = 0x80;
6180     else {
6181       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6182         // Cross lane is not allowed.
6183         return SDValue();
6184       EltIdx &= 0xf;
6185     }
6186     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6187   }
6188   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6189                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6190                                   MVT::v32i8, &pshufbMask[0], 32));
6191 }
6192
6193 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6194 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6195 /// done when every pair / quad of shuffle mask elements point to elements in
6196 /// the right sequence. e.g.
6197 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6198 static
6199 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6200                                  SelectionDAG &DAG) {
6201   MVT VT = SVOp->getValueType(0).getSimpleVT();
6202   DebugLoc dl = SVOp->getDebugLoc();
6203   unsigned NumElems = VT.getVectorNumElements();
6204   MVT NewVT;
6205   unsigned Scale;
6206   switch (VT.SimpleTy) {
6207   default: llvm_unreachable("Unexpected!");
6208   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6209   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6210   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6211   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6212   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6213   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6214   }
6215
6216   SmallVector<int, 8> MaskVec;
6217   for (unsigned i = 0; i != NumElems; i += Scale) {
6218     int StartIdx = -1;
6219     for (unsigned j = 0; j != Scale; ++j) {
6220       int EltIdx = SVOp->getMaskElt(i+j);
6221       if (EltIdx < 0)
6222         continue;
6223       if (StartIdx < 0)
6224         StartIdx = (EltIdx / Scale);
6225       if (EltIdx != (int)(StartIdx*Scale + j))
6226         return SDValue();
6227     }
6228     MaskVec.push_back(StartIdx);
6229   }
6230
6231   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6232   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6233   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6234 }
6235
6236 /// getVZextMovL - Return a zero-extending vector move low node.
6237 ///
6238 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6239                             SDValue SrcOp, SelectionDAG &DAG,
6240                             const X86Subtarget *Subtarget, DebugLoc dl) {
6241   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6242     LoadSDNode *LD = NULL;
6243     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6244       LD = dyn_cast<LoadSDNode>(SrcOp);
6245     if (!LD) {
6246       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6247       // instead.
6248       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6249       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6250           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6251           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6252           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6253         // PR2108
6254         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6255         return DAG.getNode(ISD::BITCAST, dl, VT,
6256                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6257                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6258                                                    OpVT,
6259                                                    SrcOp.getOperand(0)
6260                                                           .getOperand(0))));
6261       }
6262     }
6263   }
6264
6265   return DAG.getNode(ISD::BITCAST, dl, VT,
6266                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6267                                  DAG.getNode(ISD::BITCAST, dl,
6268                                              OpVT, SrcOp)));
6269 }
6270
6271 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6272 /// which could not be matched by any known target speficic shuffle
6273 static SDValue
6274 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6275
6276   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6277   if (NewOp.getNode())
6278     return NewOp;
6279
6280   MVT VT = SVOp->getValueType(0).getSimpleVT();
6281
6282   unsigned NumElems = VT.getVectorNumElements();
6283   unsigned NumLaneElems = NumElems / 2;
6284
6285   DebugLoc dl = SVOp->getDebugLoc();
6286   MVT EltVT = VT.getVectorElementType();
6287   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6288   SDValue Output[2];
6289
6290   SmallVector<int, 16> Mask;
6291   for (unsigned l = 0; l < 2; ++l) {
6292     // Build a shuffle mask for the output, discovering on the fly which
6293     // input vectors to use as shuffle operands (recorded in InputUsed).
6294     // If building a suitable shuffle vector proves too hard, then bail
6295     // out with UseBuildVector set.
6296     bool UseBuildVector = false;
6297     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6298     unsigned LaneStart = l * NumLaneElems;
6299     for (unsigned i = 0; i != NumLaneElems; ++i) {
6300       // The mask element.  This indexes into the input.
6301       int Idx = SVOp->getMaskElt(i+LaneStart);
6302       if (Idx < 0) {
6303         // the mask element does not index into any input vector.
6304         Mask.push_back(-1);
6305         continue;
6306       }
6307
6308       // The input vector this mask element indexes into.
6309       int Input = Idx / NumLaneElems;
6310
6311       // Turn the index into an offset from the start of the input vector.
6312       Idx -= Input * NumLaneElems;
6313
6314       // Find or create a shuffle vector operand to hold this input.
6315       unsigned OpNo;
6316       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6317         if (InputUsed[OpNo] == Input)
6318           // This input vector is already an operand.
6319           break;
6320         if (InputUsed[OpNo] < 0) {
6321           // Create a new operand for this input vector.
6322           InputUsed[OpNo] = Input;
6323           break;
6324         }
6325       }
6326
6327       if (OpNo >= array_lengthof(InputUsed)) {
6328         // More than two input vectors used!  Give up on trying to create a
6329         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6330         UseBuildVector = true;
6331         break;
6332       }
6333
6334       // Add the mask index for the new shuffle vector.
6335       Mask.push_back(Idx + OpNo * NumLaneElems);
6336     }
6337
6338     if (UseBuildVector) {
6339       SmallVector<SDValue, 16> SVOps;
6340       for (unsigned i = 0; i != NumLaneElems; ++i) {
6341         // The mask element.  This indexes into the input.
6342         int Idx = SVOp->getMaskElt(i+LaneStart);
6343         if (Idx < 0) {
6344           SVOps.push_back(DAG.getUNDEF(EltVT));
6345           continue;
6346         }
6347
6348         // The input vector this mask element indexes into.
6349         int Input = Idx / NumElems;
6350
6351         // Turn the index into an offset from the start of the input vector.
6352         Idx -= Input * NumElems;
6353
6354         // Extract the vector element by hand.
6355         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6356                                     SVOp->getOperand(Input),
6357                                     DAG.getIntPtrConstant(Idx)));
6358       }
6359
6360       // Construct the output using a BUILD_VECTOR.
6361       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6362                               SVOps.size());
6363     } else if (InputUsed[0] < 0) {
6364       // No input vectors were used! The result is undefined.
6365       Output[l] = DAG.getUNDEF(NVT);
6366     } else {
6367       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6368                                         (InputUsed[0] % 2) * NumLaneElems,
6369                                         DAG, dl);
6370       // If only one input was used, use an undefined vector for the other.
6371       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6372         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6373                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6374       // At least one input vector was used. Create a new shuffle vector.
6375       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6376     }
6377
6378     Mask.clear();
6379   }
6380
6381   // Concatenate the result back
6382   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6383 }
6384
6385 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6386 /// 4 elements, and match them with several different shuffle types.
6387 static SDValue
6388 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6389   SDValue V1 = SVOp->getOperand(0);
6390   SDValue V2 = SVOp->getOperand(1);
6391   DebugLoc dl = SVOp->getDebugLoc();
6392   MVT VT = SVOp->getValueType(0).getSimpleVT();
6393
6394   assert(VT.is128BitVector() && "Unsupported vector size");
6395
6396   std::pair<int, int> Locs[4];
6397   int Mask1[] = { -1, -1, -1, -1 };
6398   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6399
6400   unsigned NumHi = 0;
6401   unsigned NumLo = 0;
6402   for (unsigned i = 0; i != 4; ++i) {
6403     int Idx = PermMask[i];
6404     if (Idx < 0) {
6405       Locs[i] = std::make_pair(-1, -1);
6406     } else {
6407       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6408       if (Idx < 4) {
6409         Locs[i] = std::make_pair(0, NumLo);
6410         Mask1[NumLo] = Idx;
6411         NumLo++;
6412       } else {
6413         Locs[i] = std::make_pair(1, NumHi);
6414         if (2+NumHi < 4)
6415           Mask1[2+NumHi] = Idx;
6416         NumHi++;
6417       }
6418     }
6419   }
6420
6421   if (NumLo <= 2 && NumHi <= 2) {
6422     // If no more than two elements come from either vector. This can be
6423     // implemented with two shuffles. First shuffle gather the elements.
6424     // The second shuffle, which takes the first shuffle as both of its
6425     // vector operands, put the elements into the right order.
6426     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6427
6428     int Mask2[] = { -1, -1, -1, -1 };
6429
6430     for (unsigned i = 0; i != 4; ++i)
6431       if (Locs[i].first != -1) {
6432         unsigned Idx = (i < 2) ? 0 : 4;
6433         Idx += Locs[i].first * 2 + Locs[i].second;
6434         Mask2[i] = Idx;
6435       }
6436
6437     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6438   }
6439
6440   if (NumLo == 3 || NumHi == 3) {
6441     // Otherwise, we must have three elements from one vector, call it X, and
6442     // one element from the other, call it Y.  First, use a shufps to build an
6443     // intermediate vector with the one element from Y and the element from X
6444     // that will be in the same half in the final destination (the indexes don't
6445     // matter). Then, use a shufps to build the final vector, taking the half
6446     // containing the element from Y from the intermediate, and the other half
6447     // from X.
6448     if (NumHi == 3) {
6449       // Normalize it so the 3 elements come from V1.
6450       CommuteVectorShuffleMask(PermMask, 4);
6451       std::swap(V1, V2);
6452     }
6453
6454     // Find the element from V2.
6455     unsigned HiIndex;
6456     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6457       int Val = PermMask[HiIndex];
6458       if (Val < 0)
6459         continue;
6460       if (Val >= 4)
6461         break;
6462     }
6463
6464     Mask1[0] = PermMask[HiIndex];
6465     Mask1[1] = -1;
6466     Mask1[2] = PermMask[HiIndex^1];
6467     Mask1[3] = -1;
6468     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6469
6470     if (HiIndex >= 2) {
6471       Mask1[0] = PermMask[0];
6472       Mask1[1] = PermMask[1];
6473       Mask1[2] = HiIndex & 1 ? 6 : 4;
6474       Mask1[3] = HiIndex & 1 ? 4 : 6;
6475       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6476     }
6477
6478     Mask1[0] = HiIndex & 1 ? 2 : 0;
6479     Mask1[1] = HiIndex & 1 ? 0 : 2;
6480     Mask1[2] = PermMask[2];
6481     Mask1[3] = PermMask[3];
6482     if (Mask1[2] >= 0)
6483       Mask1[2] += 4;
6484     if (Mask1[3] >= 0)
6485       Mask1[3] += 4;
6486     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6487   }
6488
6489   // Break it into (shuffle shuffle_hi, shuffle_lo).
6490   int LoMask[] = { -1, -1, -1, -1 };
6491   int HiMask[] = { -1, -1, -1, -1 };
6492
6493   int *MaskPtr = LoMask;
6494   unsigned MaskIdx = 0;
6495   unsigned LoIdx = 0;
6496   unsigned HiIdx = 2;
6497   for (unsigned i = 0; i != 4; ++i) {
6498     if (i == 2) {
6499       MaskPtr = HiMask;
6500       MaskIdx = 1;
6501       LoIdx = 0;
6502       HiIdx = 2;
6503     }
6504     int Idx = PermMask[i];
6505     if (Idx < 0) {
6506       Locs[i] = std::make_pair(-1, -1);
6507     } else if (Idx < 4) {
6508       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6509       MaskPtr[LoIdx] = Idx;
6510       LoIdx++;
6511     } else {
6512       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6513       MaskPtr[HiIdx] = Idx;
6514       HiIdx++;
6515     }
6516   }
6517
6518   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6519   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6520   int MaskOps[] = { -1, -1, -1, -1 };
6521   for (unsigned i = 0; i != 4; ++i)
6522     if (Locs[i].first != -1)
6523       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6524   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6525 }
6526
6527 static bool MayFoldVectorLoad(SDValue V) {
6528   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6529     V = V.getOperand(0);
6530
6531   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6532     V = V.getOperand(0);
6533   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6534       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6535     // BUILD_VECTOR (load), undef
6536     V = V.getOperand(0);
6537
6538   return MayFoldLoad(V);
6539 }
6540
6541 static
6542 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6543   EVT VT = Op.getValueType();
6544
6545   // Canonizalize to v2f64.
6546   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6547   return DAG.getNode(ISD::BITCAST, dl, VT,
6548                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6549                                           V1, DAG));
6550 }
6551
6552 static
6553 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6554                         bool HasSSE2) {
6555   SDValue V1 = Op.getOperand(0);
6556   SDValue V2 = Op.getOperand(1);
6557   EVT VT = Op.getValueType();
6558
6559   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6560
6561   if (HasSSE2 && VT == MVT::v2f64)
6562     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6563
6564   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6565   return DAG.getNode(ISD::BITCAST, dl, VT,
6566                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6567                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6568                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6569 }
6570
6571 static
6572 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6573   SDValue V1 = Op.getOperand(0);
6574   SDValue V2 = Op.getOperand(1);
6575   EVT VT = Op.getValueType();
6576
6577   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6578          "unsupported shuffle type");
6579
6580   if (V2.getOpcode() == ISD::UNDEF)
6581     V2 = V1;
6582
6583   // v4i32 or v4f32
6584   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6585 }
6586
6587 static
6588 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6589   SDValue V1 = Op.getOperand(0);
6590   SDValue V2 = Op.getOperand(1);
6591   EVT VT = Op.getValueType();
6592   unsigned NumElems = VT.getVectorNumElements();
6593
6594   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6595   // operand of these instructions is only memory, so check if there's a
6596   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6597   // same masks.
6598   bool CanFoldLoad = false;
6599
6600   // Trivial case, when V2 comes from a load.
6601   if (MayFoldVectorLoad(V2))
6602     CanFoldLoad = true;
6603
6604   // When V1 is a load, it can be folded later into a store in isel, example:
6605   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6606   //    turns into:
6607   //  (MOVLPSmr addr:$src1, VR128:$src2)
6608   // So, recognize this potential and also use MOVLPS or MOVLPD
6609   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6610     CanFoldLoad = true;
6611
6612   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6613   if (CanFoldLoad) {
6614     if (HasSSE2 && NumElems == 2)
6615       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6616
6617     if (NumElems == 4)
6618       // If we don't care about the second element, proceed to use movss.
6619       if (SVOp->getMaskElt(1) != -1)
6620         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6621   }
6622
6623   // movl and movlp will both match v2i64, but v2i64 is never matched by
6624   // movl earlier because we make it strict to avoid messing with the movlp load
6625   // folding logic (see the code above getMOVLP call). Match it here then,
6626   // this is horrible, but will stay like this until we move all shuffle
6627   // matching to x86 specific nodes. Note that for the 1st condition all
6628   // types are matched with movsd.
6629   if (HasSSE2) {
6630     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6631     // as to remove this logic from here, as much as possible
6632     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6633       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6634     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6635   }
6636
6637   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6638
6639   // Invert the operand order and use SHUFPS to match it.
6640   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6641                               getShuffleSHUFImmediate(SVOp), DAG);
6642 }
6643
6644 // Reduce a vector shuffle to zext.
6645 SDValue
6646 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6647   // PMOVZX is only available from SSE41.
6648   if (!Subtarget->hasSSE41())
6649     return SDValue();
6650
6651   EVT VT = Op.getValueType();
6652
6653   // Only AVX2 support 256-bit vector integer extending.
6654   if (!Subtarget->hasInt256() && VT.is256BitVector())
6655     return SDValue();
6656
6657   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6658   DebugLoc DL = Op.getDebugLoc();
6659   SDValue V1 = Op.getOperand(0);
6660   SDValue V2 = Op.getOperand(1);
6661   unsigned NumElems = VT.getVectorNumElements();
6662
6663   // Extending is an unary operation and the element type of the source vector
6664   // won't be equal to or larger than i64.
6665   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6666       VT.getVectorElementType() == MVT::i64)
6667     return SDValue();
6668
6669   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6670   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6671   while ((1U << Shift) < NumElems) {
6672     if (SVOp->getMaskElt(1U << Shift) == 1)
6673       break;
6674     Shift += 1;
6675     // The maximal ratio is 8, i.e. from i8 to i64.
6676     if (Shift > 3)
6677       return SDValue();
6678   }
6679
6680   // Check the shuffle mask.
6681   unsigned Mask = (1U << Shift) - 1;
6682   for (unsigned i = 0; i != NumElems; ++i) {
6683     int EltIdx = SVOp->getMaskElt(i);
6684     if ((i & Mask) != 0 && EltIdx != -1)
6685       return SDValue();
6686     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6687       return SDValue();
6688   }
6689
6690   LLVMContext *Context = DAG.getContext();
6691   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6692   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6693   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6694
6695   if (!isTypeLegal(NVT))
6696     return SDValue();
6697
6698   // Simplify the operand as it's prepared to be fed into shuffle.
6699   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6700   if (V1.getOpcode() == ISD::BITCAST &&
6701       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6702       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6703       V1.getOperand(0)
6704         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6705     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6706     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6707     ConstantSDNode *CIdx =
6708       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6709     // If it's foldable, i.e. normal load with single use, we will let code
6710     // selection to fold it. Otherwise, we will short the conversion sequence.
6711     if (CIdx && CIdx->getZExtValue() == 0 &&
6712         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6713       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6714         // The "ext_vec_elt" node is wider than the result node.
6715         // In this case we should extract subvector from V.
6716         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6717         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6718         EVT FullVT = V.getValueType();
6719         EVT SubVecVT = EVT::getVectorVT(*Context, 
6720                                         FullVT.getVectorElementType(),
6721                                         FullVT.getVectorNumElements()/Ratio);
6722         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V, 
6723                         DAG.getIntPtrConstant(0));
6724       }
6725       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6726     }
6727   }
6728
6729   return DAG.getNode(ISD::BITCAST, DL, VT,
6730                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6731 }
6732
6733 SDValue
6734 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6735   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6736   MVT VT = Op.getValueType().getSimpleVT();
6737   DebugLoc dl = Op.getDebugLoc();
6738   SDValue V1 = Op.getOperand(0);
6739   SDValue V2 = Op.getOperand(1);
6740
6741   if (isZeroShuffle(SVOp))
6742     return getZeroVector(VT, Subtarget, DAG, dl);
6743
6744   // Handle splat operations
6745   if (SVOp->isSplat()) {
6746     // Use vbroadcast whenever the splat comes from a foldable load
6747     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6748     if (Broadcast.getNode())
6749       return Broadcast;
6750   }
6751
6752   // Check integer expanding shuffles.
6753   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6754   if (NewOp.getNode())
6755     return NewOp;
6756
6757   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6758   // do it!
6759   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6760       VT == MVT::v16i16 || VT == MVT::v32i8) {
6761     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6762     if (NewOp.getNode())
6763       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6764   } else if ((VT == MVT::v4i32 ||
6765              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6766     // FIXME: Figure out a cleaner way to do this.
6767     // Try to make use of movq to zero out the top part.
6768     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6769       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6770       if (NewOp.getNode()) {
6771         MVT NewVT = NewOp.getValueType().getSimpleVT();
6772         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6773                                NewVT, true, false))
6774           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6775                               DAG, Subtarget, dl);
6776       }
6777     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6778       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6779       if (NewOp.getNode()) {
6780         MVT NewVT = NewOp.getValueType().getSimpleVT();
6781         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6782           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6783                               DAG, Subtarget, dl);
6784       }
6785     }
6786   }
6787   return SDValue();
6788 }
6789
6790 SDValue
6791 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6792   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6793   SDValue V1 = Op.getOperand(0);
6794   SDValue V2 = Op.getOperand(1);
6795   MVT VT = Op.getValueType().getSimpleVT();
6796   DebugLoc dl = Op.getDebugLoc();
6797   unsigned NumElems = VT.getVectorNumElements();
6798   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6799   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6800   bool V1IsSplat = false;
6801   bool V2IsSplat = false;
6802   bool HasSSE2 = Subtarget->hasSSE2();
6803   bool HasFp256    = Subtarget->hasFp256();
6804   bool HasInt256   = Subtarget->hasInt256();
6805   MachineFunction &MF = DAG.getMachineFunction();
6806   bool OptForSize = MF.getFunction()->getAttributes().
6807     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6808
6809   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6810
6811   if (V1IsUndef && V2IsUndef)
6812     return DAG.getUNDEF(VT);
6813
6814   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6815
6816   // Vector shuffle lowering takes 3 steps:
6817   //
6818   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6819   //    narrowing and commutation of operands should be handled.
6820   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6821   //    shuffle nodes.
6822   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6823   //    so the shuffle can be broken into other shuffles and the legalizer can
6824   //    try the lowering again.
6825   //
6826   // The general idea is that no vector_shuffle operation should be left to
6827   // be matched during isel, all of them must be converted to a target specific
6828   // node here.
6829
6830   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6831   // narrowing and commutation of operands should be handled. The actual code
6832   // doesn't include all of those, work in progress...
6833   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6834   if (NewOp.getNode())
6835     return NewOp;
6836
6837   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6838
6839   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6840   // unpckh_undef). Only use pshufd if speed is more important than size.
6841   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6842     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6843   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6844     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6845
6846   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6847       V2IsUndef && MayFoldVectorLoad(V1))
6848     return getMOVDDup(Op, dl, V1, DAG);
6849
6850   if (isMOVHLPS_v_undef_Mask(M, VT))
6851     return getMOVHighToLow(Op, dl, DAG);
6852
6853   // Use to match splats
6854   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6855       (VT == MVT::v2f64 || VT == MVT::v2i64))
6856     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6857
6858   if (isPSHUFDMask(M, VT)) {
6859     // The actual implementation will match the mask in the if above and then
6860     // during isel it can match several different instructions, not only pshufd
6861     // as its name says, sad but true, emulate the behavior for now...
6862     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6863       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6864
6865     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6866
6867     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6868       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6869
6870     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6871       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6872                                   DAG);
6873
6874     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6875                                 TargetMask, DAG);
6876   }
6877
6878   // Check if this can be converted into a logical shift.
6879   bool isLeft = false;
6880   unsigned ShAmt = 0;
6881   SDValue ShVal;
6882   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6883   if (isShift && ShVal.hasOneUse()) {
6884     // If the shifted value has multiple uses, it may be cheaper to use
6885     // v_set0 + movlhps or movhlps, etc.
6886     MVT EltVT = VT.getVectorElementType();
6887     ShAmt *= EltVT.getSizeInBits();
6888     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6889   }
6890
6891   if (isMOVLMask(M, VT)) {
6892     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6893       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6894     if (!isMOVLPMask(M, VT)) {
6895       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6896         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6897
6898       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6899         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6900     }
6901   }
6902
6903   // FIXME: fold these into legal mask.
6904   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6905     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6906
6907   if (isMOVHLPSMask(M, VT))
6908     return getMOVHighToLow(Op, dl, DAG);
6909
6910   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6911     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6912
6913   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6914     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6915
6916   if (isMOVLPMask(M, VT))
6917     return getMOVLP(Op, dl, DAG, HasSSE2);
6918
6919   if (ShouldXformToMOVHLPS(M, VT) ||
6920       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6921     return CommuteVectorShuffle(SVOp, DAG);
6922
6923   if (isShift) {
6924     // No better options. Use a vshldq / vsrldq.
6925     MVT EltVT = VT.getVectorElementType();
6926     ShAmt *= EltVT.getSizeInBits();
6927     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6928   }
6929
6930   bool Commuted = false;
6931   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6932   // 1,1,1,1 -> v8i16 though.
6933   V1IsSplat = isSplatVector(V1.getNode());
6934   V2IsSplat = isSplatVector(V2.getNode());
6935
6936   // Canonicalize the splat or undef, if present, to be on the RHS.
6937   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6938     CommuteVectorShuffleMask(M, NumElems);
6939     std::swap(V1, V2);
6940     std::swap(V1IsSplat, V2IsSplat);
6941     Commuted = true;
6942   }
6943
6944   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6945     // Shuffling low element of v1 into undef, just return v1.
6946     if (V2IsUndef)
6947       return V1;
6948     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6949     // the instruction selector will not match, so get a canonical MOVL with
6950     // swapped operands to undo the commute.
6951     return getMOVL(DAG, dl, VT, V2, V1);
6952   }
6953
6954   if (isUNPCKLMask(M, VT, HasInt256))
6955     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6956
6957   if (isUNPCKHMask(M, VT, HasInt256))
6958     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6959
6960   if (V2IsSplat) {
6961     // Normalize mask so all entries that point to V2 points to its first
6962     // element then try to match unpck{h|l} again. If match, return a
6963     // new vector_shuffle with the corrected mask.p
6964     SmallVector<int, 8> NewMask(M.begin(), M.end());
6965     NormalizeMask(NewMask, NumElems);
6966     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6967       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6968     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6969       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6970   }
6971
6972   if (Commuted) {
6973     // Commute is back and try unpck* again.
6974     // FIXME: this seems wrong.
6975     CommuteVectorShuffleMask(M, NumElems);
6976     std::swap(V1, V2);
6977     std::swap(V1IsSplat, V2IsSplat);
6978     Commuted = false;
6979
6980     if (isUNPCKLMask(M, VT, HasInt256))
6981       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6982
6983     if (isUNPCKHMask(M, VT, HasInt256))
6984       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6985   }
6986
6987   // Normalize the node to match x86 shuffle ops if needed
6988   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6989     return CommuteVectorShuffle(SVOp, DAG);
6990
6991   // The checks below are all present in isShuffleMaskLegal, but they are
6992   // inlined here right now to enable us to directly emit target specific
6993   // nodes, and remove one by one until they don't return Op anymore.
6994
6995   if (isPALIGNRMask(M, VT, Subtarget))
6996     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6997                                 getShufflePALIGNRImmediate(SVOp),
6998                                 DAG);
6999
7000   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7001       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7002     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7003       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7004   }
7005
7006   if (isPSHUFHWMask(M, VT, HasInt256))
7007     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7008                                 getShufflePSHUFHWImmediate(SVOp),
7009                                 DAG);
7010
7011   if (isPSHUFLWMask(M, VT, HasInt256))
7012     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7013                                 getShufflePSHUFLWImmediate(SVOp),
7014                                 DAG);
7015
7016   if (isSHUFPMask(M, VT, HasFp256))
7017     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7018                                 getShuffleSHUFImmediate(SVOp), DAG);
7019
7020   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7021     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7022   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7023     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7024
7025   //===--------------------------------------------------------------------===//
7026   // Generate target specific nodes for 128 or 256-bit shuffles only
7027   // supported in the AVX instruction set.
7028   //
7029
7030   // Handle VMOVDDUPY permutations
7031   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7032     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7033
7034   // Handle VPERMILPS/D* permutations
7035   if (isVPERMILPMask(M, VT, HasFp256)) {
7036     if (HasInt256 && VT == MVT::v8i32)
7037       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7038                                   getShuffleSHUFImmediate(SVOp), DAG);
7039     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7040                                 getShuffleSHUFImmediate(SVOp), DAG);
7041   }
7042
7043   // Handle VPERM2F128/VPERM2I128 permutations
7044   if (isVPERM2X128Mask(M, VT, HasFp256))
7045     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7046                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7047
7048   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7049   if (BlendOp.getNode())
7050     return BlendOp;
7051
7052   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7053     SmallVector<SDValue, 8> permclMask;
7054     for (unsigned i = 0; i != 8; ++i) {
7055       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7056     }
7057     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7058                                &permclMask[0], 8);
7059     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7060     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7061                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7062   }
7063
7064   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7065     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7066                                 getShuffleCLImmediate(SVOp), DAG);
7067
7068   //===--------------------------------------------------------------------===//
7069   // Since no target specific shuffle was selected for this generic one,
7070   // lower it into other known shuffles. FIXME: this isn't true yet, but
7071   // this is the plan.
7072   //
7073
7074   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7075   if (VT == MVT::v8i16) {
7076     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7077     if (NewOp.getNode())
7078       return NewOp;
7079   }
7080
7081   if (VT == MVT::v16i8) {
7082     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7083     if (NewOp.getNode())
7084       return NewOp;
7085   }
7086
7087   if (VT == MVT::v32i8) {
7088     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7089     if (NewOp.getNode())
7090       return NewOp;
7091   }
7092
7093   // Handle all 128-bit wide vectors with 4 elements, and match them with
7094   // several different shuffle types.
7095   if (NumElems == 4 && VT.is128BitVector())
7096     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7097
7098   // Handle general 256-bit shuffles
7099   if (VT.is256BitVector())
7100     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7101
7102   return SDValue();
7103 }
7104
7105 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7106   MVT VT = Op.getValueType().getSimpleVT();
7107   DebugLoc dl = Op.getDebugLoc();
7108
7109   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7110     return SDValue();
7111
7112   if (VT.getSizeInBits() == 8) {
7113     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7114                                   Op.getOperand(0), Op.getOperand(1));
7115     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7116                                   DAG.getValueType(VT));
7117     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7118   }
7119
7120   if (VT.getSizeInBits() == 16) {
7121     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7122     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7123     if (Idx == 0)
7124       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7125                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7126                                      DAG.getNode(ISD::BITCAST, dl,
7127                                                  MVT::v4i32,
7128                                                  Op.getOperand(0)),
7129                                      Op.getOperand(1)));
7130     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7131                                   Op.getOperand(0), Op.getOperand(1));
7132     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7133                                   DAG.getValueType(VT));
7134     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7135   }
7136
7137   if (VT == MVT::f32) {
7138     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7139     // the result back to FR32 register. It's only worth matching if the
7140     // result has a single use which is a store or a bitcast to i32.  And in
7141     // the case of a store, it's not worth it if the index is a constant 0,
7142     // because a MOVSSmr can be used instead, which is smaller and faster.
7143     if (!Op.hasOneUse())
7144       return SDValue();
7145     SDNode *User = *Op.getNode()->use_begin();
7146     if ((User->getOpcode() != ISD::STORE ||
7147          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7148           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7149         (User->getOpcode() != ISD::BITCAST ||
7150          User->getValueType(0) != MVT::i32))
7151       return SDValue();
7152     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7153                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7154                                               Op.getOperand(0)),
7155                                               Op.getOperand(1));
7156     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7157   }
7158
7159   if (VT == MVT::i32 || VT == MVT::i64) {
7160     // ExtractPS/pextrq works with constant index.
7161     if (isa<ConstantSDNode>(Op.getOperand(1)))
7162       return Op;
7163   }
7164   return SDValue();
7165 }
7166
7167 SDValue
7168 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7169                                            SelectionDAG &DAG) const {
7170   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7171     return SDValue();
7172
7173   SDValue Vec = Op.getOperand(0);
7174   MVT VecVT = Vec.getValueType().getSimpleVT();
7175
7176   // If this is a 256-bit vector result, first extract the 128-bit vector and
7177   // then extract the element from the 128-bit vector.
7178   if (VecVT.is256BitVector()) {
7179     DebugLoc dl = Op.getNode()->getDebugLoc();
7180     unsigned NumElems = VecVT.getVectorNumElements();
7181     SDValue Idx = Op.getOperand(1);
7182     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7183
7184     // Get the 128-bit vector.
7185     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7186
7187     if (IdxVal >= NumElems/2)
7188       IdxVal -= NumElems/2;
7189     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7190                        DAG.getConstant(IdxVal, MVT::i32));
7191   }
7192
7193   assert(VecVT.is128BitVector() && "Unexpected vector length");
7194
7195   if (Subtarget->hasSSE41()) {
7196     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7197     if (Res.getNode())
7198       return Res;
7199   }
7200
7201   MVT VT = Op.getValueType().getSimpleVT();
7202   DebugLoc dl = Op.getDebugLoc();
7203   // TODO: handle v16i8.
7204   if (VT.getSizeInBits() == 16) {
7205     SDValue Vec = Op.getOperand(0);
7206     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7207     if (Idx == 0)
7208       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7209                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7210                                      DAG.getNode(ISD::BITCAST, dl,
7211                                                  MVT::v4i32, Vec),
7212                                      Op.getOperand(1)));
7213     // Transform it so it match pextrw which produces a 32-bit result.
7214     MVT EltVT = MVT::i32;
7215     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7216                                   Op.getOperand(0), Op.getOperand(1));
7217     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7218                                   DAG.getValueType(VT));
7219     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7220   }
7221
7222   if (VT.getSizeInBits() == 32) {
7223     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7224     if (Idx == 0)
7225       return Op;
7226
7227     // SHUFPS the element to the lowest double word, then movss.
7228     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7229     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7230     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7231                                        DAG.getUNDEF(VVT), Mask);
7232     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7233                        DAG.getIntPtrConstant(0));
7234   }
7235
7236   if (VT.getSizeInBits() == 64) {
7237     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7238     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7239     //        to match extract_elt for f64.
7240     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7241     if (Idx == 0)
7242       return Op;
7243
7244     // UNPCKHPD the element to the lowest double word, then movsd.
7245     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7246     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7247     int Mask[2] = { 1, -1 };
7248     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7249     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7250                                        DAG.getUNDEF(VVT), Mask);
7251     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7252                        DAG.getIntPtrConstant(0));
7253   }
7254
7255   return SDValue();
7256 }
7257
7258 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7259   MVT VT = Op.getValueType().getSimpleVT();
7260   MVT EltVT = VT.getVectorElementType();
7261   DebugLoc dl = Op.getDebugLoc();
7262
7263   SDValue N0 = Op.getOperand(0);
7264   SDValue N1 = Op.getOperand(1);
7265   SDValue N2 = Op.getOperand(2);
7266
7267   if (!VT.is128BitVector())
7268     return SDValue();
7269
7270   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7271       isa<ConstantSDNode>(N2)) {
7272     unsigned Opc;
7273     if (VT == MVT::v8i16)
7274       Opc = X86ISD::PINSRW;
7275     else if (VT == MVT::v16i8)
7276       Opc = X86ISD::PINSRB;
7277     else
7278       Opc = X86ISD::PINSRB;
7279
7280     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7281     // argument.
7282     if (N1.getValueType() != MVT::i32)
7283       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7284     if (N2.getValueType() != MVT::i32)
7285       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7286     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7287   }
7288
7289   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7290     // Bits [7:6] of the constant are the source select.  This will always be
7291     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7292     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7293     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7294     // Bits [5:4] of the constant are the destination select.  This is the
7295     //  value of the incoming immediate.
7296     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7297     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7298     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7299     // Create this as a scalar to vector..
7300     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7301     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7302   }
7303
7304   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7305     // PINSR* works with constant index.
7306     return Op;
7307   }
7308   return SDValue();
7309 }
7310
7311 SDValue
7312 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7313   MVT VT = Op.getValueType().getSimpleVT();
7314   MVT EltVT = VT.getVectorElementType();
7315
7316   DebugLoc dl = Op.getDebugLoc();
7317   SDValue N0 = Op.getOperand(0);
7318   SDValue N1 = Op.getOperand(1);
7319   SDValue N2 = Op.getOperand(2);
7320
7321   // If this is a 256-bit vector result, first extract the 128-bit vector,
7322   // insert the element into the extracted half and then place it back.
7323   if (VT.is256BitVector()) {
7324     if (!isa<ConstantSDNode>(N2))
7325       return SDValue();
7326
7327     // Get the desired 128-bit vector half.
7328     unsigned NumElems = VT.getVectorNumElements();
7329     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7330     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7331
7332     // Insert the element into the desired half.
7333     bool Upper = IdxVal >= NumElems/2;
7334     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7335                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7336
7337     // Insert the changed part back to the 256-bit vector
7338     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7339   }
7340
7341   if (Subtarget->hasSSE41())
7342     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7343
7344   if (EltVT == MVT::i8)
7345     return SDValue();
7346
7347   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7348     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7349     // as its second argument.
7350     if (N1.getValueType() != MVT::i32)
7351       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7352     if (N2.getValueType() != MVT::i32)
7353       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7354     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7355   }
7356   return SDValue();
7357 }
7358
7359 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7360   LLVMContext *Context = DAG.getContext();
7361   DebugLoc dl = Op.getDebugLoc();
7362   MVT OpVT = Op.getValueType().getSimpleVT();
7363
7364   // If this is a 256-bit vector result, first insert into a 128-bit
7365   // vector and then insert into the 256-bit vector.
7366   if (!OpVT.is128BitVector()) {
7367     // Insert into a 128-bit vector.
7368     EVT VT128 = EVT::getVectorVT(*Context,
7369                                  OpVT.getVectorElementType(),
7370                                  OpVT.getVectorNumElements() / 2);
7371
7372     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7373
7374     // Insert the 128-bit vector.
7375     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7376   }
7377
7378   if (OpVT == MVT::v1i64 &&
7379       Op.getOperand(0).getValueType() == MVT::i64)
7380     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7381
7382   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7383   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7384   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7385                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7386 }
7387
7388 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7389 // a simple subregister reference or explicit instructions to grab
7390 // upper bits of a vector.
7391 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7392                                       SelectionDAG &DAG) {
7393   if (Subtarget->hasFp256()) {
7394     DebugLoc dl = Op.getNode()->getDebugLoc();
7395     SDValue Vec = Op.getNode()->getOperand(0);
7396     SDValue Idx = Op.getNode()->getOperand(1);
7397
7398     if (Op.getNode()->getValueType(0).is128BitVector() &&
7399         Vec.getNode()->getValueType(0).is256BitVector() &&
7400         isa<ConstantSDNode>(Idx)) {
7401       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7402       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7403     }
7404   }
7405   return SDValue();
7406 }
7407
7408 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7409 // simple superregister reference or explicit instructions to insert
7410 // the upper bits of a vector.
7411 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7412                                      SelectionDAG &DAG) {
7413   if (Subtarget->hasFp256()) {
7414     DebugLoc dl = Op.getNode()->getDebugLoc();
7415     SDValue Vec = Op.getNode()->getOperand(0);
7416     SDValue SubVec = Op.getNode()->getOperand(1);
7417     SDValue Idx = Op.getNode()->getOperand(2);
7418
7419     if (Op.getNode()->getValueType(0).is256BitVector() &&
7420         SubVec.getNode()->getValueType(0).is128BitVector() &&
7421         isa<ConstantSDNode>(Idx)) {
7422       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7423       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7424     }
7425   }
7426   return SDValue();
7427 }
7428
7429 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7430 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7431 // one of the above mentioned nodes. It has to be wrapped because otherwise
7432 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7433 // be used to form addressing mode. These wrapped nodes will be selected
7434 // into MOV32ri.
7435 SDValue
7436 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7437   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7438
7439   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7440   // global base reg.
7441   unsigned char OpFlag = 0;
7442   unsigned WrapperKind = X86ISD::Wrapper;
7443   CodeModel::Model M = getTargetMachine().getCodeModel();
7444
7445   if (Subtarget->isPICStyleRIPRel() &&
7446       (M == CodeModel::Small || M == CodeModel::Kernel))
7447     WrapperKind = X86ISD::WrapperRIP;
7448   else if (Subtarget->isPICStyleGOT())
7449     OpFlag = X86II::MO_GOTOFF;
7450   else if (Subtarget->isPICStyleStubPIC())
7451     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7452
7453   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7454                                              CP->getAlignment(),
7455                                              CP->getOffset(), OpFlag);
7456   DebugLoc DL = CP->getDebugLoc();
7457   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7458   // With PIC, the address is actually $g + Offset.
7459   if (OpFlag) {
7460     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7461                          DAG.getNode(X86ISD::GlobalBaseReg,
7462                                      DebugLoc(), getPointerTy()),
7463                          Result);
7464   }
7465
7466   return Result;
7467 }
7468
7469 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7470   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7471
7472   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7473   // global base reg.
7474   unsigned char OpFlag = 0;
7475   unsigned WrapperKind = X86ISD::Wrapper;
7476   CodeModel::Model M = getTargetMachine().getCodeModel();
7477
7478   if (Subtarget->isPICStyleRIPRel() &&
7479       (M == CodeModel::Small || M == CodeModel::Kernel))
7480     WrapperKind = X86ISD::WrapperRIP;
7481   else if (Subtarget->isPICStyleGOT())
7482     OpFlag = X86II::MO_GOTOFF;
7483   else if (Subtarget->isPICStyleStubPIC())
7484     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7485
7486   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7487                                           OpFlag);
7488   DebugLoc DL = JT->getDebugLoc();
7489   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7490
7491   // With PIC, the address is actually $g + Offset.
7492   if (OpFlag)
7493     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7494                          DAG.getNode(X86ISD::GlobalBaseReg,
7495                                      DebugLoc(), getPointerTy()),
7496                          Result);
7497
7498   return Result;
7499 }
7500
7501 SDValue
7502 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7503   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7504
7505   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7506   // global base reg.
7507   unsigned char OpFlag = 0;
7508   unsigned WrapperKind = X86ISD::Wrapper;
7509   CodeModel::Model M = getTargetMachine().getCodeModel();
7510
7511   if (Subtarget->isPICStyleRIPRel() &&
7512       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7513     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7514       OpFlag = X86II::MO_GOTPCREL;
7515     WrapperKind = X86ISD::WrapperRIP;
7516   } else if (Subtarget->isPICStyleGOT()) {
7517     OpFlag = X86II::MO_GOT;
7518   } else if (Subtarget->isPICStyleStubPIC()) {
7519     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7520   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7521     OpFlag = X86II::MO_DARWIN_NONLAZY;
7522   }
7523
7524   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7525
7526   DebugLoc DL = Op.getDebugLoc();
7527   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7528
7529   // With PIC, the address is actually $g + Offset.
7530   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7531       !Subtarget->is64Bit()) {
7532     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7533                          DAG.getNode(X86ISD::GlobalBaseReg,
7534                                      DebugLoc(), getPointerTy()),
7535                          Result);
7536   }
7537
7538   // For symbols that require a load from a stub to get the address, emit the
7539   // load.
7540   if (isGlobalStubReference(OpFlag))
7541     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7542                          MachinePointerInfo::getGOT(), false, false, false, 0);
7543
7544   return Result;
7545 }
7546
7547 SDValue
7548 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7549   // Create the TargetBlockAddressAddress node.
7550   unsigned char OpFlags =
7551     Subtarget->ClassifyBlockAddressReference();
7552   CodeModel::Model M = getTargetMachine().getCodeModel();
7553   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7554   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7555   DebugLoc dl = Op.getDebugLoc();
7556   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7557                                              OpFlags);
7558
7559   if (Subtarget->isPICStyleRIPRel() &&
7560       (M == CodeModel::Small || M == CodeModel::Kernel))
7561     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7562   else
7563     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7564
7565   // With PIC, the address is actually $g + Offset.
7566   if (isGlobalRelativeToPICBase(OpFlags)) {
7567     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7568                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7569                          Result);
7570   }
7571
7572   return Result;
7573 }
7574
7575 SDValue
7576 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7577                                       int64_t Offset, SelectionDAG &DAG) const {
7578   // Create the TargetGlobalAddress node, folding in the constant
7579   // offset if it is legal.
7580   unsigned char OpFlags =
7581     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7582   CodeModel::Model M = getTargetMachine().getCodeModel();
7583   SDValue Result;
7584   if (OpFlags == X86II::MO_NO_FLAG &&
7585       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7586     // A direct static reference to a global.
7587     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7588     Offset = 0;
7589   } else {
7590     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7591   }
7592
7593   if (Subtarget->isPICStyleRIPRel() &&
7594       (M == CodeModel::Small || M == CodeModel::Kernel))
7595     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7596   else
7597     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7598
7599   // With PIC, the address is actually $g + Offset.
7600   if (isGlobalRelativeToPICBase(OpFlags)) {
7601     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7602                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7603                          Result);
7604   }
7605
7606   // For globals that require a load from a stub to get the address, emit the
7607   // load.
7608   if (isGlobalStubReference(OpFlags))
7609     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7610                          MachinePointerInfo::getGOT(), false, false, false, 0);
7611
7612   // If there was a non-zero offset that we didn't fold, create an explicit
7613   // addition for it.
7614   if (Offset != 0)
7615     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7616                          DAG.getConstant(Offset, getPointerTy()));
7617
7618   return Result;
7619 }
7620
7621 SDValue
7622 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7623   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7624   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7625   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7626 }
7627
7628 static SDValue
7629 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7630            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7631            unsigned char OperandFlags, bool LocalDynamic = false) {
7632   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7633   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7634   DebugLoc dl = GA->getDebugLoc();
7635   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7636                                            GA->getValueType(0),
7637                                            GA->getOffset(),
7638                                            OperandFlags);
7639
7640   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7641                                            : X86ISD::TLSADDR;
7642
7643   if (InFlag) {
7644     SDValue Ops[] = { Chain,  TGA, *InFlag };
7645     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7646   } else {
7647     SDValue Ops[]  = { Chain, TGA };
7648     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7649   }
7650
7651   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7652   MFI->setAdjustsStack(true);
7653
7654   SDValue Flag = Chain.getValue(1);
7655   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7656 }
7657
7658 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7659 static SDValue
7660 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7661                                 const EVT PtrVT) {
7662   SDValue InFlag;
7663   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7664   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7665                                    DAG.getNode(X86ISD::GlobalBaseReg,
7666                                                DebugLoc(), PtrVT), InFlag);
7667   InFlag = Chain.getValue(1);
7668
7669   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7670 }
7671
7672 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7673 static SDValue
7674 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7675                                 const EVT PtrVT) {
7676   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7677                     X86::RAX, X86II::MO_TLSGD);
7678 }
7679
7680 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7681                                            SelectionDAG &DAG,
7682                                            const EVT PtrVT,
7683                                            bool is64Bit) {
7684   DebugLoc dl = GA->getDebugLoc();
7685
7686   // Get the start address of the TLS block for this module.
7687   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7688       .getInfo<X86MachineFunctionInfo>();
7689   MFI->incNumLocalDynamicTLSAccesses();
7690
7691   SDValue Base;
7692   if (is64Bit) {
7693     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7694                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7695   } else {
7696     SDValue InFlag;
7697     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7698         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7699     InFlag = Chain.getValue(1);
7700     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7701                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7702   }
7703
7704   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7705   // of Base.
7706
7707   // Build x@dtpoff.
7708   unsigned char OperandFlags = X86II::MO_DTPOFF;
7709   unsigned WrapperKind = X86ISD::Wrapper;
7710   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7711                                            GA->getValueType(0),
7712                                            GA->getOffset(), OperandFlags);
7713   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7714
7715   // Add x@dtpoff with the base.
7716   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7717 }
7718
7719 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7720 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7721                                    const EVT PtrVT, TLSModel::Model model,
7722                                    bool is64Bit, bool isPIC) {
7723   DebugLoc dl = GA->getDebugLoc();
7724
7725   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7726   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7727                                                          is64Bit ? 257 : 256));
7728
7729   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7730                                       DAG.getIntPtrConstant(0),
7731                                       MachinePointerInfo(Ptr),
7732                                       false, false, false, 0);
7733
7734   unsigned char OperandFlags = 0;
7735   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7736   // initialexec.
7737   unsigned WrapperKind = X86ISD::Wrapper;
7738   if (model == TLSModel::LocalExec) {
7739     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7740   } else if (model == TLSModel::InitialExec) {
7741     if (is64Bit) {
7742       OperandFlags = X86II::MO_GOTTPOFF;
7743       WrapperKind = X86ISD::WrapperRIP;
7744     } else {
7745       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7746     }
7747   } else {
7748     llvm_unreachable("Unexpected model");
7749   }
7750
7751   // emit "addl x@ntpoff,%eax" (local exec)
7752   // or "addl x@indntpoff,%eax" (initial exec)
7753   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7754   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7755                                            GA->getValueType(0),
7756                                            GA->getOffset(), OperandFlags);
7757   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7758
7759   if (model == TLSModel::InitialExec) {
7760     if (isPIC && !is64Bit) {
7761       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7762                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7763                            Offset);
7764     }
7765
7766     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7767                          MachinePointerInfo::getGOT(), false, false, false,
7768                          0);
7769   }
7770
7771   // The address of the thread local variable is the add of the thread
7772   // pointer with the offset of the variable.
7773   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7774 }
7775
7776 SDValue
7777 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7778
7779   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7780   const GlobalValue *GV = GA->getGlobal();
7781
7782   if (Subtarget->isTargetELF()) {
7783     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7784
7785     switch (model) {
7786       case TLSModel::GeneralDynamic:
7787         if (Subtarget->is64Bit())
7788           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7789         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7790       case TLSModel::LocalDynamic:
7791         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7792                                            Subtarget->is64Bit());
7793       case TLSModel::InitialExec:
7794       case TLSModel::LocalExec:
7795         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7796                                    Subtarget->is64Bit(),
7797                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7798     }
7799     llvm_unreachable("Unknown TLS model.");
7800   }
7801
7802   if (Subtarget->isTargetDarwin()) {
7803     // Darwin only has one model of TLS.  Lower to that.
7804     unsigned char OpFlag = 0;
7805     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7806                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7807
7808     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7809     // global base reg.
7810     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7811                   !Subtarget->is64Bit();
7812     if (PIC32)
7813       OpFlag = X86II::MO_TLVP_PIC_BASE;
7814     else
7815       OpFlag = X86II::MO_TLVP;
7816     DebugLoc DL = Op.getDebugLoc();
7817     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7818                                                 GA->getValueType(0),
7819                                                 GA->getOffset(), OpFlag);
7820     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7821
7822     // With PIC32, the address is actually $g + Offset.
7823     if (PIC32)
7824       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7825                            DAG.getNode(X86ISD::GlobalBaseReg,
7826                                        DebugLoc(), getPointerTy()),
7827                            Offset);
7828
7829     // Lowering the machine isd will make sure everything is in the right
7830     // location.
7831     SDValue Chain = DAG.getEntryNode();
7832     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7833     SDValue Args[] = { Chain, Offset };
7834     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7835
7836     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7837     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7838     MFI->setAdjustsStack(true);
7839
7840     // And our return value (tls address) is in the standard call return value
7841     // location.
7842     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7843     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7844                               Chain.getValue(1));
7845   }
7846
7847   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7848     // Just use the implicit TLS architecture
7849     // Need to generate someting similar to:
7850     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7851     //                                  ; from TEB
7852     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7853     //   mov     rcx, qword [rdx+rcx*8]
7854     //   mov     eax, .tls$:tlsvar
7855     //   [rax+rcx] contains the address
7856     // Windows 64bit: gs:0x58
7857     // Windows 32bit: fs:__tls_array
7858
7859     // If GV is an alias then use the aliasee for determining
7860     // thread-localness.
7861     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7862       GV = GA->resolveAliasedGlobal(false);
7863     DebugLoc dl = GA->getDebugLoc();
7864     SDValue Chain = DAG.getEntryNode();
7865
7866     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7867     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7868     // use its literal value of 0x2C.
7869     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7870                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7871                                                              256)
7872                                         : Type::getInt32PtrTy(*DAG.getContext(),
7873                                                               257));
7874
7875     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7876       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7877         DAG.getExternalSymbol("_tls_array", getPointerTy()));
7878
7879     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7880                                         MachinePointerInfo(Ptr),
7881                                         false, false, false, 0);
7882
7883     // Load the _tls_index variable
7884     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7885     if (Subtarget->is64Bit())
7886       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7887                            IDX, MachinePointerInfo(), MVT::i32,
7888                            false, false, 0);
7889     else
7890       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7891                         false, false, false, 0);
7892
7893     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7894                                     getPointerTy());
7895     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7896
7897     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7898     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7899                       false, false, false, 0);
7900
7901     // Get the offset of start of .tls section
7902     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7903                                              GA->getValueType(0),
7904                                              GA->getOffset(), X86II::MO_SECREL);
7905     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7906
7907     // The address of the thread local variable is the add of the thread
7908     // pointer with the offset of the variable.
7909     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7910   }
7911
7912   llvm_unreachable("TLS not implemented for this target.");
7913 }
7914
7915 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7916 /// and take a 2 x i32 value to shift plus a shift amount.
7917 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7918   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7919   EVT VT = Op.getValueType();
7920   unsigned VTBits = VT.getSizeInBits();
7921   DebugLoc dl = Op.getDebugLoc();
7922   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7923   SDValue ShOpLo = Op.getOperand(0);
7924   SDValue ShOpHi = Op.getOperand(1);
7925   SDValue ShAmt  = Op.getOperand(2);
7926   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7927                                      DAG.getConstant(VTBits - 1, MVT::i8))
7928                        : DAG.getConstant(0, VT);
7929
7930   SDValue Tmp2, Tmp3;
7931   if (Op.getOpcode() == ISD::SHL_PARTS) {
7932     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7933     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7934   } else {
7935     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7936     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7937   }
7938
7939   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7940                                 DAG.getConstant(VTBits, MVT::i8));
7941   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7942                              AndNode, DAG.getConstant(0, MVT::i8));
7943
7944   SDValue Hi, Lo;
7945   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7946   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7947   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7948
7949   if (Op.getOpcode() == ISD::SHL_PARTS) {
7950     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7951     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7952   } else {
7953     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7954     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7955   }
7956
7957   SDValue Ops[2] = { Lo, Hi };
7958   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7959 }
7960
7961 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7962                                            SelectionDAG &DAG) const {
7963   EVT SrcVT = Op.getOperand(0).getValueType();
7964
7965   if (SrcVT.isVector())
7966     return SDValue();
7967
7968   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7969          "Unknown SINT_TO_FP to lower!");
7970
7971   // These are really Legal; return the operand so the caller accepts it as
7972   // Legal.
7973   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7974     return Op;
7975   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7976       Subtarget->is64Bit()) {
7977     return Op;
7978   }
7979
7980   DebugLoc dl = Op.getDebugLoc();
7981   unsigned Size = SrcVT.getSizeInBits()/8;
7982   MachineFunction &MF = DAG.getMachineFunction();
7983   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7984   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7985   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7986                                StackSlot,
7987                                MachinePointerInfo::getFixedStack(SSFI),
7988                                false, false, 0);
7989   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7990 }
7991
7992 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7993                                      SDValue StackSlot,
7994                                      SelectionDAG &DAG) const {
7995   // Build the FILD
7996   DebugLoc DL = Op.getDebugLoc();
7997   SDVTList Tys;
7998   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7999   if (useSSE)
8000     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8001   else
8002     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8003
8004   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8005
8006   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8007   MachineMemOperand *MMO;
8008   if (FI) {
8009     int SSFI = FI->getIndex();
8010     MMO =
8011       DAG.getMachineFunction()
8012       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8013                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8014   } else {
8015     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8016     StackSlot = StackSlot.getOperand(1);
8017   }
8018   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8019   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8020                                            X86ISD::FILD, DL,
8021                                            Tys, Ops, array_lengthof(Ops),
8022                                            SrcVT, MMO);
8023
8024   if (useSSE) {
8025     Chain = Result.getValue(1);
8026     SDValue InFlag = Result.getValue(2);
8027
8028     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8029     // shouldn't be necessary except that RFP cannot be live across
8030     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8031     MachineFunction &MF = DAG.getMachineFunction();
8032     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8033     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8034     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8035     Tys = DAG.getVTList(MVT::Other);
8036     SDValue Ops[] = {
8037       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8038     };
8039     MachineMemOperand *MMO =
8040       DAG.getMachineFunction()
8041       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8042                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8043
8044     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8045                                     Ops, array_lengthof(Ops),
8046                                     Op.getValueType(), MMO);
8047     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8048                          MachinePointerInfo::getFixedStack(SSFI),
8049                          false, false, false, 0);
8050   }
8051
8052   return Result;
8053 }
8054
8055 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8056 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8057                                                SelectionDAG &DAG) const {
8058   // This algorithm is not obvious. Here it is what we're trying to output:
8059   /*
8060      movq       %rax,  %xmm0
8061      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8062      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8063      #ifdef __SSE3__
8064        haddpd   %xmm0, %xmm0
8065      #else
8066        pshufd   $0x4e, %xmm0, %xmm1
8067        addpd    %xmm1, %xmm0
8068      #endif
8069   */
8070
8071   DebugLoc dl = Op.getDebugLoc();
8072   LLVMContext *Context = DAG.getContext();
8073
8074   // Build some magic constants.
8075   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8076   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8077   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8078
8079   SmallVector<Constant*,2> CV1;
8080   CV1.push_back(
8081     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8082                                       APInt(64, 0x4330000000000000ULL))));
8083   CV1.push_back(
8084     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8085                                       APInt(64, 0x4530000000000000ULL))));
8086   Constant *C1 = ConstantVector::get(CV1);
8087   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8088
8089   // Load the 64-bit value into an XMM register.
8090   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8091                             Op.getOperand(0));
8092   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8093                               MachinePointerInfo::getConstantPool(),
8094                               false, false, false, 16);
8095   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8096                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8097                               CLod0);
8098
8099   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8100                               MachinePointerInfo::getConstantPool(),
8101                               false, false, false, 16);
8102   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8103   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8104   SDValue Result;
8105
8106   if (Subtarget->hasSSE3()) {
8107     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8108     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8109   } else {
8110     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8111     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8112                                            S2F, 0x4E, DAG);
8113     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8114                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8115                          Sub);
8116   }
8117
8118   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8119                      DAG.getIntPtrConstant(0));
8120 }
8121
8122 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8123 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8124                                                SelectionDAG &DAG) const {
8125   DebugLoc dl = Op.getDebugLoc();
8126   // FP constant to bias correct the final result.
8127   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8128                                    MVT::f64);
8129
8130   // Load the 32-bit value into an XMM register.
8131   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8132                              Op.getOperand(0));
8133
8134   // Zero out the upper parts of the register.
8135   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8136
8137   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8138                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8139                      DAG.getIntPtrConstant(0));
8140
8141   // Or the load with the bias.
8142   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8143                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8144                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8145                                                    MVT::v2f64, Load)),
8146                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8147                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8148                                                    MVT::v2f64, Bias)));
8149   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8150                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8151                    DAG.getIntPtrConstant(0));
8152
8153   // Subtract the bias.
8154   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8155
8156   // Handle final rounding.
8157   EVT DestVT = Op.getValueType();
8158
8159   if (DestVT.bitsLT(MVT::f64))
8160     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8161                        DAG.getIntPtrConstant(0));
8162   if (DestVT.bitsGT(MVT::f64))
8163     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8164
8165   // Handle final rounding.
8166   return Sub;
8167 }
8168
8169 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8170                                                SelectionDAG &DAG) const {
8171   SDValue N0 = Op.getOperand(0);
8172   EVT SVT = N0.getValueType();
8173   DebugLoc dl = Op.getDebugLoc();
8174
8175   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8176           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8177          "Custom UINT_TO_FP is not supported!");
8178
8179   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8180                              SVT.getVectorNumElements());
8181   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8182                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8183 }
8184
8185 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8186                                            SelectionDAG &DAG) const {
8187   SDValue N0 = Op.getOperand(0);
8188   DebugLoc dl = Op.getDebugLoc();
8189
8190   if (Op.getValueType().isVector())
8191     return lowerUINT_TO_FP_vec(Op, DAG);
8192
8193   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8194   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8195   // the optimization here.
8196   if (DAG.SignBitIsZero(N0))
8197     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8198
8199   EVT SrcVT = N0.getValueType();
8200   EVT DstVT = Op.getValueType();
8201   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8202     return LowerUINT_TO_FP_i64(Op, DAG);
8203   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8204     return LowerUINT_TO_FP_i32(Op, DAG);
8205   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8206     return SDValue();
8207
8208   // Make a 64-bit buffer, and use it to build an FILD.
8209   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8210   if (SrcVT == MVT::i32) {
8211     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8212     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8213                                      getPointerTy(), StackSlot, WordOff);
8214     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8215                                   StackSlot, MachinePointerInfo(),
8216                                   false, false, 0);
8217     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8218                                   OffsetSlot, MachinePointerInfo(),
8219                                   false, false, 0);
8220     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8221     return Fild;
8222   }
8223
8224   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8225   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8226                                StackSlot, MachinePointerInfo(),
8227                                false, false, 0);
8228   // For i64 source, we need to add the appropriate power of 2 if the input
8229   // was negative.  This is the same as the optimization in
8230   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8231   // we must be careful to do the computation in x87 extended precision, not
8232   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8233   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8234   MachineMemOperand *MMO =
8235     DAG.getMachineFunction()
8236     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8237                           MachineMemOperand::MOLoad, 8, 8);
8238
8239   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8240   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8241   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8242                                          array_lengthof(Ops), MVT::i64, MMO);
8243
8244   APInt FF(32, 0x5F800000ULL);
8245
8246   // Check whether the sign bit is set.
8247   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8248                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8249                                  ISD::SETLT);
8250
8251   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8252   SDValue FudgePtr = DAG.getConstantPool(
8253                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8254                                          getPointerTy());
8255
8256   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8257   SDValue Zero = DAG.getIntPtrConstant(0);
8258   SDValue Four = DAG.getIntPtrConstant(4);
8259   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8260                                Zero, Four);
8261   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8262
8263   // Load the value out, extending it from f32 to f80.
8264   // FIXME: Avoid the extend by constructing the right constant pool?
8265   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8266                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8267                                  MVT::f32, false, false, 4);
8268   // Extend everything to 80 bits to force it to be done on x87.
8269   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8270   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8271 }
8272
8273 std::pair<SDValue,SDValue>
8274 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8275                                     bool IsSigned, bool IsReplace) const {
8276   DebugLoc DL = Op.getDebugLoc();
8277
8278   EVT DstTy = Op.getValueType();
8279
8280   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8281     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8282     DstTy = MVT::i64;
8283   }
8284
8285   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8286          DstTy.getSimpleVT() >= MVT::i16 &&
8287          "Unknown FP_TO_INT to lower!");
8288
8289   // These are really Legal.
8290   if (DstTy == MVT::i32 &&
8291       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8292     return std::make_pair(SDValue(), SDValue());
8293   if (Subtarget->is64Bit() &&
8294       DstTy == MVT::i64 &&
8295       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8296     return std::make_pair(SDValue(), SDValue());
8297
8298   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8299   // stack slot, or into the FTOL runtime function.
8300   MachineFunction &MF = DAG.getMachineFunction();
8301   unsigned MemSize = DstTy.getSizeInBits()/8;
8302   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8303   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8304
8305   unsigned Opc;
8306   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8307     Opc = X86ISD::WIN_FTOL;
8308   else
8309     switch (DstTy.getSimpleVT().SimpleTy) {
8310     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8311     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8312     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8313     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8314     }
8315
8316   SDValue Chain = DAG.getEntryNode();
8317   SDValue Value = Op.getOperand(0);
8318   EVT TheVT = Op.getOperand(0).getValueType();
8319   // FIXME This causes a redundant load/store if the SSE-class value is already
8320   // in memory, such as if it is on the callstack.
8321   if (isScalarFPTypeInSSEReg(TheVT)) {
8322     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8323     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8324                          MachinePointerInfo::getFixedStack(SSFI),
8325                          false, false, 0);
8326     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8327     SDValue Ops[] = {
8328       Chain, StackSlot, DAG.getValueType(TheVT)
8329     };
8330
8331     MachineMemOperand *MMO =
8332       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8333                               MachineMemOperand::MOLoad, MemSize, MemSize);
8334     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8335                                     array_lengthof(Ops), DstTy, MMO);
8336     Chain = Value.getValue(1);
8337     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8338     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8339   }
8340
8341   MachineMemOperand *MMO =
8342     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8343                             MachineMemOperand::MOStore, MemSize, MemSize);
8344
8345   if (Opc != X86ISD::WIN_FTOL) {
8346     // Build the FP_TO_INT*_IN_MEM
8347     SDValue Ops[] = { Chain, Value, StackSlot };
8348     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8349                                            Ops, array_lengthof(Ops), DstTy,
8350                                            MMO);
8351     return std::make_pair(FIST, StackSlot);
8352   } else {
8353     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8354       DAG.getVTList(MVT::Other, MVT::Glue),
8355       Chain, Value);
8356     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8357       MVT::i32, ftol.getValue(1));
8358     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8359       MVT::i32, eax.getValue(2));
8360     SDValue Ops[] = { eax, edx };
8361     SDValue pair = IsReplace
8362       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8363       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8364     return std::make_pair(pair, SDValue());
8365   }
8366 }
8367
8368 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8369                               const X86Subtarget *Subtarget) {
8370   MVT VT = Op->getValueType(0).getSimpleVT();
8371   SDValue In = Op->getOperand(0);
8372   MVT InVT = In.getValueType().getSimpleVT();
8373   DebugLoc dl = Op->getDebugLoc();
8374
8375   // Optimize vectors in AVX mode:
8376   //
8377   //   v8i16 -> v8i32
8378   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8379   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8380   //   Concat upper and lower parts.
8381   //
8382   //   v4i32 -> v4i64
8383   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8384   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8385   //   Concat upper and lower parts.
8386   //
8387
8388   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8389       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8390     return SDValue();
8391
8392   if (Subtarget->hasInt256())
8393     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8394
8395   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8396   SDValue Undef = DAG.getUNDEF(InVT);
8397   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8398   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8399   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8400
8401   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8402                              VT.getVectorNumElements()/2);
8403
8404   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8405   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8406
8407   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8408 }
8409
8410 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8411                                            SelectionDAG &DAG) const {
8412   if (Subtarget->hasFp256()) {
8413     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8414     if (Res.getNode())
8415       return Res;
8416   }
8417
8418   return SDValue();
8419 }
8420 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8421                                             SelectionDAG &DAG) const {
8422   DebugLoc DL = Op.getDebugLoc();
8423   MVT VT = Op.getValueType().getSimpleVT();
8424   SDValue In = Op.getOperand(0);
8425   MVT SVT = In.getValueType().getSimpleVT();
8426
8427   if (Subtarget->hasFp256()) {
8428     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8429     if (Res.getNode())
8430       return Res;
8431   }
8432
8433   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8434       VT.getVectorNumElements() != SVT.getVectorNumElements())
8435     return SDValue();
8436
8437   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8438
8439   // AVX2 has better support of integer extending.
8440   if (Subtarget->hasInt256())
8441     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8442
8443   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8444   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8445   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8446                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8447                                                 DAG.getUNDEF(MVT::v8i16),
8448                                                 &Mask[0]));
8449
8450   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8451 }
8452
8453 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8454   DebugLoc DL = Op.getDebugLoc();
8455   MVT VT = Op.getValueType().getSimpleVT();
8456   SDValue In = Op.getOperand(0);
8457   MVT SVT = In.getValueType().getSimpleVT();
8458
8459   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8460     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8461     if (Subtarget->hasInt256()) {
8462       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8463       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8464       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8465                                 ShufMask);
8466       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8467                          DAG.getIntPtrConstant(0));
8468     }
8469
8470     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8471     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8472                                DAG.getIntPtrConstant(0));
8473     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8474                                DAG.getIntPtrConstant(2));
8475
8476     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8477     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8478
8479     // The PSHUFD mask:
8480     static const int ShufMask1[] = {0, 2, 0, 0};
8481     SDValue Undef = DAG.getUNDEF(VT);
8482     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8483     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8484
8485     // The MOVLHPS mask:
8486     static const int ShufMask2[] = {0, 1, 4, 5};
8487     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8488   }
8489
8490   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8491     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8492     if (Subtarget->hasInt256()) {
8493       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8494
8495       SmallVector<SDValue,32> pshufbMask;
8496       for (unsigned i = 0; i < 2; ++i) {
8497         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8498         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8499         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8500         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8501         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8502         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8503         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8504         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8505         for (unsigned j = 0; j < 8; ++j)
8506           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8507       }
8508       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8509                                &pshufbMask[0], 32);
8510       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8511       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8512
8513       static const int ShufMask[] = {0,  2,  -1,  -1};
8514       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8515                                 &ShufMask[0]);
8516       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8517                        DAG.getIntPtrConstant(0));
8518       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8519     }
8520
8521     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8522                                DAG.getIntPtrConstant(0));
8523
8524     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8525                                DAG.getIntPtrConstant(4));
8526
8527     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8528     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8529
8530     // The PSHUFB mask:
8531     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8532                                    -1, -1, -1, -1, -1, -1, -1, -1};
8533
8534     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8535     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8536     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8537
8538     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8539     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8540
8541     // The MOVLHPS Mask:
8542     static const int ShufMask2[] = {0, 1, 4, 5};
8543     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8544     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8545   }
8546
8547   // Handle truncation of V256 to V128 using shuffles.
8548   if (!VT.is128BitVector() || !SVT.is256BitVector())
8549     return SDValue();
8550
8551   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8552          "Invalid op");
8553   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8554
8555   unsigned NumElems = VT.getVectorNumElements();
8556   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8557                              NumElems * 2);
8558
8559   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8560   // Prepare truncation shuffle mask
8561   for (unsigned i = 0; i != NumElems; ++i)
8562     MaskVec[i] = i * 2;
8563   SDValue V = DAG.getVectorShuffle(NVT, DL,
8564                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8565                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8566   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8567                      DAG.getIntPtrConstant(0));
8568 }
8569
8570 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8571                                            SelectionDAG &DAG) const {
8572   MVT VT = Op.getValueType().getSimpleVT();
8573   if (VT.isVector()) {
8574     if (VT == MVT::v8i16)
8575       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8576                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8577                                      MVT::v8i32, Op.getOperand(0)));
8578     return SDValue();
8579   }
8580
8581   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8582     /*IsSigned=*/ true, /*IsReplace=*/ false);
8583   SDValue FIST = Vals.first, StackSlot = Vals.second;
8584   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8585   if (FIST.getNode() == 0) return Op;
8586
8587   if (StackSlot.getNode())
8588     // Load the result.
8589     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8590                        FIST, StackSlot, MachinePointerInfo(),
8591                        false, false, false, 0);
8592
8593   // The node is the result.
8594   return FIST;
8595 }
8596
8597 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8598                                            SelectionDAG &DAG) const {
8599   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8600     /*IsSigned=*/ false, /*IsReplace=*/ false);
8601   SDValue FIST = Vals.first, StackSlot = Vals.second;
8602   assert(FIST.getNode() && "Unexpected failure");
8603
8604   if (StackSlot.getNode())
8605     // Load the result.
8606     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8607                        FIST, StackSlot, MachinePointerInfo(),
8608                        false, false, false, 0);
8609
8610   // The node is the result.
8611   return FIST;
8612 }
8613
8614 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8615   DebugLoc DL = Op.getDebugLoc();
8616   MVT VT = Op.getValueType().getSimpleVT();
8617   SDValue In = Op.getOperand(0);
8618   MVT SVT = In.getValueType().getSimpleVT();
8619
8620   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8621
8622   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8623                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8624                                  In, DAG.getUNDEF(SVT)));
8625 }
8626
8627 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8628   LLVMContext *Context = DAG.getContext();
8629   DebugLoc dl = Op.getDebugLoc();
8630   MVT VT = Op.getValueType().getSimpleVT();
8631   MVT EltVT = VT;
8632   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8633   if (VT.isVector()) {
8634     EltVT = VT.getVectorElementType();
8635     NumElts = VT.getVectorNumElements();
8636   }
8637   Constant *C;
8638   if (EltVT == MVT::f64)
8639     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8640                                           APInt(64, ~(1ULL << 63))));
8641   else
8642     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8643                                           APInt(32, ~(1U << 31))));
8644   C = ConstantVector::getSplat(NumElts, C);
8645   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8646   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8647   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8648                              MachinePointerInfo::getConstantPool(),
8649                              false, false, false, Alignment);
8650   if (VT.isVector()) {
8651     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8652     return DAG.getNode(ISD::BITCAST, dl, VT,
8653                        DAG.getNode(ISD::AND, dl, ANDVT,
8654                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8655                                                Op.getOperand(0)),
8656                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8657   }
8658   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8659 }
8660
8661 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8662   LLVMContext *Context = DAG.getContext();
8663   DebugLoc dl = Op.getDebugLoc();
8664   MVT VT = Op.getValueType().getSimpleVT();
8665   MVT EltVT = VT;
8666   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8667   if (VT.isVector()) {
8668     EltVT = VT.getVectorElementType();
8669     NumElts = VT.getVectorNumElements();
8670   }
8671   Constant *C;
8672   if (EltVT == MVT::f64)
8673     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8674                                           APInt(64, 1ULL << 63)));
8675   else
8676     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8677                                           APInt(32, 1U << 31)));
8678   C = ConstantVector::getSplat(NumElts, C);
8679   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8680   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8681   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8682                              MachinePointerInfo::getConstantPool(),
8683                              false, false, false, Alignment);
8684   if (VT.isVector()) {
8685     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8686     return DAG.getNode(ISD::BITCAST, dl, VT,
8687                        DAG.getNode(ISD::XOR, dl, XORVT,
8688                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8689                                                Op.getOperand(0)),
8690                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8691   }
8692
8693   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8694 }
8695
8696 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8697   LLVMContext *Context = DAG.getContext();
8698   SDValue Op0 = Op.getOperand(0);
8699   SDValue Op1 = Op.getOperand(1);
8700   DebugLoc dl = Op.getDebugLoc();
8701   MVT VT = Op.getValueType().getSimpleVT();
8702   MVT SrcVT = Op1.getValueType().getSimpleVT();
8703
8704   // If second operand is smaller, extend it first.
8705   if (SrcVT.bitsLT(VT)) {
8706     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8707     SrcVT = VT;
8708   }
8709   // And if it is bigger, shrink it first.
8710   if (SrcVT.bitsGT(VT)) {
8711     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8712     SrcVT = VT;
8713   }
8714
8715   // At this point the operands and the result should have the same
8716   // type, and that won't be f80 since that is not custom lowered.
8717
8718   // First get the sign bit of second operand.
8719   SmallVector<Constant*,4> CV;
8720   if (SrcVT == MVT::f64) {
8721     const fltSemantics &Sem = APFloat::IEEEdouble;
8722     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8723     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8724   } else {
8725     const fltSemantics &Sem = APFloat::IEEEsingle;
8726     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8727     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8728     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8729     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8730   }
8731   Constant *C = ConstantVector::get(CV);
8732   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8733   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8734                               MachinePointerInfo::getConstantPool(),
8735                               false, false, false, 16);
8736   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8737
8738   // Shift sign bit right or left if the two operands have different types.
8739   if (SrcVT.bitsGT(VT)) {
8740     // Op0 is MVT::f32, Op1 is MVT::f64.
8741     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8742     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8743                           DAG.getConstant(32, MVT::i32));
8744     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8745     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8746                           DAG.getIntPtrConstant(0));
8747   }
8748
8749   // Clear first operand sign bit.
8750   CV.clear();
8751   if (VT == MVT::f64) {
8752     const fltSemantics &Sem = APFloat::IEEEdouble;
8753     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8754                                                    APInt(64, ~(1ULL << 63)))));
8755     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8756   } else {
8757     const fltSemantics &Sem = APFloat::IEEEsingle;
8758     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8759                                                    APInt(32, ~(1U << 31)))));
8760     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8761     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8762     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8763   }
8764   C = ConstantVector::get(CV);
8765   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8766   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8767                               MachinePointerInfo::getConstantPool(),
8768                               false, false, false, 16);
8769   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8770
8771   // Or the value with the sign bit.
8772   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8773 }
8774
8775 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8776   SDValue N0 = Op.getOperand(0);
8777   DebugLoc dl = Op.getDebugLoc();
8778   MVT VT = Op.getValueType().getSimpleVT();
8779
8780   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8781   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8782                                   DAG.getConstant(1, VT));
8783   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8784 }
8785
8786 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8787 //
8788 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8789                                                   SelectionDAG &DAG) const {
8790   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8791
8792   if (!Subtarget->hasSSE41())
8793     return SDValue();
8794
8795   if (!Op->hasOneUse())
8796     return SDValue();
8797
8798   SDNode *N = Op.getNode();
8799   DebugLoc DL = N->getDebugLoc();
8800
8801   SmallVector<SDValue, 8> Opnds;
8802   DenseMap<SDValue, unsigned> VecInMap;
8803   EVT VT = MVT::Other;
8804
8805   // Recognize a special case where a vector is casted into wide integer to
8806   // test all 0s.
8807   Opnds.push_back(N->getOperand(0));
8808   Opnds.push_back(N->getOperand(1));
8809
8810   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8811     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8812     // BFS traverse all OR'd operands.
8813     if (I->getOpcode() == ISD::OR) {
8814       Opnds.push_back(I->getOperand(0));
8815       Opnds.push_back(I->getOperand(1));
8816       // Re-evaluate the number of nodes to be traversed.
8817       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8818       continue;
8819     }
8820
8821     // Quit if a non-EXTRACT_VECTOR_ELT
8822     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8823       return SDValue();
8824
8825     // Quit if without a constant index.
8826     SDValue Idx = I->getOperand(1);
8827     if (!isa<ConstantSDNode>(Idx))
8828       return SDValue();
8829
8830     SDValue ExtractedFromVec = I->getOperand(0);
8831     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8832     if (M == VecInMap.end()) {
8833       VT = ExtractedFromVec.getValueType();
8834       // Quit if not 128/256-bit vector.
8835       if (!VT.is128BitVector() && !VT.is256BitVector())
8836         return SDValue();
8837       // Quit if not the same type.
8838       if (VecInMap.begin() != VecInMap.end() &&
8839           VT != VecInMap.begin()->first.getValueType())
8840         return SDValue();
8841       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8842     }
8843     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8844   }
8845
8846   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8847          "Not extracted from 128-/256-bit vector.");
8848
8849   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8850   SmallVector<SDValue, 8> VecIns;
8851
8852   for (DenseMap<SDValue, unsigned>::const_iterator
8853         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8854     // Quit if not all elements are used.
8855     if (I->second != FullMask)
8856       return SDValue();
8857     VecIns.push_back(I->first);
8858   }
8859
8860   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8861
8862   // Cast all vectors into TestVT for PTEST.
8863   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8864     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8865
8866   // If more than one full vectors are evaluated, OR them first before PTEST.
8867   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8868     // Each iteration will OR 2 nodes and append the result until there is only
8869     // 1 node left, i.e. the final OR'd value of all vectors.
8870     SDValue LHS = VecIns[Slot];
8871     SDValue RHS = VecIns[Slot + 1];
8872     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8873   }
8874
8875   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8876                      VecIns.back(), VecIns.back());
8877 }
8878
8879 /// Emit nodes that will be selected as "test Op0,Op0", or something
8880 /// equivalent.
8881 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8882                                     SelectionDAG &DAG) const {
8883   DebugLoc dl = Op.getDebugLoc();
8884
8885   // CF and OF aren't always set the way we want. Determine which
8886   // of these we need.
8887   bool NeedCF = false;
8888   bool NeedOF = false;
8889   switch (X86CC) {
8890   default: break;
8891   case X86::COND_A: case X86::COND_AE:
8892   case X86::COND_B: case X86::COND_BE:
8893     NeedCF = true;
8894     break;
8895   case X86::COND_G: case X86::COND_GE:
8896   case X86::COND_L: case X86::COND_LE:
8897   case X86::COND_O: case X86::COND_NO:
8898     NeedOF = true;
8899     break;
8900   }
8901
8902   // See if we can use the EFLAGS value from the operand instead of
8903   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8904   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8905   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8906     // Emit a CMP with 0, which is the TEST pattern.
8907     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8908                        DAG.getConstant(0, Op.getValueType()));
8909
8910   unsigned Opcode = 0;
8911   unsigned NumOperands = 0;
8912
8913   // Truncate operations may prevent the merge of the SETCC instruction
8914   // and the arithmetic intruction before it. Attempt to truncate the operands
8915   // of the arithmetic instruction and use a reduced bit-width instruction.
8916   bool NeedTruncation = false;
8917   SDValue ArithOp = Op;
8918   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8919     SDValue Arith = Op->getOperand(0);
8920     // Both the trunc and the arithmetic op need to have one user each.
8921     if (Arith->hasOneUse())
8922       switch (Arith.getOpcode()) {
8923         default: break;
8924         case ISD::ADD:
8925         case ISD::SUB:
8926         case ISD::AND:
8927         case ISD::OR:
8928         case ISD::XOR: {
8929           NeedTruncation = true;
8930           ArithOp = Arith;
8931         }
8932       }
8933   }
8934
8935   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8936   // which may be the result of a CAST.  We use the variable 'Op', which is the
8937   // non-casted variable when we check for possible users.
8938   switch (ArithOp.getOpcode()) {
8939   case ISD::ADD:
8940     // Due to an isel shortcoming, be conservative if this add is likely to be
8941     // selected as part of a load-modify-store instruction. When the root node
8942     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8943     // uses of other nodes in the match, such as the ADD in this case. This
8944     // leads to the ADD being left around and reselected, with the result being
8945     // two adds in the output.  Alas, even if none our users are stores, that
8946     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8947     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8948     // climbing the DAG back to the root, and it doesn't seem to be worth the
8949     // effort.
8950     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8951          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8952       if (UI->getOpcode() != ISD::CopyToReg &&
8953           UI->getOpcode() != ISD::SETCC &&
8954           UI->getOpcode() != ISD::STORE)
8955         goto default_case;
8956
8957     if (ConstantSDNode *C =
8958         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8959       // An add of one will be selected as an INC.
8960       if (C->getAPIntValue() == 1) {
8961         Opcode = X86ISD::INC;
8962         NumOperands = 1;
8963         break;
8964       }
8965
8966       // An add of negative one (subtract of one) will be selected as a DEC.
8967       if (C->getAPIntValue().isAllOnesValue()) {
8968         Opcode = X86ISD::DEC;
8969         NumOperands = 1;
8970         break;
8971       }
8972     }
8973
8974     // Otherwise use a regular EFLAGS-setting add.
8975     Opcode = X86ISD::ADD;
8976     NumOperands = 2;
8977     break;
8978   case ISD::AND: {
8979     // If the primary and result isn't used, don't bother using X86ISD::AND,
8980     // because a TEST instruction will be better.
8981     bool NonFlagUse = false;
8982     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8983            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8984       SDNode *User = *UI;
8985       unsigned UOpNo = UI.getOperandNo();
8986       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8987         // Look pass truncate.
8988         UOpNo = User->use_begin().getOperandNo();
8989         User = *User->use_begin();
8990       }
8991
8992       if (User->getOpcode() != ISD::BRCOND &&
8993           User->getOpcode() != ISD::SETCC &&
8994           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8995         NonFlagUse = true;
8996         break;
8997       }
8998     }
8999
9000     if (!NonFlagUse)
9001       break;
9002   }
9003     // FALL THROUGH
9004   case ISD::SUB:
9005   case ISD::OR:
9006   case ISD::XOR:
9007     // Due to the ISEL shortcoming noted above, be conservative if this op is
9008     // likely to be selected as part of a load-modify-store instruction.
9009     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9010            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9011       if (UI->getOpcode() == ISD::STORE)
9012         goto default_case;
9013
9014     // Otherwise use a regular EFLAGS-setting instruction.
9015     switch (ArithOp.getOpcode()) {
9016     default: llvm_unreachable("unexpected operator!");
9017     case ISD::SUB: Opcode = X86ISD::SUB; break;
9018     case ISD::XOR: Opcode = X86ISD::XOR; break;
9019     case ISD::AND: Opcode = X86ISD::AND; break;
9020     case ISD::OR: {
9021       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9022         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9023         if (EFLAGS.getNode())
9024           return EFLAGS;
9025       }
9026       Opcode = X86ISD::OR;
9027       break;
9028     }
9029     }
9030
9031     NumOperands = 2;
9032     break;
9033   case X86ISD::ADD:
9034   case X86ISD::SUB:
9035   case X86ISD::INC:
9036   case X86ISD::DEC:
9037   case X86ISD::OR:
9038   case X86ISD::XOR:
9039   case X86ISD::AND:
9040     return SDValue(Op.getNode(), 1);
9041   default:
9042   default_case:
9043     break;
9044   }
9045
9046   // If we found that truncation is beneficial, perform the truncation and
9047   // update 'Op'.
9048   if (NeedTruncation) {
9049     EVT VT = Op.getValueType();
9050     SDValue WideVal = Op->getOperand(0);
9051     EVT WideVT = WideVal.getValueType();
9052     unsigned ConvertedOp = 0;
9053     // Use a target machine opcode to prevent further DAGCombine
9054     // optimizations that may separate the arithmetic operations
9055     // from the setcc node.
9056     switch (WideVal.getOpcode()) {
9057       default: break;
9058       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9059       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9060       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9061       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9062       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9063     }
9064
9065     if (ConvertedOp) {
9066       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9067       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9068         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9069         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9070         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9071       }
9072     }
9073   }
9074
9075   if (Opcode == 0)
9076     // Emit a CMP with 0, which is the TEST pattern.
9077     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9078                        DAG.getConstant(0, Op.getValueType()));
9079
9080   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9081   SmallVector<SDValue, 4> Ops;
9082   for (unsigned i = 0; i != NumOperands; ++i)
9083     Ops.push_back(Op.getOperand(i));
9084
9085   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9086   DAG.ReplaceAllUsesWith(Op, New);
9087   return SDValue(New.getNode(), 1);
9088 }
9089
9090 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9091 /// equivalent.
9092 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9093                                    SelectionDAG &DAG) const {
9094   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9095     if (C->getAPIntValue() == 0)
9096       return EmitTest(Op0, X86CC, DAG);
9097
9098   DebugLoc dl = Op0.getDebugLoc();
9099   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9100        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9101     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9102     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9103     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9104                               Op0, Op1);
9105     return SDValue(Sub.getNode(), 1);
9106   }
9107   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9108 }
9109
9110 /// Convert a comparison if required by the subtarget.
9111 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9112                                                  SelectionDAG &DAG) const {
9113   // If the subtarget does not support the FUCOMI instruction, floating-point
9114   // comparisons have to be converted.
9115   if (Subtarget->hasCMov() ||
9116       Cmp.getOpcode() != X86ISD::CMP ||
9117       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9118       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9119     return Cmp;
9120
9121   // The instruction selector will select an FUCOM instruction instead of
9122   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9123   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9124   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9125   DebugLoc dl = Cmp.getDebugLoc();
9126   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9127   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9128   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9129                             DAG.getConstant(8, MVT::i8));
9130   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9131   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9132 }
9133
9134 static bool isAllOnes(SDValue V) {
9135   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9136   return C && C->isAllOnesValue();
9137 }
9138
9139 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9140 /// if it's possible.
9141 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9142                                      DebugLoc dl, SelectionDAG &DAG) const {
9143   SDValue Op0 = And.getOperand(0);
9144   SDValue Op1 = And.getOperand(1);
9145   if (Op0.getOpcode() == ISD::TRUNCATE)
9146     Op0 = Op0.getOperand(0);
9147   if (Op1.getOpcode() == ISD::TRUNCATE)
9148     Op1 = Op1.getOperand(0);
9149
9150   SDValue LHS, RHS;
9151   if (Op1.getOpcode() == ISD::SHL)
9152     std::swap(Op0, Op1);
9153   if (Op0.getOpcode() == ISD::SHL) {
9154     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9155       if (And00C->getZExtValue() == 1) {
9156         // If we looked past a truncate, check that it's only truncating away
9157         // known zeros.
9158         unsigned BitWidth = Op0.getValueSizeInBits();
9159         unsigned AndBitWidth = And.getValueSizeInBits();
9160         if (BitWidth > AndBitWidth) {
9161           APInt Zeros, Ones;
9162           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9163           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9164             return SDValue();
9165         }
9166         LHS = Op1;
9167         RHS = Op0.getOperand(1);
9168       }
9169   } else if (Op1.getOpcode() == ISD::Constant) {
9170     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9171     uint64_t AndRHSVal = AndRHS->getZExtValue();
9172     SDValue AndLHS = Op0;
9173
9174     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9175       LHS = AndLHS.getOperand(0);
9176       RHS = AndLHS.getOperand(1);
9177     }
9178
9179     // Use BT if the immediate can't be encoded in a TEST instruction.
9180     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9181       LHS = AndLHS;
9182       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9183     }
9184   }
9185
9186   if (LHS.getNode()) {
9187     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9188     // instruction.  Since the shift amount is in-range-or-undefined, we know
9189     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9190     // the encoding for the i16 version is larger than the i32 version.
9191     // Also promote i16 to i32 for performance / code size reason.
9192     if (LHS.getValueType() == MVT::i8 ||
9193         LHS.getValueType() == MVT::i16)
9194       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9195
9196     // If the operand types disagree, extend the shift amount to match.  Since
9197     // BT ignores high bits (like shifts) we can use anyextend.
9198     if (LHS.getValueType() != RHS.getValueType())
9199       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9200
9201     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9202     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9203     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9204                        DAG.getConstant(Cond, MVT::i8), BT);
9205   }
9206
9207   return SDValue();
9208 }
9209
9210 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9211 // ones, and then concatenate the result back.
9212 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9213   MVT VT = Op.getValueType().getSimpleVT();
9214
9215   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9216          "Unsupported value type for operation");
9217
9218   unsigned NumElems = VT.getVectorNumElements();
9219   DebugLoc dl = Op.getDebugLoc();
9220   SDValue CC = Op.getOperand(2);
9221
9222   // Extract the LHS vectors
9223   SDValue LHS = Op.getOperand(0);
9224   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9225   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9226
9227   // Extract the RHS vectors
9228   SDValue RHS = Op.getOperand(1);
9229   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9230   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9231
9232   // Issue the operation on the smaller types and concatenate the result back
9233   MVT EltVT = VT.getVectorElementType();
9234   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9235   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9236                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9237                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9238 }
9239
9240 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9241                            SelectionDAG &DAG) {
9242   SDValue Cond;
9243   SDValue Op0 = Op.getOperand(0);
9244   SDValue Op1 = Op.getOperand(1);
9245   SDValue CC = Op.getOperand(2);
9246   MVT VT = Op.getValueType().getSimpleVT();
9247   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9248   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9249   DebugLoc dl = Op.getDebugLoc();
9250
9251   if (isFP) {
9252 #ifndef NDEBUG
9253     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9254     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9255 #endif
9256
9257     unsigned SSECC;
9258     bool Swap = false;
9259
9260     // SSE Condition code mapping:
9261     //  0 - EQ
9262     //  1 - LT
9263     //  2 - LE
9264     //  3 - UNORD
9265     //  4 - NEQ
9266     //  5 - NLT
9267     //  6 - NLE
9268     //  7 - ORD
9269     switch (SetCCOpcode) {
9270     default: llvm_unreachable("Unexpected SETCC condition");
9271     case ISD::SETOEQ:
9272     case ISD::SETEQ:  SSECC = 0; break;
9273     case ISD::SETOGT:
9274     case ISD::SETGT: Swap = true; // Fallthrough
9275     case ISD::SETLT:
9276     case ISD::SETOLT: SSECC = 1; break;
9277     case ISD::SETOGE:
9278     case ISD::SETGE: Swap = true; // Fallthrough
9279     case ISD::SETLE:
9280     case ISD::SETOLE: SSECC = 2; break;
9281     case ISD::SETUO:  SSECC = 3; break;
9282     case ISD::SETUNE:
9283     case ISD::SETNE:  SSECC = 4; break;
9284     case ISD::SETULE: Swap = true; // Fallthrough
9285     case ISD::SETUGE: SSECC = 5; break;
9286     case ISD::SETULT: Swap = true; // Fallthrough
9287     case ISD::SETUGT: SSECC = 6; break;
9288     case ISD::SETO:   SSECC = 7; break;
9289     case ISD::SETUEQ:
9290     case ISD::SETONE: SSECC = 8; break;
9291     }
9292     if (Swap)
9293       std::swap(Op0, Op1);
9294
9295     // In the two special cases we can't handle, emit two comparisons.
9296     if (SSECC == 8) {
9297       unsigned CC0, CC1;
9298       unsigned CombineOpc;
9299       if (SetCCOpcode == ISD::SETUEQ) {
9300         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9301       } else {
9302         assert(SetCCOpcode == ISD::SETONE);
9303         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9304       }
9305
9306       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9307                                  DAG.getConstant(CC0, MVT::i8));
9308       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9309                                  DAG.getConstant(CC1, MVT::i8));
9310       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9311     }
9312     // Handle all other FP comparisons here.
9313     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9314                        DAG.getConstant(SSECC, MVT::i8));
9315   }
9316
9317   // Break 256-bit integer vector compare into smaller ones.
9318   if (VT.is256BitVector() && !Subtarget->hasInt256())
9319     return Lower256IntVSETCC(Op, DAG);
9320
9321   // We are handling one of the integer comparisons here.  Since SSE only has
9322   // GT and EQ comparisons for integer, swapping operands and multiple
9323   // operations may be required for some comparisons.
9324   unsigned Opc;
9325   bool Swap = false, Invert = false, FlipSigns = false;
9326
9327   switch (SetCCOpcode) {
9328   default: llvm_unreachable("Unexpected SETCC condition");
9329   case ISD::SETNE:  Invert = true;
9330   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9331   case ISD::SETLT:  Swap = true;
9332   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9333   case ISD::SETGE:  Swap = true;
9334   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9335   case ISD::SETULT: Swap = true;
9336   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9337   case ISD::SETUGE: Swap = true;
9338   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9339   }
9340   if (Swap)
9341     std::swap(Op0, Op1);
9342
9343   // Check that the operation in question is available (most are plain SSE2,
9344   // but PCMPGTQ and PCMPEQQ have different requirements).
9345   if (VT == MVT::v2i64) {
9346     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9347       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9348
9349       // First cast everything to the right type.
9350       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9351       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9352
9353       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9354       // bits of the inputs before performing those operations. The lower
9355       // compare is always unsigned.
9356       SDValue SB;
9357       if (FlipSigns) {
9358         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9359       } else {
9360         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9361         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9362         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9363                          Sign, Zero, Sign, Zero);
9364       }
9365       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9366       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9367
9368       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9369       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9370       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9371
9372       // Create masks for only the low parts/high parts of the 64 bit integers.
9373       const int MaskHi[] = { 1, 1, 3, 3 };
9374       const int MaskLo[] = { 0, 0, 2, 2 };
9375       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9376       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9377       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9378
9379       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9380       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9381
9382       if (Invert)
9383         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9384
9385       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9386     }
9387
9388     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9389       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9390       // pcmpeqd + pshufd + pand.
9391       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9392
9393       // First cast everything to the right type.
9394       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9395       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9396
9397       // Do the compare.
9398       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9399
9400       // Make sure the lower and upper halves are both all-ones.
9401       const int Mask[] = { 1, 0, 3, 2 };
9402       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9403       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9404
9405       if (Invert)
9406         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9407
9408       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9409     }
9410   }
9411
9412   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9413   // bits of the inputs before performing those operations.
9414   if (FlipSigns) {
9415     EVT EltVT = VT.getVectorElementType();
9416     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9417     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9418     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9419   }
9420
9421   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9422
9423   // If the logical-not of the result is required, perform that now.
9424   if (Invert)
9425     Result = DAG.getNOT(dl, Result, VT);
9426
9427   return Result;
9428 }
9429
9430 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9431
9432   MVT VT = Op.getValueType().getSimpleVT();
9433
9434   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9435
9436   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9437   SDValue Op0 = Op.getOperand(0);
9438   SDValue Op1 = Op.getOperand(1);
9439   DebugLoc dl = Op.getDebugLoc();
9440   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9441
9442   // Optimize to BT if possible.
9443   // Lower (X & (1 << N)) == 0 to BT(X, N).
9444   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9445   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9446   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9447       Op1.getOpcode() == ISD::Constant &&
9448       cast<ConstantSDNode>(Op1)->isNullValue() &&
9449       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9450     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9451     if (NewSetCC.getNode())
9452       return NewSetCC;
9453   }
9454
9455   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9456   // these.
9457   if (Op1.getOpcode() == ISD::Constant &&
9458       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9459        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9460       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9461
9462     // If the input is a setcc, then reuse the input setcc or use a new one with
9463     // the inverted condition.
9464     if (Op0.getOpcode() == X86ISD::SETCC) {
9465       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9466       bool Invert = (CC == ISD::SETNE) ^
9467         cast<ConstantSDNode>(Op1)->isNullValue();
9468       if (!Invert) return Op0;
9469
9470       CCode = X86::GetOppositeBranchCondition(CCode);
9471       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9472                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9473     }
9474   }
9475
9476   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9477   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9478   if (X86CC == X86::COND_INVALID)
9479     return SDValue();
9480
9481   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9482   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9483   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9484                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9485 }
9486
9487 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9488 static bool isX86LogicalCmp(SDValue Op) {
9489   unsigned Opc = Op.getNode()->getOpcode();
9490   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9491       Opc == X86ISD::SAHF)
9492     return true;
9493   if (Op.getResNo() == 1 &&
9494       (Opc == X86ISD::ADD ||
9495        Opc == X86ISD::SUB ||
9496        Opc == X86ISD::ADC ||
9497        Opc == X86ISD::SBB ||
9498        Opc == X86ISD::SMUL ||
9499        Opc == X86ISD::UMUL ||
9500        Opc == X86ISD::INC ||
9501        Opc == X86ISD::DEC ||
9502        Opc == X86ISD::OR ||
9503        Opc == X86ISD::XOR ||
9504        Opc == X86ISD::AND))
9505     return true;
9506
9507   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9508     return true;
9509
9510   return false;
9511 }
9512
9513 static bool isZero(SDValue V) {
9514   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9515   return C && C->isNullValue();
9516 }
9517
9518 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9519   if (V.getOpcode() != ISD::TRUNCATE)
9520     return false;
9521
9522   SDValue VOp0 = V.getOperand(0);
9523   unsigned InBits = VOp0.getValueSizeInBits();
9524   unsigned Bits = V.getValueSizeInBits();
9525   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9526 }
9527
9528 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9529   bool addTest = true;
9530   SDValue Cond  = Op.getOperand(0);
9531   SDValue Op1 = Op.getOperand(1);
9532   SDValue Op2 = Op.getOperand(2);
9533   DebugLoc DL = Op.getDebugLoc();
9534   SDValue CC;
9535
9536   if (Cond.getOpcode() == ISD::SETCC) {
9537     SDValue NewCond = LowerSETCC(Cond, DAG);
9538     if (NewCond.getNode())
9539       Cond = NewCond;
9540   }
9541
9542   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9543   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9544   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9545   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9546   if (Cond.getOpcode() == X86ISD::SETCC &&
9547       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9548       isZero(Cond.getOperand(1).getOperand(1))) {
9549     SDValue Cmp = Cond.getOperand(1);
9550
9551     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9552
9553     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9554         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9555       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9556
9557       SDValue CmpOp0 = Cmp.getOperand(0);
9558       // Apply further optimizations for special cases
9559       // (select (x != 0), -1, 0) -> neg & sbb
9560       // (select (x == 0), 0, -1) -> neg & sbb
9561       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9562         if (YC->isNullValue() &&
9563             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9564           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9565           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9566                                     DAG.getConstant(0, CmpOp0.getValueType()),
9567                                     CmpOp0);
9568           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9569                                     DAG.getConstant(X86::COND_B, MVT::i8),
9570                                     SDValue(Neg.getNode(), 1));
9571           return Res;
9572         }
9573
9574       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9575                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9576       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9577
9578       SDValue Res =   // Res = 0 or -1.
9579         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9580                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9581
9582       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9583         Res = DAG.getNOT(DL, Res, Res.getValueType());
9584
9585       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9586       if (N2C == 0 || !N2C->isNullValue())
9587         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9588       return Res;
9589     }
9590   }
9591
9592   // Look past (and (setcc_carry (cmp ...)), 1).
9593   if (Cond.getOpcode() == ISD::AND &&
9594       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9595     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9596     if (C && C->getAPIntValue() == 1)
9597       Cond = Cond.getOperand(0);
9598   }
9599
9600   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9601   // setting operand in place of the X86ISD::SETCC.
9602   unsigned CondOpcode = Cond.getOpcode();
9603   if (CondOpcode == X86ISD::SETCC ||
9604       CondOpcode == X86ISD::SETCC_CARRY) {
9605     CC = Cond.getOperand(0);
9606
9607     SDValue Cmp = Cond.getOperand(1);
9608     unsigned Opc = Cmp.getOpcode();
9609     MVT VT = Op.getValueType().getSimpleVT();
9610
9611     bool IllegalFPCMov = false;
9612     if (VT.isFloatingPoint() && !VT.isVector() &&
9613         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9614       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9615
9616     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9617         Opc == X86ISD::BT) { // FIXME
9618       Cond = Cmp;
9619       addTest = false;
9620     }
9621   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9622              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9623              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9624               Cond.getOperand(0).getValueType() != MVT::i8)) {
9625     SDValue LHS = Cond.getOperand(0);
9626     SDValue RHS = Cond.getOperand(1);
9627     unsigned X86Opcode;
9628     unsigned X86Cond;
9629     SDVTList VTs;
9630     switch (CondOpcode) {
9631     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9632     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9633     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9634     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9635     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9636     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9637     default: llvm_unreachable("unexpected overflowing operator");
9638     }
9639     if (CondOpcode == ISD::UMULO)
9640       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9641                           MVT::i32);
9642     else
9643       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9644
9645     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9646
9647     if (CondOpcode == ISD::UMULO)
9648       Cond = X86Op.getValue(2);
9649     else
9650       Cond = X86Op.getValue(1);
9651
9652     CC = DAG.getConstant(X86Cond, MVT::i8);
9653     addTest = false;
9654   }
9655
9656   if (addTest) {
9657     // Look pass the truncate if the high bits are known zero.
9658     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9659         Cond = Cond.getOperand(0);
9660
9661     // We know the result of AND is compared against zero. Try to match
9662     // it to BT.
9663     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9664       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9665       if (NewSetCC.getNode()) {
9666         CC = NewSetCC.getOperand(0);
9667         Cond = NewSetCC.getOperand(1);
9668         addTest = false;
9669       }
9670     }
9671   }
9672
9673   if (addTest) {
9674     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9675     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9676   }
9677
9678   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9679   // a <  b ?  0 : -1 -> RES = setcc_carry
9680   // a >= b ? -1 :  0 -> RES = setcc_carry
9681   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9682   if (Cond.getOpcode() == X86ISD::SUB) {
9683     Cond = ConvertCmpIfNecessary(Cond, DAG);
9684     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9685
9686     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9687         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9688       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9689                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9690       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9691         return DAG.getNOT(DL, Res, Res.getValueType());
9692       return Res;
9693     }
9694   }
9695
9696   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9697   // widen the cmov and push the truncate through. This avoids introducing a new
9698   // branch during isel and doesn't add any extensions.
9699   if (Op.getValueType() == MVT::i8 &&
9700       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9701     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9702     if (T1.getValueType() == T2.getValueType() &&
9703         // Blacklist CopyFromReg to avoid partial register stalls.
9704         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9705       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9706       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9707       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9708     }
9709   }
9710
9711   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9712   // condition is true.
9713   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9714   SDValue Ops[] = { Op2, Op1, CC, Cond };
9715   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9716 }
9717
9718 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9719                                             SelectionDAG &DAG) const {
9720   MVT VT = Op->getValueType(0).getSimpleVT();
9721   SDValue In = Op->getOperand(0);
9722   MVT InVT = In.getValueType().getSimpleVT();
9723   DebugLoc dl = Op->getDebugLoc();
9724
9725   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9726       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9727     return SDValue();
9728
9729   if (Subtarget->hasInt256())
9730     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9731
9732   // Optimize vectors in AVX mode
9733   // Sign extend  v8i16 to v8i32 and
9734   //              v4i32 to v4i64
9735   //
9736   // Divide input vector into two parts
9737   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9738   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9739   // concat the vectors to original VT
9740
9741   unsigned NumElems = InVT.getVectorNumElements();
9742   SDValue Undef = DAG.getUNDEF(InVT);
9743
9744   SmallVector<int,8> ShufMask1(NumElems, -1);
9745   for (unsigned i = 0; i != NumElems/2; ++i)
9746     ShufMask1[i] = i;
9747
9748   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9749
9750   SmallVector<int,8> ShufMask2(NumElems, -1);
9751   for (unsigned i = 0; i != NumElems/2; ++i)
9752     ShufMask2[i] = i + NumElems/2;
9753
9754   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9755
9756   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9757                                 VT.getVectorNumElements()/2);
9758
9759   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9760   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9761
9762   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9763 }
9764
9765 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9766 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9767 // from the AND / OR.
9768 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9769   Opc = Op.getOpcode();
9770   if (Opc != ISD::OR && Opc != ISD::AND)
9771     return false;
9772   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9773           Op.getOperand(0).hasOneUse() &&
9774           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9775           Op.getOperand(1).hasOneUse());
9776 }
9777
9778 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9779 // 1 and that the SETCC node has a single use.
9780 static bool isXor1OfSetCC(SDValue Op) {
9781   if (Op.getOpcode() != ISD::XOR)
9782     return false;
9783   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9784   if (N1C && N1C->getAPIntValue() == 1) {
9785     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9786       Op.getOperand(0).hasOneUse();
9787   }
9788   return false;
9789 }
9790
9791 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9792   bool addTest = true;
9793   SDValue Chain = Op.getOperand(0);
9794   SDValue Cond  = Op.getOperand(1);
9795   SDValue Dest  = Op.getOperand(2);
9796   DebugLoc dl = Op.getDebugLoc();
9797   SDValue CC;
9798   bool Inverted = false;
9799
9800   if (Cond.getOpcode() == ISD::SETCC) {
9801     // Check for setcc([su]{add,sub,mul}o == 0).
9802     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9803         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9804         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9805         Cond.getOperand(0).getResNo() == 1 &&
9806         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9807          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9808          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9809          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9810          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9811          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9812       Inverted = true;
9813       Cond = Cond.getOperand(0);
9814     } else {
9815       SDValue NewCond = LowerSETCC(Cond, DAG);
9816       if (NewCond.getNode())
9817         Cond = NewCond;
9818     }
9819   }
9820 #if 0
9821   // FIXME: LowerXALUO doesn't handle these!!
9822   else if (Cond.getOpcode() == X86ISD::ADD  ||
9823            Cond.getOpcode() == X86ISD::SUB  ||
9824            Cond.getOpcode() == X86ISD::SMUL ||
9825            Cond.getOpcode() == X86ISD::UMUL)
9826     Cond = LowerXALUO(Cond, DAG);
9827 #endif
9828
9829   // Look pass (and (setcc_carry (cmp ...)), 1).
9830   if (Cond.getOpcode() == ISD::AND &&
9831       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9832     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9833     if (C && C->getAPIntValue() == 1)
9834       Cond = Cond.getOperand(0);
9835   }
9836
9837   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9838   // setting operand in place of the X86ISD::SETCC.
9839   unsigned CondOpcode = Cond.getOpcode();
9840   if (CondOpcode == X86ISD::SETCC ||
9841       CondOpcode == X86ISD::SETCC_CARRY) {
9842     CC = Cond.getOperand(0);
9843
9844     SDValue Cmp = Cond.getOperand(1);
9845     unsigned Opc = Cmp.getOpcode();
9846     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9847     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9848       Cond = Cmp;
9849       addTest = false;
9850     } else {
9851       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9852       default: break;
9853       case X86::COND_O:
9854       case X86::COND_B:
9855         // These can only come from an arithmetic instruction with overflow,
9856         // e.g. SADDO, UADDO.
9857         Cond = Cond.getNode()->getOperand(1);
9858         addTest = false;
9859         break;
9860       }
9861     }
9862   }
9863   CondOpcode = Cond.getOpcode();
9864   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9865       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9866       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9867        Cond.getOperand(0).getValueType() != MVT::i8)) {
9868     SDValue LHS = Cond.getOperand(0);
9869     SDValue RHS = Cond.getOperand(1);
9870     unsigned X86Opcode;
9871     unsigned X86Cond;
9872     SDVTList VTs;
9873     switch (CondOpcode) {
9874     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9875     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9876     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9877     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9878     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9879     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9880     default: llvm_unreachable("unexpected overflowing operator");
9881     }
9882     if (Inverted)
9883       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9884     if (CondOpcode == ISD::UMULO)
9885       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9886                           MVT::i32);
9887     else
9888       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9889
9890     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9891
9892     if (CondOpcode == ISD::UMULO)
9893       Cond = X86Op.getValue(2);
9894     else
9895       Cond = X86Op.getValue(1);
9896
9897     CC = DAG.getConstant(X86Cond, MVT::i8);
9898     addTest = false;
9899   } else {
9900     unsigned CondOpc;
9901     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9902       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9903       if (CondOpc == ISD::OR) {
9904         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9905         // two branches instead of an explicit OR instruction with a
9906         // separate test.
9907         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9908             isX86LogicalCmp(Cmp)) {
9909           CC = Cond.getOperand(0).getOperand(0);
9910           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9911                               Chain, Dest, CC, Cmp);
9912           CC = Cond.getOperand(1).getOperand(0);
9913           Cond = Cmp;
9914           addTest = false;
9915         }
9916       } else { // ISD::AND
9917         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9918         // two branches instead of an explicit AND instruction with a
9919         // separate test. However, we only do this if this block doesn't
9920         // have a fall-through edge, because this requires an explicit
9921         // jmp when the condition is false.
9922         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9923             isX86LogicalCmp(Cmp) &&
9924             Op.getNode()->hasOneUse()) {
9925           X86::CondCode CCode =
9926             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9927           CCode = X86::GetOppositeBranchCondition(CCode);
9928           CC = DAG.getConstant(CCode, MVT::i8);
9929           SDNode *User = *Op.getNode()->use_begin();
9930           // Look for an unconditional branch following this conditional branch.
9931           // We need this because we need to reverse the successors in order
9932           // to implement FCMP_OEQ.
9933           if (User->getOpcode() == ISD::BR) {
9934             SDValue FalseBB = User->getOperand(1);
9935             SDNode *NewBR =
9936               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9937             assert(NewBR == User);
9938             (void)NewBR;
9939             Dest = FalseBB;
9940
9941             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9942                                 Chain, Dest, CC, Cmp);
9943             X86::CondCode CCode =
9944               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9945             CCode = X86::GetOppositeBranchCondition(CCode);
9946             CC = DAG.getConstant(CCode, MVT::i8);
9947             Cond = Cmp;
9948             addTest = false;
9949           }
9950         }
9951       }
9952     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9953       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9954       // It should be transformed during dag combiner except when the condition
9955       // is set by a arithmetics with overflow node.
9956       X86::CondCode CCode =
9957         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9958       CCode = X86::GetOppositeBranchCondition(CCode);
9959       CC = DAG.getConstant(CCode, MVT::i8);
9960       Cond = Cond.getOperand(0).getOperand(1);
9961       addTest = false;
9962     } else if (Cond.getOpcode() == ISD::SETCC &&
9963                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9964       // For FCMP_OEQ, we can emit
9965       // two branches instead of an explicit AND instruction with a
9966       // separate test. However, we only do this if this block doesn't
9967       // have a fall-through edge, because this requires an explicit
9968       // jmp when the condition is false.
9969       if (Op.getNode()->hasOneUse()) {
9970         SDNode *User = *Op.getNode()->use_begin();
9971         // Look for an unconditional branch following this conditional branch.
9972         // We need this because we need to reverse the successors in order
9973         // to implement FCMP_OEQ.
9974         if (User->getOpcode() == ISD::BR) {
9975           SDValue FalseBB = User->getOperand(1);
9976           SDNode *NewBR =
9977             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9978           assert(NewBR == User);
9979           (void)NewBR;
9980           Dest = FalseBB;
9981
9982           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9983                                     Cond.getOperand(0), Cond.getOperand(1));
9984           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9985           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9986           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9987                               Chain, Dest, CC, Cmp);
9988           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9989           Cond = Cmp;
9990           addTest = false;
9991         }
9992       }
9993     } else if (Cond.getOpcode() == ISD::SETCC &&
9994                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9995       // For FCMP_UNE, we can emit
9996       // two branches instead of an explicit AND instruction with a
9997       // separate test. However, we only do this if this block doesn't
9998       // have a fall-through edge, because this requires an explicit
9999       // jmp when the condition is false.
10000       if (Op.getNode()->hasOneUse()) {
10001         SDNode *User = *Op.getNode()->use_begin();
10002         // Look for an unconditional branch following this conditional branch.
10003         // We need this because we need to reverse the successors in order
10004         // to implement FCMP_UNE.
10005         if (User->getOpcode() == ISD::BR) {
10006           SDValue FalseBB = User->getOperand(1);
10007           SDNode *NewBR =
10008             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10009           assert(NewBR == User);
10010           (void)NewBR;
10011
10012           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10013                                     Cond.getOperand(0), Cond.getOperand(1));
10014           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10015           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10016           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10017                               Chain, Dest, CC, Cmp);
10018           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10019           Cond = Cmp;
10020           addTest = false;
10021           Dest = FalseBB;
10022         }
10023       }
10024     }
10025   }
10026
10027   if (addTest) {
10028     // Look pass the truncate if the high bits are known zero.
10029     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10030         Cond = Cond.getOperand(0);
10031
10032     // We know the result of AND is compared against zero. Try to match
10033     // it to BT.
10034     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10035       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10036       if (NewSetCC.getNode()) {
10037         CC = NewSetCC.getOperand(0);
10038         Cond = NewSetCC.getOperand(1);
10039         addTest = false;
10040       }
10041     }
10042   }
10043
10044   if (addTest) {
10045     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10046     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10047   }
10048   Cond = ConvertCmpIfNecessary(Cond, DAG);
10049   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10050                      Chain, Dest, CC, Cond);
10051 }
10052
10053 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10054 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10055 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10056 // that the guard pages used by the OS virtual memory manager are allocated in
10057 // correct sequence.
10058 SDValue
10059 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10060                                            SelectionDAG &DAG) const {
10061   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10062           getTargetMachine().Options.EnableSegmentedStacks) &&
10063          "This should be used only on Windows targets or when segmented stacks "
10064          "are being used");
10065   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10066   DebugLoc dl = Op.getDebugLoc();
10067
10068   // Get the inputs.
10069   SDValue Chain = Op.getOperand(0);
10070   SDValue Size  = Op.getOperand(1);
10071   // FIXME: Ensure alignment here
10072
10073   bool Is64Bit = Subtarget->is64Bit();
10074   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10075
10076   if (getTargetMachine().Options.EnableSegmentedStacks) {
10077     MachineFunction &MF = DAG.getMachineFunction();
10078     MachineRegisterInfo &MRI = MF.getRegInfo();
10079
10080     if (Is64Bit) {
10081       // The 64 bit implementation of segmented stacks needs to clobber both r10
10082       // r11. This makes it impossible to use it along with nested parameters.
10083       const Function *F = MF.getFunction();
10084
10085       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10086            I != E; ++I)
10087         if (I->hasNestAttr())
10088           report_fatal_error("Cannot use segmented stacks with functions that "
10089                              "have nested arguments.");
10090     }
10091
10092     const TargetRegisterClass *AddrRegClass =
10093       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10094     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10095     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10096     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10097                                 DAG.getRegister(Vreg, SPTy));
10098     SDValue Ops1[2] = { Value, Chain };
10099     return DAG.getMergeValues(Ops1, 2, dl);
10100   } else {
10101     SDValue Flag;
10102     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10103
10104     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10105     Flag = Chain.getValue(1);
10106     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10107
10108     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10109     Flag = Chain.getValue(1);
10110
10111     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10112                                SPTy).getValue(1);
10113
10114     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10115     return DAG.getMergeValues(Ops1, 2, dl);
10116   }
10117 }
10118
10119 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10120   MachineFunction &MF = DAG.getMachineFunction();
10121   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10122
10123   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10124   DebugLoc DL = Op.getDebugLoc();
10125
10126   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10127     // vastart just stores the address of the VarArgsFrameIndex slot into the
10128     // memory location argument.
10129     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10130                                    getPointerTy());
10131     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10132                         MachinePointerInfo(SV), false, false, 0);
10133   }
10134
10135   // __va_list_tag:
10136   //   gp_offset         (0 - 6 * 8)
10137   //   fp_offset         (48 - 48 + 8 * 16)
10138   //   overflow_arg_area (point to parameters coming in memory).
10139   //   reg_save_area
10140   SmallVector<SDValue, 8> MemOps;
10141   SDValue FIN = Op.getOperand(1);
10142   // Store gp_offset
10143   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10144                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10145                                                MVT::i32),
10146                                FIN, MachinePointerInfo(SV), false, false, 0);
10147   MemOps.push_back(Store);
10148
10149   // Store fp_offset
10150   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10151                     FIN, DAG.getIntPtrConstant(4));
10152   Store = DAG.getStore(Op.getOperand(0), DL,
10153                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10154                                        MVT::i32),
10155                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10156   MemOps.push_back(Store);
10157
10158   // Store ptr to overflow_arg_area
10159   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10160                     FIN, DAG.getIntPtrConstant(4));
10161   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10162                                     getPointerTy());
10163   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10164                        MachinePointerInfo(SV, 8),
10165                        false, false, 0);
10166   MemOps.push_back(Store);
10167
10168   // Store ptr to reg_save_area.
10169   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10170                     FIN, DAG.getIntPtrConstant(8));
10171   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10172                                     getPointerTy());
10173   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10174                        MachinePointerInfo(SV, 16), false, false, 0);
10175   MemOps.push_back(Store);
10176   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10177                      &MemOps[0], MemOps.size());
10178 }
10179
10180 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10181   assert(Subtarget->is64Bit() &&
10182          "LowerVAARG only handles 64-bit va_arg!");
10183   assert((Subtarget->isTargetLinux() ||
10184           Subtarget->isTargetDarwin()) &&
10185           "Unhandled target in LowerVAARG");
10186   assert(Op.getNode()->getNumOperands() == 4);
10187   SDValue Chain = Op.getOperand(0);
10188   SDValue SrcPtr = Op.getOperand(1);
10189   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10190   unsigned Align = Op.getConstantOperandVal(3);
10191   DebugLoc dl = Op.getDebugLoc();
10192
10193   EVT ArgVT = Op.getNode()->getValueType(0);
10194   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10195   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10196   uint8_t ArgMode;
10197
10198   // Decide which area this value should be read from.
10199   // TODO: Implement the AMD64 ABI in its entirety. This simple
10200   // selection mechanism works only for the basic types.
10201   if (ArgVT == MVT::f80) {
10202     llvm_unreachable("va_arg for f80 not yet implemented");
10203   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10204     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10205   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10206     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10207   } else {
10208     llvm_unreachable("Unhandled argument type in LowerVAARG");
10209   }
10210
10211   if (ArgMode == 2) {
10212     // Sanity Check: Make sure using fp_offset makes sense.
10213     assert(!getTargetMachine().Options.UseSoftFloat &&
10214            !(DAG.getMachineFunction()
10215                 .getFunction()->getAttributes()
10216                 .hasAttribute(AttributeSet::FunctionIndex,
10217                               Attribute::NoImplicitFloat)) &&
10218            Subtarget->hasSSE1());
10219   }
10220
10221   // Insert VAARG_64 node into the DAG
10222   // VAARG_64 returns two values: Variable Argument Address, Chain
10223   SmallVector<SDValue, 11> InstOps;
10224   InstOps.push_back(Chain);
10225   InstOps.push_back(SrcPtr);
10226   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10227   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10228   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10229   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10230   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10231                                           VTs, &InstOps[0], InstOps.size(),
10232                                           MVT::i64,
10233                                           MachinePointerInfo(SV),
10234                                           /*Align=*/0,
10235                                           /*Volatile=*/false,
10236                                           /*ReadMem=*/true,
10237                                           /*WriteMem=*/true);
10238   Chain = VAARG.getValue(1);
10239
10240   // Load the next argument and return it
10241   return DAG.getLoad(ArgVT, dl,
10242                      Chain,
10243                      VAARG,
10244                      MachinePointerInfo(),
10245                      false, false, false, 0);
10246 }
10247
10248 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10249                            SelectionDAG &DAG) {
10250   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10251   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10252   SDValue Chain = Op.getOperand(0);
10253   SDValue DstPtr = Op.getOperand(1);
10254   SDValue SrcPtr = Op.getOperand(2);
10255   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10256   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10257   DebugLoc DL = Op.getDebugLoc();
10258
10259   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10260                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10261                        false,
10262                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10263 }
10264
10265 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10266 // may or may not be a constant. Takes immediate version of shift as input.
10267 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10268                                    SDValue SrcOp, SDValue ShAmt,
10269                                    SelectionDAG &DAG) {
10270   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10271
10272   if (isa<ConstantSDNode>(ShAmt)) {
10273     // Constant may be a TargetConstant. Use a regular constant.
10274     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10275     switch (Opc) {
10276       default: llvm_unreachable("Unknown target vector shift node");
10277       case X86ISD::VSHLI:
10278       case X86ISD::VSRLI:
10279       case X86ISD::VSRAI:
10280         return DAG.getNode(Opc, dl, VT, SrcOp,
10281                            DAG.getConstant(ShiftAmt, MVT::i32));
10282     }
10283   }
10284
10285   // Change opcode to non-immediate version
10286   switch (Opc) {
10287     default: llvm_unreachable("Unknown target vector shift node");
10288     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10289     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10290     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10291   }
10292
10293   // Need to build a vector containing shift amount
10294   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10295   SDValue ShOps[4];
10296   ShOps[0] = ShAmt;
10297   ShOps[1] = DAG.getConstant(0, MVT::i32);
10298   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10299   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10300
10301   // The return type has to be a 128-bit type with the same element
10302   // type as the input type.
10303   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10304   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10305
10306   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10307   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10308 }
10309
10310 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10311   DebugLoc dl = Op.getDebugLoc();
10312   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10313   switch (IntNo) {
10314   default: return SDValue();    // Don't custom lower most intrinsics.
10315   // Comparison intrinsics.
10316   case Intrinsic::x86_sse_comieq_ss:
10317   case Intrinsic::x86_sse_comilt_ss:
10318   case Intrinsic::x86_sse_comile_ss:
10319   case Intrinsic::x86_sse_comigt_ss:
10320   case Intrinsic::x86_sse_comige_ss:
10321   case Intrinsic::x86_sse_comineq_ss:
10322   case Intrinsic::x86_sse_ucomieq_ss:
10323   case Intrinsic::x86_sse_ucomilt_ss:
10324   case Intrinsic::x86_sse_ucomile_ss:
10325   case Intrinsic::x86_sse_ucomigt_ss:
10326   case Intrinsic::x86_sse_ucomige_ss:
10327   case Intrinsic::x86_sse_ucomineq_ss:
10328   case Intrinsic::x86_sse2_comieq_sd:
10329   case Intrinsic::x86_sse2_comilt_sd:
10330   case Intrinsic::x86_sse2_comile_sd:
10331   case Intrinsic::x86_sse2_comigt_sd:
10332   case Intrinsic::x86_sse2_comige_sd:
10333   case Intrinsic::x86_sse2_comineq_sd:
10334   case Intrinsic::x86_sse2_ucomieq_sd:
10335   case Intrinsic::x86_sse2_ucomilt_sd:
10336   case Intrinsic::x86_sse2_ucomile_sd:
10337   case Intrinsic::x86_sse2_ucomigt_sd:
10338   case Intrinsic::x86_sse2_ucomige_sd:
10339   case Intrinsic::x86_sse2_ucomineq_sd: {
10340     unsigned Opc;
10341     ISD::CondCode CC;
10342     switch (IntNo) {
10343     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10344     case Intrinsic::x86_sse_comieq_ss:
10345     case Intrinsic::x86_sse2_comieq_sd:
10346       Opc = X86ISD::COMI;
10347       CC = ISD::SETEQ;
10348       break;
10349     case Intrinsic::x86_sse_comilt_ss:
10350     case Intrinsic::x86_sse2_comilt_sd:
10351       Opc = X86ISD::COMI;
10352       CC = ISD::SETLT;
10353       break;
10354     case Intrinsic::x86_sse_comile_ss:
10355     case Intrinsic::x86_sse2_comile_sd:
10356       Opc = X86ISD::COMI;
10357       CC = ISD::SETLE;
10358       break;
10359     case Intrinsic::x86_sse_comigt_ss:
10360     case Intrinsic::x86_sse2_comigt_sd:
10361       Opc = X86ISD::COMI;
10362       CC = ISD::SETGT;
10363       break;
10364     case Intrinsic::x86_sse_comige_ss:
10365     case Intrinsic::x86_sse2_comige_sd:
10366       Opc = X86ISD::COMI;
10367       CC = ISD::SETGE;
10368       break;
10369     case Intrinsic::x86_sse_comineq_ss:
10370     case Intrinsic::x86_sse2_comineq_sd:
10371       Opc = X86ISD::COMI;
10372       CC = ISD::SETNE;
10373       break;
10374     case Intrinsic::x86_sse_ucomieq_ss:
10375     case Intrinsic::x86_sse2_ucomieq_sd:
10376       Opc = X86ISD::UCOMI;
10377       CC = ISD::SETEQ;
10378       break;
10379     case Intrinsic::x86_sse_ucomilt_ss:
10380     case Intrinsic::x86_sse2_ucomilt_sd:
10381       Opc = X86ISD::UCOMI;
10382       CC = ISD::SETLT;
10383       break;
10384     case Intrinsic::x86_sse_ucomile_ss:
10385     case Intrinsic::x86_sse2_ucomile_sd:
10386       Opc = X86ISD::UCOMI;
10387       CC = ISD::SETLE;
10388       break;
10389     case Intrinsic::x86_sse_ucomigt_ss:
10390     case Intrinsic::x86_sse2_ucomigt_sd:
10391       Opc = X86ISD::UCOMI;
10392       CC = ISD::SETGT;
10393       break;
10394     case Intrinsic::x86_sse_ucomige_ss:
10395     case Intrinsic::x86_sse2_ucomige_sd:
10396       Opc = X86ISD::UCOMI;
10397       CC = ISD::SETGE;
10398       break;
10399     case Intrinsic::x86_sse_ucomineq_ss:
10400     case Intrinsic::x86_sse2_ucomineq_sd:
10401       Opc = X86ISD::UCOMI;
10402       CC = ISD::SETNE;
10403       break;
10404     }
10405
10406     SDValue LHS = Op.getOperand(1);
10407     SDValue RHS = Op.getOperand(2);
10408     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10409     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10410     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10411     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10412                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10413     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10414   }
10415
10416   // Arithmetic intrinsics.
10417   case Intrinsic::x86_sse2_pmulu_dq:
10418   case Intrinsic::x86_avx2_pmulu_dq:
10419     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10420                        Op.getOperand(1), Op.getOperand(2));
10421
10422   // SSE2/AVX2 sub with unsigned saturation intrinsics
10423   case Intrinsic::x86_sse2_psubus_b:
10424   case Intrinsic::x86_sse2_psubus_w:
10425   case Intrinsic::x86_avx2_psubus_b:
10426   case Intrinsic::x86_avx2_psubus_w:
10427     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10428                        Op.getOperand(1), Op.getOperand(2));
10429
10430   // SSE3/AVX horizontal add/sub intrinsics
10431   case Intrinsic::x86_sse3_hadd_ps:
10432   case Intrinsic::x86_sse3_hadd_pd:
10433   case Intrinsic::x86_avx_hadd_ps_256:
10434   case Intrinsic::x86_avx_hadd_pd_256:
10435   case Intrinsic::x86_sse3_hsub_ps:
10436   case Intrinsic::x86_sse3_hsub_pd:
10437   case Intrinsic::x86_avx_hsub_ps_256:
10438   case Intrinsic::x86_avx_hsub_pd_256:
10439   case Intrinsic::x86_ssse3_phadd_w_128:
10440   case Intrinsic::x86_ssse3_phadd_d_128:
10441   case Intrinsic::x86_avx2_phadd_w:
10442   case Intrinsic::x86_avx2_phadd_d:
10443   case Intrinsic::x86_ssse3_phsub_w_128:
10444   case Intrinsic::x86_ssse3_phsub_d_128:
10445   case Intrinsic::x86_avx2_phsub_w:
10446   case Intrinsic::x86_avx2_phsub_d: {
10447     unsigned Opcode;
10448     switch (IntNo) {
10449     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10450     case Intrinsic::x86_sse3_hadd_ps:
10451     case Intrinsic::x86_sse3_hadd_pd:
10452     case Intrinsic::x86_avx_hadd_ps_256:
10453     case Intrinsic::x86_avx_hadd_pd_256:
10454       Opcode = X86ISD::FHADD;
10455       break;
10456     case Intrinsic::x86_sse3_hsub_ps:
10457     case Intrinsic::x86_sse3_hsub_pd:
10458     case Intrinsic::x86_avx_hsub_ps_256:
10459     case Intrinsic::x86_avx_hsub_pd_256:
10460       Opcode = X86ISD::FHSUB;
10461       break;
10462     case Intrinsic::x86_ssse3_phadd_w_128:
10463     case Intrinsic::x86_ssse3_phadd_d_128:
10464     case Intrinsic::x86_avx2_phadd_w:
10465     case Intrinsic::x86_avx2_phadd_d:
10466       Opcode = X86ISD::HADD;
10467       break;
10468     case Intrinsic::x86_ssse3_phsub_w_128:
10469     case Intrinsic::x86_ssse3_phsub_d_128:
10470     case Intrinsic::x86_avx2_phsub_w:
10471     case Intrinsic::x86_avx2_phsub_d:
10472       Opcode = X86ISD::HSUB;
10473       break;
10474     }
10475     return DAG.getNode(Opcode, dl, Op.getValueType(),
10476                        Op.getOperand(1), Op.getOperand(2));
10477   }
10478
10479   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10480   case Intrinsic::x86_sse2_pmaxu_b:
10481   case Intrinsic::x86_sse41_pmaxuw:
10482   case Intrinsic::x86_sse41_pmaxud:
10483   case Intrinsic::x86_avx2_pmaxu_b:
10484   case Intrinsic::x86_avx2_pmaxu_w:
10485   case Intrinsic::x86_avx2_pmaxu_d:
10486   case Intrinsic::x86_sse2_pminu_b:
10487   case Intrinsic::x86_sse41_pminuw:
10488   case Intrinsic::x86_sse41_pminud:
10489   case Intrinsic::x86_avx2_pminu_b:
10490   case Intrinsic::x86_avx2_pminu_w:
10491   case Intrinsic::x86_avx2_pminu_d:
10492   case Intrinsic::x86_sse41_pmaxsb:
10493   case Intrinsic::x86_sse2_pmaxs_w:
10494   case Intrinsic::x86_sse41_pmaxsd:
10495   case Intrinsic::x86_avx2_pmaxs_b:
10496   case Intrinsic::x86_avx2_pmaxs_w:
10497   case Intrinsic::x86_avx2_pmaxs_d:
10498   case Intrinsic::x86_sse41_pminsb:
10499   case Intrinsic::x86_sse2_pmins_w:
10500   case Intrinsic::x86_sse41_pminsd:
10501   case Intrinsic::x86_avx2_pmins_b:
10502   case Intrinsic::x86_avx2_pmins_w:
10503   case Intrinsic::x86_avx2_pmins_d: {
10504     unsigned Opcode;
10505     switch (IntNo) {
10506     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10507     case Intrinsic::x86_sse2_pmaxu_b:
10508     case Intrinsic::x86_sse41_pmaxuw:
10509     case Intrinsic::x86_sse41_pmaxud:
10510     case Intrinsic::x86_avx2_pmaxu_b:
10511     case Intrinsic::x86_avx2_pmaxu_w:
10512     case Intrinsic::x86_avx2_pmaxu_d:
10513       Opcode = X86ISD::UMAX;
10514       break;
10515     case Intrinsic::x86_sse2_pminu_b:
10516     case Intrinsic::x86_sse41_pminuw:
10517     case Intrinsic::x86_sse41_pminud:
10518     case Intrinsic::x86_avx2_pminu_b:
10519     case Intrinsic::x86_avx2_pminu_w:
10520     case Intrinsic::x86_avx2_pminu_d:
10521       Opcode = X86ISD::UMIN;
10522       break;
10523     case Intrinsic::x86_sse41_pmaxsb:
10524     case Intrinsic::x86_sse2_pmaxs_w:
10525     case Intrinsic::x86_sse41_pmaxsd:
10526     case Intrinsic::x86_avx2_pmaxs_b:
10527     case Intrinsic::x86_avx2_pmaxs_w:
10528     case Intrinsic::x86_avx2_pmaxs_d:
10529       Opcode = X86ISD::SMAX;
10530       break;
10531     case Intrinsic::x86_sse41_pminsb:
10532     case Intrinsic::x86_sse2_pmins_w:
10533     case Intrinsic::x86_sse41_pminsd:
10534     case Intrinsic::x86_avx2_pmins_b:
10535     case Intrinsic::x86_avx2_pmins_w:
10536     case Intrinsic::x86_avx2_pmins_d:
10537       Opcode = X86ISD::SMIN;
10538       break;
10539     }
10540     return DAG.getNode(Opcode, dl, Op.getValueType(),
10541                        Op.getOperand(1), Op.getOperand(2));
10542   }
10543
10544   // SSE/SSE2/AVX floating point max/min intrinsics.
10545   case Intrinsic::x86_sse_max_ps:
10546   case Intrinsic::x86_sse2_max_pd:
10547   case Intrinsic::x86_avx_max_ps_256:
10548   case Intrinsic::x86_avx_max_pd_256:
10549   case Intrinsic::x86_sse_min_ps:
10550   case Intrinsic::x86_sse2_min_pd:
10551   case Intrinsic::x86_avx_min_ps_256:
10552   case Intrinsic::x86_avx_min_pd_256: {
10553     unsigned Opcode;
10554     switch (IntNo) {
10555     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10556     case Intrinsic::x86_sse_max_ps:
10557     case Intrinsic::x86_sse2_max_pd:
10558     case Intrinsic::x86_avx_max_ps_256:
10559     case Intrinsic::x86_avx_max_pd_256:
10560       Opcode = X86ISD::FMAX;
10561       break;
10562     case Intrinsic::x86_sse_min_ps:
10563     case Intrinsic::x86_sse2_min_pd:
10564     case Intrinsic::x86_avx_min_ps_256:
10565     case Intrinsic::x86_avx_min_pd_256:
10566       Opcode = X86ISD::FMIN;
10567       break;
10568     }
10569     return DAG.getNode(Opcode, dl, Op.getValueType(),
10570                        Op.getOperand(1), Op.getOperand(2));
10571   }
10572
10573   // AVX2 variable shift intrinsics
10574   case Intrinsic::x86_avx2_psllv_d:
10575   case Intrinsic::x86_avx2_psllv_q:
10576   case Intrinsic::x86_avx2_psllv_d_256:
10577   case Intrinsic::x86_avx2_psllv_q_256:
10578   case Intrinsic::x86_avx2_psrlv_d:
10579   case Intrinsic::x86_avx2_psrlv_q:
10580   case Intrinsic::x86_avx2_psrlv_d_256:
10581   case Intrinsic::x86_avx2_psrlv_q_256:
10582   case Intrinsic::x86_avx2_psrav_d:
10583   case Intrinsic::x86_avx2_psrav_d_256: {
10584     unsigned Opcode;
10585     switch (IntNo) {
10586     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10587     case Intrinsic::x86_avx2_psllv_d:
10588     case Intrinsic::x86_avx2_psllv_q:
10589     case Intrinsic::x86_avx2_psllv_d_256:
10590     case Intrinsic::x86_avx2_psllv_q_256:
10591       Opcode = ISD::SHL;
10592       break;
10593     case Intrinsic::x86_avx2_psrlv_d:
10594     case Intrinsic::x86_avx2_psrlv_q:
10595     case Intrinsic::x86_avx2_psrlv_d_256:
10596     case Intrinsic::x86_avx2_psrlv_q_256:
10597       Opcode = ISD::SRL;
10598       break;
10599     case Intrinsic::x86_avx2_psrav_d:
10600     case Intrinsic::x86_avx2_psrav_d_256:
10601       Opcode = ISD::SRA;
10602       break;
10603     }
10604     return DAG.getNode(Opcode, dl, Op.getValueType(),
10605                        Op.getOperand(1), Op.getOperand(2));
10606   }
10607
10608   case Intrinsic::x86_ssse3_pshuf_b_128:
10609   case Intrinsic::x86_avx2_pshuf_b:
10610     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10611                        Op.getOperand(1), Op.getOperand(2));
10612
10613   case Intrinsic::x86_ssse3_psign_b_128:
10614   case Intrinsic::x86_ssse3_psign_w_128:
10615   case Intrinsic::x86_ssse3_psign_d_128:
10616   case Intrinsic::x86_avx2_psign_b:
10617   case Intrinsic::x86_avx2_psign_w:
10618   case Intrinsic::x86_avx2_psign_d:
10619     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10620                        Op.getOperand(1), Op.getOperand(2));
10621
10622   case Intrinsic::x86_sse41_insertps:
10623     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10624                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10625
10626   case Intrinsic::x86_avx_vperm2f128_ps_256:
10627   case Intrinsic::x86_avx_vperm2f128_pd_256:
10628   case Intrinsic::x86_avx_vperm2f128_si_256:
10629   case Intrinsic::x86_avx2_vperm2i128:
10630     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10631                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10632
10633   case Intrinsic::x86_avx2_permd:
10634   case Intrinsic::x86_avx2_permps:
10635     // Operands intentionally swapped. Mask is last operand to intrinsic,
10636     // but second operand for node/intruction.
10637     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10638                        Op.getOperand(2), Op.getOperand(1));
10639
10640   case Intrinsic::x86_sse_sqrt_ps:
10641   case Intrinsic::x86_sse2_sqrt_pd:
10642   case Intrinsic::x86_avx_sqrt_ps_256:
10643   case Intrinsic::x86_avx_sqrt_pd_256:
10644     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10645
10646   // ptest and testp intrinsics. The intrinsic these come from are designed to
10647   // return an integer value, not just an instruction so lower it to the ptest
10648   // or testp pattern and a setcc for the result.
10649   case Intrinsic::x86_sse41_ptestz:
10650   case Intrinsic::x86_sse41_ptestc:
10651   case Intrinsic::x86_sse41_ptestnzc:
10652   case Intrinsic::x86_avx_ptestz_256:
10653   case Intrinsic::x86_avx_ptestc_256:
10654   case Intrinsic::x86_avx_ptestnzc_256:
10655   case Intrinsic::x86_avx_vtestz_ps:
10656   case Intrinsic::x86_avx_vtestc_ps:
10657   case Intrinsic::x86_avx_vtestnzc_ps:
10658   case Intrinsic::x86_avx_vtestz_pd:
10659   case Intrinsic::x86_avx_vtestc_pd:
10660   case Intrinsic::x86_avx_vtestnzc_pd:
10661   case Intrinsic::x86_avx_vtestz_ps_256:
10662   case Intrinsic::x86_avx_vtestc_ps_256:
10663   case Intrinsic::x86_avx_vtestnzc_ps_256:
10664   case Intrinsic::x86_avx_vtestz_pd_256:
10665   case Intrinsic::x86_avx_vtestc_pd_256:
10666   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10667     bool IsTestPacked = false;
10668     unsigned X86CC;
10669     switch (IntNo) {
10670     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10671     case Intrinsic::x86_avx_vtestz_ps:
10672     case Intrinsic::x86_avx_vtestz_pd:
10673     case Intrinsic::x86_avx_vtestz_ps_256:
10674     case Intrinsic::x86_avx_vtestz_pd_256:
10675       IsTestPacked = true; // Fallthrough
10676     case Intrinsic::x86_sse41_ptestz:
10677     case Intrinsic::x86_avx_ptestz_256:
10678       // ZF = 1
10679       X86CC = X86::COND_E;
10680       break;
10681     case Intrinsic::x86_avx_vtestc_ps:
10682     case Intrinsic::x86_avx_vtestc_pd:
10683     case Intrinsic::x86_avx_vtestc_ps_256:
10684     case Intrinsic::x86_avx_vtestc_pd_256:
10685       IsTestPacked = true; // Fallthrough
10686     case Intrinsic::x86_sse41_ptestc:
10687     case Intrinsic::x86_avx_ptestc_256:
10688       // CF = 1
10689       X86CC = X86::COND_B;
10690       break;
10691     case Intrinsic::x86_avx_vtestnzc_ps:
10692     case Intrinsic::x86_avx_vtestnzc_pd:
10693     case Intrinsic::x86_avx_vtestnzc_ps_256:
10694     case Intrinsic::x86_avx_vtestnzc_pd_256:
10695       IsTestPacked = true; // Fallthrough
10696     case Intrinsic::x86_sse41_ptestnzc:
10697     case Intrinsic::x86_avx_ptestnzc_256:
10698       // ZF and CF = 0
10699       X86CC = X86::COND_A;
10700       break;
10701     }
10702
10703     SDValue LHS = Op.getOperand(1);
10704     SDValue RHS = Op.getOperand(2);
10705     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10706     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10707     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10708     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10709     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10710   }
10711
10712   // SSE/AVX shift intrinsics
10713   case Intrinsic::x86_sse2_psll_w:
10714   case Intrinsic::x86_sse2_psll_d:
10715   case Intrinsic::x86_sse2_psll_q:
10716   case Intrinsic::x86_avx2_psll_w:
10717   case Intrinsic::x86_avx2_psll_d:
10718   case Intrinsic::x86_avx2_psll_q:
10719   case Intrinsic::x86_sse2_psrl_w:
10720   case Intrinsic::x86_sse2_psrl_d:
10721   case Intrinsic::x86_sse2_psrl_q:
10722   case Intrinsic::x86_avx2_psrl_w:
10723   case Intrinsic::x86_avx2_psrl_d:
10724   case Intrinsic::x86_avx2_psrl_q:
10725   case Intrinsic::x86_sse2_psra_w:
10726   case Intrinsic::x86_sse2_psra_d:
10727   case Intrinsic::x86_avx2_psra_w:
10728   case Intrinsic::x86_avx2_psra_d: {
10729     unsigned Opcode;
10730     switch (IntNo) {
10731     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10732     case Intrinsic::x86_sse2_psll_w:
10733     case Intrinsic::x86_sse2_psll_d:
10734     case Intrinsic::x86_sse2_psll_q:
10735     case Intrinsic::x86_avx2_psll_w:
10736     case Intrinsic::x86_avx2_psll_d:
10737     case Intrinsic::x86_avx2_psll_q:
10738       Opcode = X86ISD::VSHL;
10739       break;
10740     case Intrinsic::x86_sse2_psrl_w:
10741     case Intrinsic::x86_sse2_psrl_d:
10742     case Intrinsic::x86_sse2_psrl_q:
10743     case Intrinsic::x86_avx2_psrl_w:
10744     case Intrinsic::x86_avx2_psrl_d:
10745     case Intrinsic::x86_avx2_psrl_q:
10746       Opcode = X86ISD::VSRL;
10747       break;
10748     case Intrinsic::x86_sse2_psra_w:
10749     case Intrinsic::x86_sse2_psra_d:
10750     case Intrinsic::x86_avx2_psra_w:
10751     case Intrinsic::x86_avx2_psra_d:
10752       Opcode = X86ISD::VSRA;
10753       break;
10754     }
10755     return DAG.getNode(Opcode, dl, Op.getValueType(),
10756                        Op.getOperand(1), Op.getOperand(2));
10757   }
10758
10759   // SSE/AVX immediate shift intrinsics
10760   case Intrinsic::x86_sse2_pslli_w:
10761   case Intrinsic::x86_sse2_pslli_d:
10762   case Intrinsic::x86_sse2_pslli_q:
10763   case Intrinsic::x86_avx2_pslli_w:
10764   case Intrinsic::x86_avx2_pslli_d:
10765   case Intrinsic::x86_avx2_pslli_q:
10766   case Intrinsic::x86_sse2_psrli_w:
10767   case Intrinsic::x86_sse2_psrli_d:
10768   case Intrinsic::x86_sse2_psrli_q:
10769   case Intrinsic::x86_avx2_psrli_w:
10770   case Intrinsic::x86_avx2_psrli_d:
10771   case Intrinsic::x86_avx2_psrli_q:
10772   case Intrinsic::x86_sse2_psrai_w:
10773   case Intrinsic::x86_sse2_psrai_d:
10774   case Intrinsic::x86_avx2_psrai_w:
10775   case Intrinsic::x86_avx2_psrai_d: {
10776     unsigned Opcode;
10777     switch (IntNo) {
10778     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10779     case Intrinsic::x86_sse2_pslli_w:
10780     case Intrinsic::x86_sse2_pslli_d:
10781     case Intrinsic::x86_sse2_pslli_q:
10782     case Intrinsic::x86_avx2_pslli_w:
10783     case Intrinsic::x86_avx2_pslli_d:
10784     case Intrinsic::x86_avx2_pslli_q:
10785       Opcode = X86ISD::VSHLI;
10786       break;
10787     case Intrinsic::x86_sse2_psrli_w:
10788     case Intrinsic::x86_sse2_psrli_d:
10789     case Intrinsic::x86_sse2_psrli_q:
10790     case Intrinsic::x86_avx2_psrli_w:
10791     case Intrinsic::x86_avx2_psrli_d:
10792     case Intrinsic::x86_avx2_psrli_q:
10793       Opcode = X86ISD::VSRLI;
10794       break;
10795     case Intrinsic::x86_sse2_psrai_w:
10796     case Intrinsic::x86_sse2_psrai_d:
10797     case Intrinsic::x86_avx2_psrai_w:
10798     case Intrinsic::x86_avx2_psrai_d:
10799       Opcode = X86ISD::VSRAI;
10800       break;
10801     }
10802     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10803                                Op.getOperand(1), Op.getOperand(2), DAG);
10804   }
10805
10806   case Intrinsic::x86_sse42_pcmpistria128:
10807   case Intrinsic::x86_sse42_pcmpestria128:
10808   case Intrinsic::x86_sse42_pcmpistric128:
10809   case Intrinsic::x86_sse42_pcmpestric128:
10810   case Intrinsic::x86_sse42_pcmpistrio128:
10811   case Intrinsic::x86_sse42_pcmpestrio128:
10812   case Intrinsic::x86_sse42_pcmpistris128:
10813   case Intrinsic::x86_sse42_pcmpestris128:
10814   case Intrinsic::x86_sse42_pcmpistriz128:
10815   case Intrinsic::x86_sse42_pcmpestriz128: {
10816     unsigned Opcode;
10817     unsigned X86CC;
10818     switch (IntNo) {
10819     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10820     case Intrinsic::x86_sse42_pcmpistria128:
10821       Opcode = X86ISD::PCMPISTRI;
10822       X86CC = X86::COND_A;
10823       break;
10824     case Intrinsic::x86_sse42_pcmpestria128:
10825       Opcode = X86ISD::PCMPESTRI;
10826       X86CC = X86::COND_A;
10827       break;
10828     case Intrinsic::x86_sse42_pcmpistric128:
10829       Opcode = X86ISD::PCMPISTRI;
10830       X86CC = X86::COND_B;
10831       break;
10832     case Intrinsic::x86_sse42_pcmpestric128:
10833       Opcode = X86ISD::PCMPESTRI;
10834       X86CC = X86::COND_B;
10835       break;
10836     case Intrinsic::x86_sse42_pcmpistrio128:
10837       Opcode = X86ISD::PCMPISTRI;
10838       X86CC = X86::COND_O;
10839       break;
10840     case Intrinsic::x86_sse42_pcmpestrio128:
10841       Opcode = X86ISD::PCMPESTRI;
10842       X86CC = X86::COND_O;
10843       break;
10844     case Intrinsic::x86_sse42_pcmpistris128:
10845       Opcode = X86ISD::PCMPISTRI;
10846       X86CC = X86::COND_S;
10847       break;
10848     case Intrinsic::x86_sse42_pcmpestris128:
10849       Opcode = X86ISD::PCMPESTRI;
10850       X86CC = X86::COND_S;
10851       break;
10852     case Intrinsic::x86_sse42_pcmpistriz128:
10853       Opcode = X86ISD::PCMPISTRI;
10854       X86CC = X86::COND_E;
10855       break;
10856     case Intrinsic::x86_sse42_pcmpestriz128:
10857       Opcode = X86ISD::PCMPESTRI;
10858       X86CC = X86::COND_E;
10859       break;
10860     }
10861     SmallVector<SDValue, 5> NewOps;
10862     NewOps.append(Op->op_begin()+1, Op->op_end());
10863     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10864     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10865     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10866                                 DAG.getConstant(X86CC, MVT::i8),
10867                                 SDValue(PCMP.getNode(), 1));
10868     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10869   }
10870
10871   case Intrinsic::x86_sse42_pcmpistri128:
10872   case Intrinsic::x86_sse42_pcmpestri128: {
10873     unsigned Opcode;
10874     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10875       Opcode = X86ISD::PCMPISTRI;
10876     else
10877       Opcode = X86ISD::PCMPESTRI;
10878
10879     SmallVector<SDValue, 5> NewOps;
10880     NewOps.append(Op->op_begin()+1, Op->op_end());
10881     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10882     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10883   }
10884   case Intrinsic::x86_fma_vfmadd_ps:
10885   case Intrinsic::x86_fma_vfmadd_pd:
10886   case Intrinsic::x86_fma_vfmsub_ps:
10887   case Intrinsic::x86_fma_vfmsub_pd:
10888   case Intrinsic::x86_fma_vfnmadd_ps:
10889   case Intrinsic::x86_fma_vfnmadd_pd:
10890   case Intrinsic::x86_fma_vfnmsub_ps:
10891   case Intrinsic::x86_fma_vfnmsub_pd:
10892   case Intrinsic::x86_fma_vfmaddsub_ps:
10893   case Intrinsic::x86_fma_vfmaddsub_pd:
10894   case Intrinsic::x86_fma_vfmsubadd_ps:
10895   case Intrinsic::x86_fma_vfmsubadd_pd:
10896   case Intrinsic::x86_fma_vfmadd_ps_256:
10897   case Intrinsic::x86_fma_vfmadd_pd_256:
10898   case Intrinsic::x86_fma_vfmsub_ps_256:
10899   case Intrinsic::x86_fma_vfmsub_pd_256:
10900   case Intrinsic::x86_fma_vfnmadd_ps_256:
10901   case Intrinsic::x86_fma_vfnmadd_pd_256:
10902   case Intrinsic::x86_fma_vfnmsub_ps_256:
10903   case Intrinsic::x86_fma_vfnmsub_pd_256:
10904   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10905   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10906   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10907   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10908     unsigned Opc;
10909     switch (IntNo) {
10910     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10911     case Intrinsic::x86_fma_vfmadd_ps:
10912     case Intrinsic::x86_fma_vfmadd_pd:
10913     case Intrinsic::x86_fma_vfmadd_ps_256:
10914     case Intrinsic::x86_fma_vfmadd_pd_256:
10915       Opc = X86ISD::FMADD;
10916       break;
10917     case Intrinsic::x86_fma_vfmsub_ps:
10918     case Intrinsic::x86_fma_vfmsub_pd:
10919     case Intrinsic::x86_fma_vfmsub_ps_256:
10920     case Intrinsic::x86_fma_vfmsub_pd_256:
10921       Opc = X86ISD::FMSUB;
10922       break;
10923     case Intrinsic::x86_fma_vfnmadd_ps:
10924     case Intrinsic::x86_fma_vfnmadd_pd:
10925     case Intrinsic::x86_fma_vfnmadd_ps_256:
10926     case Intrinsic::x86_fma_vfnmadd_pd_256:
10927       Opc = X86ISD::FNMADD;
10928       break;
10929     case Intrinsic::x86_fma_vfnmsub_ps:
10930     case Intrinsic::x86_fma_vfnmsub_pd:
10931     case Intrinsic::x86_fma_vfnmsub_ps_256:
10932     case Intrinsic::x86_fma_vfnmsub_pd_256:
10933       Opc = X86ISD::FNMSUB;
10934       break;
10935     case Intrinsic::x86_fma_vfmaddsub_ps:
10936     case Intrinsic::x86_fma_vfmaddsub_pd:
10937     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10938     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10939       Opc = X86ISD::FMADDSUB;
10940       break;
10941     case Intrinsic::x86_fma_vfmsubadd_ps:
10942     case Intrinsic::x86_fma_vfmsubadd_pd:
10943     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10944     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10945       Opc = X86ISD::FMSUBADD;
10946       break;
10947     }
10948
10949     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10950                        Op.getOperand(2), Op.getOperand(3));
10951   }
10952   }
10953 }
10954
10955 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10956   DebugLoc dl = Op.getDebugLoc();
10957   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10958   switch (IntNo) {
10959   default: return SDValue();    // Don't custom lower most intrinsics.
10960
10961   // RDRAND/RDSEED intrinsics.
10962   case Intrinsic::x86_rdrand_16:
10963   case Intrinsic::x86_rdrand_32:
10964   case Intrinsic::x86_rdrand_64:
10965   case Intrinsic::x86_rdseed_16:
10966   case Intrinsic::x86_rdseed_32:
10967   case Intrinsic::x86_rdseed_64: {
10968     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10969                        IntNo == Intrinsic::x86_rdseed_32 ||
10970                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10971                                                             X86ISD::RDRAND;
10972     // Emit the node with the right value type.
10973     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10974     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10975
10976     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10977     // Otherwise return the value from Rand, which is always 0, casted to i32.
10978     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10979                       DAG.getConstant(1, Op->getValueType(1)),
10980                       DAG.getConstant(X86::COND_B, MVT::i32),
10981                       SDValue(Result.getNode(), 1) };
10982     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10983                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10984                                   Ops, array_lengthof(Ops));
10985
10986     // Return { result, isValid, chain }.
10987     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10988                        SDValue(Result.getNode(), 2));
10989   }
10990
10991   // XTEST intrinsics.
10992   case Intrinsic::x86_xtest: {
10993     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
10994     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
10995     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10996                                 DAG.getConstant(X86::COND_NE, MVT::i8),
10997                                 InTrans);
10998     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
10999     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11000                        Ret, SDValue(InTrans.getNode(), 1));
11001   }
11002   }
11003 }
11004
11005 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11006                                            SelectionDAG &DAG) const {
11007   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11008   MFI->setReturnAddressIsTaken(true);
11009
11010   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11011   DebugLoc dl = Op.getDebugLoc();
11012   EVT PtrVT = getPointerTy();
11013
11014   if (Depth > 0) {
11015     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11016     SDValue Offset =
11017       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11018     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11019                        DAG.getNode(ISD::ADD, dl, PtrVT,
11020                                    FrameAddr, Offset),
11021                        MachinePointerInfo(), false, false, false, 0);
11022   }
11023
11024   // Just load the return address.
11025   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11026   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11027                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11028 }
11029
11030 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11031   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11032   MFI->setFrameAddressIsTaken(true);
11033
11034   EVT VT = Op.getValueType();
11035   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
11036   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11037   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11038   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11039           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11040          "Invalid Frame Register!");
11041   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11042   while (Depth--)
11043     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11044                             MachinePointerInfo(),
11045                             false, false, false, 0);
11046   return FrameAddr;
11047 }
11048
11049 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11050                                                      SelectionDAG &DAG) const {
11051   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11052 }
11053
11054 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11055   SDValue Chain     = Op.getOperand(0);
11056   SDValue Offset    = Op.getOperand(1);
11057   SDValue Handler   = Op.getOperand(2);
11058   DebugLoc dl       = Op.getDebugLoc();
11059
11060   EVT PtrVT = getPointerTy();
11061   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11062   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11063           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11064          "Invalid Frame Register!");
11065   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11066   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11067
11068   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11069                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11070   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11071   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11072                        false, false, 0);
11073   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11074
11075   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11076                      DAG.getRegister(StoreAddrReg, PtrVT));
11077 }
11078
11079 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11080                                                SelectionDAG &DAG) const {
11081   DebugLoc DL = Op.getDebugLoc();
11082   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11083                      DAG.getVTList(MVT::i32, MVT::Other),
11084                      Op.getOperand(0), Op.getOperand(1));
11085 }
11086
11087 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11088                                                 SelectionDAG &DAG) const {
11089   DebugLoc DL = Op.getDebugLoc();
11090   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11091                      Op.getOperand(0), Op.getOperand(1));
11092 }
11093
11094 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11095   return Op.getOperand(0);
11096 }
11097
11098 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11099                                                 SelectionDAG &DAG) const {
11100   SDValue Root = Op.getOperand(0);
11101   SDValue Trmp = Op.getOperand(1); // trampoline
11102   SDValue FPtr = Op.getOperand(2); // nested function
11103   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11104   DebugLoc dl  = Op.getDebugLoc();
11105
11106   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11107   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11108
11109   if (Subtarget->is64Bit()) {
11110     SDValue OutChains[6];
11111
11112     // Large code-model.
11113     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11114     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11115
11116     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11117     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11118
11119     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11120
11121     // Load the pointer to the nested function into R11.
11122     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11123     SDValue Addr = Trmp;
11124     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11125                                 Addr, MachinePointerInfo(TrmpAddr),
11126                                 false, false, 0);
11127
11128     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11129                        DAG.getConstant(2, MVT::i64));
11130     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11131                                 MachinePointerInfo(TrmpAddr, 2),
11132                                 false, false, 2);
11133
11134     // Load the 'nest' parameter value into R10.
11135     // R10 is specified in X86CallingConv.td
11136     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11137     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11138                        DAG.getConstant(10, MVT::i64));
11139     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11140                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11141                                 false, false, 0);
11142
11143     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11144                        DAG.getConstant(12, MVT::i64));
11145     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11146                                 MachinePointerInfo(TrmpAddr, 12),
11147                                 false, false, 2);
11148
11149     // Jump to the nested function.
11150     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11151     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11152                        DAG.getConstant(20, MVT::i64));
11153     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11154                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11155                                 false, false, 0);
11156
11157     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11158     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11159                        DAG.getConstant(22, MVT::i64));
11160     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11161                                 MachinePointerInfo(TrmpAddr, 22),
11162                                 false, false, 0);
11163
11164     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11165   } else {
11166     const Function *Func =
11167       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11168     CallingConv::ID CC = Func->getCallingConv();
11169     unsigned NestReg;
11170
11171     switch (CC) {
11172     default:
11173       llvm_unreachable("Unsupported calling convention");
11174     case CallingConv::C:
11175     case CallingConv::X86_StdCall: {
11176       // Pass 'nest' parameter in ECX.
11177       // Must be kept in sync with X86CallingConv.td
11178       NestReg = X86::ECX;
11179
11180       // Check that ECX wasn't needed by an 'inreg' parameter.
11181       FunctionType *FTy = Func->getFunctionType();
11182       const AttributeSet &Attrs = Func->getAttributes();
11183
11184       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11185         unsigned InRegCount = 0;
11186         unsigned Idx = 1;
11187
11188         for (FunctionType::param_iterator I = FTy->param_begin(),
11189              E = FTy->param_end(); I != E; ++I, ++Idx)
11190           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11191             // FIXME: should only count parameters that are lowered to integers.
11192             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11193
11194         if (InRegCount > 2) {
11195           report_fatal_error("Nest register in use - reduce number of inreg"
11196                              " parameters!");
11197         }
11198       }
11199       break;
11200     }
11201     case CallingConv::X86_FastCall:
11202     case CallingConv::X86_ThisCall:
11203     case CallingConv::Fast:
11204       // Pass 'nest' parameter in EAX.
11205       // Must be kept in sync with X86CallingConv.td
11206       NestReg = X86::EAX;
11207       break;
11208     }
11209
11210     SDValue OutChains[4];
11211     SDValue Addr, Disp;
11212
11213     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11214                        DAG.getConstant(10, MVT::i32));
11215     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11216
11217     // This is storing the opcode for MOV32ri.
11218     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11219     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11220     OutChains[0] = DAG.getStore(Root, dl,
11221                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11222                                 Trmp, MachinePointerInfo(TrmpAddr),
11223                                 false, false, 0);
11224
11225     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11226                        DAG.getConstant(1, MVT::i32));
11227     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11228                                 MachinePointerInfo(TrmpAddr, 1),
11229                                 false, false, 1);
11230
11231     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11232     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11233                        DAG.getConstant(5, MVT::i32));
11234     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11235                                 MachinePointerInfo(TrmpAddr, 5),
11236                                 false, false, 1);
11237
11238     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11239                        DAG.getConstant(6, MVT::i32));
11240     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11241                                 MachinePointerInfo(TrmpAddr, 6),
11242                                 false, false, 1);
11243
11244     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11245   }
11246 }
11247
11248 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11249                                             SelectionDAG &DAG) const {
11250   /*
11251    The rounding mode is in bits 11:10 of FPSR, and has the following
11252    settings:
11253      00 Round to nearest
11254      01 Round to -inf
11255      10 Round to +inf
11256      11 Round to 0
11257
11258   FLT_ROUNDS, on the other hand, expects the following:
11259     -1 Undefined
11260      0 Round to 0
11261      1 Round to nearest
11262      2 Round to +inf
11263      3 Round to -inf
11264
11265   To perform the conversion, we do:
11266     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11267   */
11268
11269   MachineFunction &MF = DAG.getMachineFunction();
11270   const TargetMachine &TM = MF.getTarget();
11271   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11272   unsigned StackAlignment = TFI.getStackAlignment();
11273   EVT VT = Op.getValueType();
11274   DebugLoc DL = Op.getDebugLoc();
11275
11276   // Save FP Control Word to stack slot
11277   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11278   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11279
11280   MachineMemOperand *MMO =
11281    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11282                            MachineMemOperand::MOStore, 2, 2);
11283
11284   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11285   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11286                                           DAG.getVTList(MVT::Other),
11287                                           Ops, array_lengthof(Ops), MVT::i16,
11288                                           MMO);
11289
11290   // Load FP Control Word from stack slot
11291   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11292                             MachinePointerInfo(), false, false, false, 0);
11293
11294   // Transform as necessary
11295   SDValue CWD1 =
11296     DAG.getNode(ISD::SRL, DL, MVT::i16,
11297                 DAG.getNode(ISD::AND, DL, MVT::i16,
11298                             CWD, DAG.getConstant(0x800, MVT::i16)),
11299                 DAG.getConstant(11, MVT::i8));
11300   SDValue CWD2 =
11301     DAG.getNode(ISD::SRL, DL, MVT::i16,
11302                 DAG.getNode(ISD::AND, DL, MVT::i16,
11303                             CWD, DAG.getConstant(0x400, MVT::i16)),
11304                 DAG.getConstant(9, MVT::i8));
11305
11306   SDValue RetVal =
11307     DAG.getNode(ISD::AND, DL, MVT::i16,
11308                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11309                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11310                             DAG.getConstant(1, MVT::i16)),
11311                 DAG.getConstant(3, MVT::i16));
11312
11313   return DAG.getNode((VT.getSizeInBits() < 16 ?
11314                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11315 }
11316
11317 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11318   EVT VT = Op.getValueType();
11319   EVT OpVT = VT;
11320   unsigned NumBits = VT.getSizeInBits();
11321   DebugLoc dl = Op.getDebugLoc();
11322
11323   Op = Op.getOperand(0);
11324   if (VT == MVT::i8) {
11325     // Zero extend to i32 since there is not an i8 bsr.
11326     OpVT = MVT::i32;
11327     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11328   }
11329
11330   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11331   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11332   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11333
11334   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11335   SDValue Ops[] = {
11336     Op,
11337     DAG.getConstant(NumBits+NumBits-1, OpVT),
11338     DAG.getConstant(X86::COND_E, MVT::i8),
11339     Op.getValue(1)
11340   };
11341   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11342
11343   // Finally xor with NumBits-1.
11344   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11345
11346   if (VT == MVT::i8)
11347     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11348   return Op;
11349 }
11350
11351 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11352   EVT VT = Op.getValueType();
11353   EVT OpVT = VT;
11354   unsigned NumBits = VT.getSizeInBits();
11355   DebugLoc dl = Op.getDebugLoc();
11356
11357   Op = Op.getOperand(0);
11358   if (VT == MVT::i8) {
11359     // Zero extend to i32 since there is not an i8 bsr.
11360     OpVT = MVT::i32;
11361     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11362   }
11363
11364   // Issue a bsr (scan bits in reverse).
11365   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11366   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11367
11368   // And xor with NumBits-1.
11369   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11370
11371   if (VT == MVT::i8)
11372     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11373   return Op;
11374 }
11375
11376 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11377   EVT VT = Op.getValueType();
11378   unsigned NumBits = VT.getSizeInBits();
11379   DebugLoc dl = Op.getDebugLoc();
11380   Op = Op.getOperand(0);
11381
11382   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11383   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11384   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11385
11386   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11387   SDValue Ops[] = {
11388     Op,
11389     DAG.getConstant(NumBits, VT),
11390     DAG.getConstant(X86::COND_E, MVT::i8),
11391     Op.getValue(1)
11392   };
11393   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11394 }
11395
11396 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11397 // ones, and then concatenate the result back.
11398 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11399   EVT VT = Op.getValueType();
11400
11401   assert(VT.is256BitVector() && VT.isInteger() &&
11402          "Unsupported value type for operation");
11403
11404   unsigned NumElems = VT.getVectorNumElements();
11405   DebugLoc dl = Op.getDebugLoc();
11406
11407   // Extract the LHS vectors
11408   SDValue LHS = Op.getOperand(0);
11409   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11410   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11411
11412   // Extract the RHS vectors
11413   SDValue RHS = Op.getOperand(1);
11414   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11415   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11416
11417   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11418   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11419
11420   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11421                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11422                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11423 }
11424
11425 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11426   assert(Op.getValueType().is256BitVector() &&
11427          Op.getValueType().isInteger() &&
11428          "Only handle AVX 256-bit vector integer operation");
11429   return Lower256IntArith(Op, DAG);
11430 }
11431
11432 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11433   assert(Op.getValueType().is256BitVector() &&
11434          Op.getValueType().isInteger() &&
11435          "Only handle AVX 256-bit vector integer operation");
11436   return Lower256IntArith(Op, DAG);
11437 }
11438
11439 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11440                         SelectionDAG &DAG) {
11441   DebugLoc dl = Op.getDebugLoc();
11442   EVT VT = Op.getValueType();
11443
11444   // Decompose 256-bit ops into smaller 128-bit ops.
11445   if (VT.is256BitVector() && !Subtarget->hasInt256())
11446     return Lower256IntArith(Op, DAG);
11447
11448   SDValue A = Op.getOperand(0);
11449   SDValue B = Op.getOperand(1);
11450
11451   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11452   if (VT == MVT::v4i32) {
11453     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11454            "Should not custom lower when pmuldq is available!");
11455
11456     // Extract the odd parts.
11457     const int UnpackMask[] = { 1, -1, 3, -1 };
11458     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11459     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11460
11461     // Multiply the even parts.
11462     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11463     // Now multiply odd parts.
11464     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11465
11466     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11467     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11468
11469     // Merge the two vectors back together with a shuffle. This expands into 2
11470     // shuffles.
11471     const int ShufMask[] = { 0, 4, 2, 6 };
11472     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11473   }
11474
11475   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11476          "Only know how to lower V2I64/V4I64 multiply");
11477
11478   //  Ahi = psrlqi(a, 32);
11479   //  Bhi = psrlqi(b, 32);
11480   //
11481   //  AloBlo = pmuludq(a, b);
11482   //  AloBhi = pmuludq(a, Bhi);
11483   //  AhiBlo = pmuludq(Ahi, b);
11484
11485   //  AloBhi = psllqi(AloBhi, 32);
11486   //  AhiBlo = psllqi(AhiBlo, 32);
11487   //  return AloBlo + AloBhi + AhiBlo;
11488
11489   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11490
11491   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11492   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11493
11494   // Bit cast to 32-bit vectors for MULUDQ
11495   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11496   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11497   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11498   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11499   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11500
11501   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11502   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11503   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11504
11505   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11506   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11507
11508   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11509   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11510 }
11511
11512 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11513   EVT VT = Op.getValueType();
11514   EVT EltTy = VT.getVectorElementType();
11515   unsigned NumElts = VT.getVectorNumElements();
11516   SDValue N0 = Op.getOperand(0);
11517   DebugLoc dl = Op.getDebugLoc();
11518
11519   // Lower sdiv X, pow2-const.
11520   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11521   if (!C)
11522     return SDValue();
11523
11524   APInt SplatValue, SplatUndef;
11525   unsigned MinSplatBits;
11526   bool HasAnyUndefs;
11527   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11528     return SDValue();
11529
11530   if ((SplatValue != 0) &&
11531       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11532     unsigned lg2 = SplatValue.countTrailingZeros();
11533     // Splat the sign bit.
11534     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11535     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11536     // Add (N0 < 0) ? abs2 - 1 : 0;
11537     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11538     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11539     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11540     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11541     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11542
11543     // If we're dividing by a positive value, we're done.  Otherwise, we must
11544     // negate the result.
11545     if (SplatValue.isNonNegative())
11546       return SRA;
11547
11548     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11549     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11550     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11551   }
11552   return SDValue();
11553 }
11554
11555 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11556                                          const X86Subtarget *Subtarget) {
11557   EVT VT = Op.getValueType();
11558   DebugLoc dl = Op.getDebugLoc();
11559   SDValue R = Op.getOperand(0);
11560   SDValue Amt = Op.getOperand(1);
11561
11562   // Optimize shl/srl/sra with constant shift amount.
11563   if (isSplatVector(Amt.getNode())) {
11564     SDValue SclrAmt = Amt->getOperand(0);
11565     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11566       uint64_t ShiftAmt = C->getZExtValue();
11567
11568       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11569           (Subtarget->hasInt256() &&
11570            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11571         if (Op.getOpcode() == ISD::SHL)
11572           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11573                              DAG.getConstant(ShiftAmt, MVT::i32));
11574         if (Op.getOpcode() == ISD::SRL)
11575           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11576                              DAG.getConstant(ShiftAmt, MVT::i32));
11577         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11578           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11579                              DAG.getConstant(ShiftAmt, MVT::i32));
11580       }
11581
11582       if (VT == MVT::v16i8) {
11583         if (Op.getOpcode() == ISD::SHL) {
11584           // Make a large shift.
11585           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11586                                     DAG.getConstant(ShiftAmt, MVT::i32));
11587           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11588           // Zero out the rightmost bits.
11589           SmallVector<SDValue, 16> V(16,
11590                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11591                                                      MVT::i8));
11592           return DAG.getNode(ISD::AND, dl, VT, SHL,
11593                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11594         }
11595         if (Op.getOpcode() == ISD::SRL) {
11596           // Make a large shift.
11597           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11598                                     DAG.getConstant(ShiftAmt, MVT::i32));
11599           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11600           // Zero out the leftmost bits.
11601           SmallVector<SDValue, 16> V(16,
11602                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11603                                                      MVT::i8));
11604           return DAG.getNode(ISD::AND, dl, VT, SRL,
11605                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11606         }
11607         if (Op.getOpcode() == ISD::SRA) {
11608           if (ShiftAmt == 7) {
11609             // R s>> 7  ===  R s< 0
11610             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11611             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11612           }
11613
11614           // R s>> a === ((R u>> a) ^ m) - m
11615           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11616           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11617                                                          MVT::i8));
11618           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11619           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11620           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11621           return Res;
11622         }
11623         llvm_unreachable("Unknown shift opcode.");
11624       }
11625
11626       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11627         if (Op.getOpcode() == ISD::SHL) {
11628           // Make a large shift.
11629           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11630                                     DAG.getConstant(ShiftAmt, MVT::i32));
11631           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11632           // Zero out the rightmost bits.
11633           SmallVector<SDValue, 32> V(32,
11634                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11635                                                      MVT::i8));
11636           return DAG.getNode(ISD::AND, dl, VT, SHL,
11637                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11638         }
11639         if (Op.getOpcode() == ISD::SRL) {
11640           // Make a large shift.
11641           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11642                                     DAG.getConstant(ShiftAmt, MVT::i32));
11643           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11644           // Zero out the leftmost bits.
11645           SmallVector<SDValue, 32> V(32,
11646                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11647                                                      MVT::i8));
11648           return DAG.getNode(ISD::AND, dl, VT, SRL,
11649                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11650         }
11651         if (Op.getOpcode() == ISD::SRA) {
11652           if (ShiftAmt == 7) {
11653             // R s>> 7  ===  R s< 0
11654             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11655             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11656           }
11657
11658           // R s>> a === ((R u>> a) ^ m) - m
11659           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11660           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11661                                                          MVT::i8));
11662           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11663           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11664           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11665           return Res;
11666         }
11667         llvm_unreachable("Unknown shift opcode.");
11668       }
11669     }
11670   }
11671
11672   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11673   if (!Subtarget->is64Bit() &&
11674       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11675       Amt.getOpcode() == ISD::BITCAST &&
11676       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11677     Amt = Amt.getOperand(0);
11678     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11679                      VT.getVectorNumElements();
11680     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11681     uint64_t ShiftAmt = 0;
11682     for (unsigned i = 0; i != Ratio; ++i) {
11683       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11684       if (C == 0)
11685         return SDValue();
11686       // 6 == Log2(64)
11687       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11688     }
11689     // Check remaining shift amounts.
11690     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11691       uint64_t ShAmt = 0;
11692       for (unsigned j = 0; j != Ratio; ++j) {
11693         ConstantSDNode *C =
11694           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11695         if (C == 0)
11696           return SDValue();
11697         // 6 == Log2(64)
11698         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11699       }
11700       if (ShAmt != ShiftAmt)
11701         return SDValue();
11702     }
11703     switch (Op.getOpcode()) {
11704     default:
11705       llvm_unreachable("Unknown shift opcode!");
11706     case ISD::SHL:
11707       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11708                          DAG.getConstant(ShiftAmt, MVT::i32));
11709     case ISD::SRL:
11710       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11711                          DAG.getConstant(ShiftAmt, MVT::i32));
11712     case ISD::SRA:
11713       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11714                          DAG.getConstant(ShiftAmt, MVT::i32));
11715     }
11716   }
11717
11718   return SDValue();
11719 }
11720
11721 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11722                                         const X86Subtarget* Subtarget) {
11723   EVT VT = Op.getValueType();
11724   DebugLoc dl = Op.getDebugLoc();
11725   SDValue R = Op.getOperand(0);
11726   SDValue Amt = Op.getOperand(1);
11727
11728   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11729       VT == MVT::v4i32 || VT == MVT::v8i16 ||
11730       (Subtarget->hasInt256() &&
11731        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11732         VT == MVT::v8i32 || VT == MVT::v16i16))) {
11733     SDValue BaseShAmt;
11734     EVT EltVT = VT.getVectorElementType();
11735
11736     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11737       unsigned NumElts = VT.getVectorNumElements();
11738       unsigned i, j;
11739       for (i = 0; i != NumElts; ++i) {
11740         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11741           continue;
11742         break;
11743       }
11744       for (j = i; j != NumElts; ++j) {
11745         SDValue Arg = Amt.getOperand(j);
11746         if (Arg.getOpcode() == ISD::UNDEF) continue;
11747         if (Arg != Amt.getOperand(i))
11748           break;
11749       }
11750       if (i != NumElts && j == NumElts)
11751         BaseShAmt = Amt.getOperand(i);
11752     } else {
11753       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11754         Amt = Amt.getOperand(0);
11755       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11756                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11757         SDValue InVec = Amt.getOperand(0);
11758         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11759           unsigned NumElts = InVec.getValueType().getVectorNumElements();
11760           unsigned i = 0;
11761           for (; i != NumElts; ++i) {
11762             SDValue Arg = InVec.getOperand(i);
11763             if (Arg.getOpcode() == ISD::UNDEF) continue;
11764             BaseShAmt = Arg;
11765             break;
11766           }
11767         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11768            if (ConstantSDNode *C =
11769                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11770              unsigned SplatIdx =
11771                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11772              if (C->getZExtValue() == SplatIdx)
11773                BaseShAmt = InVec.getOperand(1);
11774            }
11775         }
11776         if (BaseShAmt.getNode() == 0)
11777           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11778                                   DAG.getIntPtrConstant(0));
11779       }
11780     }
11781
11782     if (BaseShAmt.getNode()) {
11783       if (EltVT.bitsGT(MVT::i32))
11784         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11785       else if (EltVT.bitsLT(MVT::i32))
11786         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11787
11788       switch (Op.getOpcode()) {
11789       default:
11790         llvm_unreachable("Unknown shift opcode!");
11791       case ISD::SHL:
11792         switch (VT.getSimpleVT().SimpleTy) {
11793         default: return SDValue();
11794         case MVT::v2i64:
11795         case MVT::v4i32:
11796         case MVT::v8i16:
11797         case MVT::v4i64:
11798         case MVT::v8i32:
11799         case MVT::v16i16:
11800           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11801         }
11802       case ISD::SRA:
11803         switch (VT.getSimpleVT().SimpleTy) {
11804         default: return SDValue();
11805         case MVT::v4i32:
11806         case MVT::v8i16:
11807         case MVT::v8i32:
11808         case MVT::v16i16:
11809           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11810         }
11811       case ISD::SRL:
11812         switch (VT.getSimpleVT().SimpleTy) {
11813         default: return SDValue();
11814         case MVT::v2i64:
11815         case MVT::v4i32:
11816         case MVT::v8i16:
11817         case MVT::v4i64:
11818         case MVT::v8i32:
11819         case MVT::v16i16:
11820           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11821         }
11822       }
11823     }
11824   }
11825
11826   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11827   if (!Subtarget->is64Bit() &&
11828       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11829       Amt.getOpcode() == ISD::BITCAST &&
11830       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11831     Amt = Amt.getOperand(0);
11832     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11833                      VT.getVectorNumElements();
11834     std::vector<SDValue> Vals(Ratio);
11835     for (unsigned i = 0; i != Ratio; ++i)
11836       Vals[i] = Amt.getOperand(i);
11837     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11838       for (unsigned j = 0; j != Ratio; ++j)
11839         if (Vals[j] != Amt.getOperand(i + j))
11840           return SDValue();
11841     }
11842     switch (Op.getOpcode()) {
11843     default:
11844       llvm_unreachable("Unknown shift opcode!");
11845     case ISD::SHL:
11846       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11847     case ISD::SRL:
11848       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11849     case ISD::SRA:
11850       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11851     }
11852   }
11853
11854   return SDValue();
11855 }
11856
11857 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11858
11859   EVT VT = Op.getValueType();
11860   DebugLoc dl = Op.getDebugLoc();
11861   SDValue R = Op.getOperand(0);
11862   SDValue Amt = Op.getOperand(1);
11863   SDValue V;
11864
11865   if (!Subtarget->hasSSE2())
11866     return SDValue();
11867
11868   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11869   if (V.getNode())
11870     return V;
11871
11872   V = LowerScalarVariableShift(Op, DAG, Subtarget);
11873   if (V.getNode())
11874       return V;
11875
11876   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11877   if (Subtarget->hasInt256()) {
11878     if (Op.getOpcode() == ISD::SRL &&
11879         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11880          VT == MVT::v4i64 || VT == MVT::v8i32))
11881       return Op;
11882     if (Op.getOpcode() == ISD::SHL &&
11883         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11884          VT == MVT::v4i64 || VT == MVT::v8i32))
11885       return Op;
11886     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11887       return Op;
11888   }
11889
11890   // Lower SHL with variable shift amount.
11891   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11892     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11893
11894     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11895     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11896     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11897     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11898   }
11899   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11900     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11901
11902     // a = a << 5;
11903     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11904     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11905
11906     // Turn 'a' into a mask suitable for VSELECT
11907     SDValue VSelM = DAG.getConstant(0x80, VT);
11908     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11909     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11910
11911     SDValue CM1 = DAG.getConstant(0x0f, VT);
11912     SDValue CM2 = DAG.getConstant(0x3f, VT);
11913
11914     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11915     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11916     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11917                             DAG.getConstant(4, MVT::i32), DAG);
11918     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11919     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11920
11921     // a += a
11922     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11923     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11924     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11925
11926     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11927     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11928     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11929                             DAG.getConstant(2, MVT::i32), DAG);
11930     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11931     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11932
11933     // a += a
11934     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11935     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11936     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11937
11938     // return VSELECT(r, r+r, a);
11939     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11940                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11941     return R;
11942   }
11943
11944   // Decompose 256-bit shifts into smaller 128-bit shifts.
11945   if (VT.is256BitVector()) {
11946     unsigned NumElems = VT.getVectorNumElements();
11947     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11948     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11949
11950     // Extract the two vectors
11951     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11952     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11953
11954     // Recreate the shift amount vectors
11955     SDValue Amt1, Amt2;
11956     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11957       // Constant shift amount
11958       SmallVector<SDValue, 4> Amt1Csts;
11959       SmallVector<SDValue, 4> Amt2Csts;
11960       for (unsigned i = 0; i != NumElems/2; ++i)
11961         Amt1Csts.push_back(Amt->getOperand(i));
11962       for (unsigned i = NumElems/2; i != NumElems; ++i)
11963         Amt2Csts.push_back(Amt->getOperand(i));
11964
11965       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11966                                  &Amt1Csts[0], NumElems/2);
11967       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11968                                  &Amt2Csts[0], NumElems/2);
11969     } else {
11970       // Variable shift amount
11971       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11972       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11973     }
11974
11975     // Issue new vector shifts for the smaller types
11976     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11977     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11978
11979     // Concatenate the result back
11980     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11981   }
11982
11983   return SDValue();
11984 }
11985
11986 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11987   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11988   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11989   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11990   // has only one use.
11991   SDNode *N = Op.getNode();
11992   SDValue LHS = N->getOperand(0);
11993   SDValue RHS = N->getOperand(1);
11994   unsigned BaseOp = 0;
11995   unsigned Cond = 0;
11996   DebugLoc DL = Op.getDebugLoc();
11997   switch (Op.getOpcode()) {
11998   default: llvm_unreachable("Unknown ovf instruction!");
11999   case ISD::SADDO:
12000     // A subtract of one will be selected as a INC. Note that INC doesn't
12001     // set CF, so we can't do this for UADDO.
12002     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12003       if (C->isOne()) {
12004         BaseOp = X86ISD::INC;
12005         Cond = X86::COND_O;
12006         break;
12007       }
12008     BaseOp = X86ISD::ADD;
12009     Cond = X86::COND_O;
12010     break;
12011   case ISD::UADDO:
12012     BaseOp = X86ISD::ADD;
12013     Cond = X86::COND_B;
12014     break;
12015   case ISD::SSUBO:
12016     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12017     // set CF, so we can't do this for USUBO.
12018     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12019       if (C->isOne()) {
12020         BaseOp = X86ISD::DEC;
12021         Cond = X86::COND_O;
12022         break;
12023       }
12024     BaseOp = X86ISD::SUB;
12025     Cond = X86::COND_O;
12026     break;
12027   case ISD::USUBO:
12028     BaseOp = X86ISD::SUB;
12029     Cond = X86::COND_B;
12030     break;
12031   case ISD::SMULO:
12032     BaseOp = X86ISD::SMUL;
12033     Cond = X86::COND_O;
12034     break;
12035   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12036     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12037                                  MVT::i32);
12038     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12039
12040     SDValue SetCC =
12041       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12042                   DAG.getConstant(X86::COND_O, MVT::i32),
12043                   SDValue(Sum.getNode(), 2));
12044
12045     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12046   }
12047   }
12048
12049   // Also sets EFLAGS.
12050   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12051   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12052
12053   SDValue SetCC =
12054     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12055                 DAG.getConstant(Cond, MVT::i32),
12056                 SDValue(Sum.getNode(), 1));
12057
12058   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12059 }
12060
12061 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12062                                                   SelectionDAG &DAG) const {
12063   DebugLoc dl = Op.getDebugLoc();
12064   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12065   EVT VT = Op.getValueType();
12066
12067   if (!Subtarget->hasSSE2() || !VT.isVector())
12068     return SDValue();
12069
12070   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12071                       ExtraVT.getScalarType().getSizeInBits();
12072   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12073
12074   switch (VT.getSimpleVT().SimpleTy) {
12075     default: return SDValue();
12076     case MVT::v8i32:
12077     case MVT::v16i16:
12078       if (!Subtarget->hasFp256())
12079         return SDValue();
12080       if (!Subtarget->hasInt256()) {
12081         // needs to be split
12082         unsigned NumElems = VT.getVectorNumElements();
12083
12084         // Extract the LHS vectors
12085         SDValue LHS = Op.getOperand(0);
12086         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12087         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12088
12089         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12090         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12091
12092         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12093         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12094         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12095                                    ExtraNumElems/2);
12096         SDValue Extra = DAG.getValueType(ExtraVT);
12097
12098         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12099         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12100
12101         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12102       }
12103       // fall through
12104     case MVT::v4i32:
12105     case MVT::v8i16: {
12106       // (sext (vzext x)) -> (vsext x)
12107       SDValue Op0 = Op.getOperand(0);
12108       SDValue Op00 = Op0.getOperand(0);
12109       SDValue Tmp1;
12110       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12111       if (Op0.getOpcode() == ISD::BITCAST &&
12112           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12113         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12114       if (Tmp1.getNode()) {
12115         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12116         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12117                "This optimization is invalid without a VZEXT.");
12118         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12119       }
12120
12121       // If the above didn't work, then just use Shift-Left + Shift-Right.
12122       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12123       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12124     }
12125   }
12126 }
12127
12128 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12129                                  SelectionDAG &DAG) {
12130   DebugLoc dl = Op.getDebugLoc();
12131   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12132     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12133   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12134     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12135
12136   // The only fence that needs an instruction is a sequentially-consistent
12137   // cross-thread fence.
12138   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12139     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12140     // no-sse2). There isn't any reason to disable it if the target processor
12141     // supports it.
12142     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12143       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12144
12145     SDValue Chain = Op.getOperand(0);
12146     SDValue Zero = DAG.getConstant(0, MVT::i32);
12147     SDValue Ops[] = {
12148       DAG.getRegister(X86::ESP, MVT::i32), // Base
12149       DAG.getTargetConstant(1, MVT::i8),   // Scale
12150       DAG.getRegister(0, MVT::i32),        // Index
12151       DAG.getTargetConstant(0, MVT::i32),  // Disp
12152       DAG.getRegister(0, MVT::i32),        // Segment.
12153       Zero,
12154       Chain
12155     };
12156     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12157     return SDValue(Res, 0);
12158   }
12159
12160   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12161   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12162 }
12163
12164 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12165                              SelectionDAG &DAG) {
12166   EVT T = Op.getValueType();
12167   DebugLoc DL = Op.getDebugLoc();
12168   unsigned Reg = 0;
12169   unsigned size = 0;
12170   switch(T.getSimpleVT().SimpleTy) {
12171   default: llvm_unreachable("Invalid value type!");
12172   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12173   case MVT::i16: Reg = X86::AX;  size = 2; break;
12174   case MVT::i32: Reg = X86::EAX; size = 4; break;
12175   case MVT::i64:
12176     assert(Subtarget->is64Bit() && "Node not type legal!");
12177     Reg = X86::RAX; size = 8;
12178     break;
12179   }
12180   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12181                                     Op.getOperand(2), SDValue());
12182   SDValue Ops[] = { cpIn.getValue(0),
12183                     Op.getOperand(1),
12184                     Op.getOperand(3),
12185                     DAG.getTargetConstant(size, MVT::i8),
12186                     cpIn.getValue(1) };
12187   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12188   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12189   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12190                                            Ops, array_lengthof(Ops), T, MMO);
12191   SDValue cpOut =
12192     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12193   return cpOut;
12194 }
12195
12196 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12197                                      SelectionDAG &DAG) {
12198   assert(Subtarget->is64Bit() && "Result not type legalized?");
12199   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12200   SDValue TheChain = Op.getOperand(0);
12201   DebugLoc dl = Op.getDebugLoc();
12202   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12203   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12204   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12205                                    rax.getValue(2));
12206   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12207                             DAG.getConstant(32, MVT::i8));
12208   SDValue Ops[] = {
12209     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12210     rdx.getValue(1)
12211   };
12212   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12213 }
12214
12215 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12216   EVT SrcVT = Op.getOperand(0).getValueType();
12217   EVT DstVT = Op.getValueType();
12218   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12219          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12220   assert((DstVT == MVT::i64 ||
12221           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12222          "Unexpected custom BITCAST");
12223   // i64 <=> MMX conversions are Legal.
12224   if (SrcVT==MVT::i64 && DstVT.isVector())
12225     return Op;
12226   if (DstVT==MVT::i64 && SrcVT.isVector())
12227     return Op;
12228   // MMX <=> MMX conversions are Legal.
12229   if (SrcVT.isVector() && DstVT.isVector())
12230     return Op;
12231   // All other conversions need to be expanded.
12232   return SDValue();
12233 }
12234
12235 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12236   SDNode *Node = Op.getNode();
12237   DebugLoc dl = Node->getDebugLoc();
12238   EVT T = Node->getValueType(0);
12239   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12240                               DAG.getConstant(0, T), Node->getOperand(2));
12241   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12242                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12243                        Node->getOperand(0),
12244                        Node->getOperand(1), negOp,
12245                        cast<AtomicSDNode>(Node)->getSrcValue(),
12246                        cast<AtomicSDNode>(Node)->getAlignment(),
12247                        cast<AtomicSDNode>(Node)->getOrdering(),
12248                        cast<AtomicSDNode>(Node)->getSynchScope());
12249 }
12250
12251 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12252   SDNode *Node = Op.getNode();
12253   DebugLoc dl = Node->getDebugLoc();
12254   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12255
12256   // Convert seq_cst store -> xchg
12257   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12258   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12259   //        (The only way to get a 16-byte store is cmpxchg16b)
12260   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12261   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12262       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12263     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12264                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12265                                  Node->getOperand(0),
12266                                  Node->getOperand(1), Node->getOperand(2),
12267                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12268                                  cast<AtomicSDNode>(Node)->getOrdering(),
12269                                  cast<AtomicSDNode>(Node)->getSynchScope());
12270     return Swap.getValue(1);
12271   }
12272   // Other atomic stores have a simple pattern.
12273   return Op;
12274 }
12275
12276 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12277   EVT VT = Op.getNode()->getValueType(0);
12278
12279   // Let legalize expand this if it isn't a legal type yet.
12280   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12281     return SDValue();
12282
12283   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12284
12285   unsigned Opc;
12286   bool ExtraOp = false;
12287   switch (Op.getOpcode()) {
12288   default: llvm_unreachable("Invalid code");
12289   case ISD::ADDC: Opc = X86ISD::ADD; break;
12290   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12291   case ISD::SUBC: Opc = X86ISD::SUB; break;
12292   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12293   }
12294
12295   if (!ExtraOp)
12296     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12297                        Op.getOperand(1));
12298   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12299                      Op.getOperand(1), Op.getOperand(2));
12300 }
12301
12302 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12303   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12304
12305   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12306   // which returns the values as { float, float } (in XMM0) or
12307   // { double, double } (which is returned in XMM0, XMM1).
12308   DebugLoc dl = Op.getDebugLoc();
12309   SDValue Arg = Op.getOperand(0);
12310   EVT ArgVT = Arg.getValueType();
12311   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12312
12313   ArgListTy Args;
12314   ArgListEntry Entry;
12315
12316   Entry.Node = Arg;
12317   Entry.Ty = ArgTy;
12318   Entry.isSExt = false;
12319   Entry.isZExt = false;
12320   Args.push_back(Entry);
12321
12322   bool isF64 = ArgVT == MVT::f64;
12323   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12324   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12325   // the results are returned via SRet in memory.
12326   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12327   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12328
12329   Type *RetTy = isF64
12330     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12331     : (Type*)VectorType::get(ArgTy, 4);
12332   TargetLowering::
12333     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12334                          false, false, false, false, 0,
12335                          CallingConv::C, /*isTaillCall=*/false,
12336                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12337                          Callee, Args, DAG, dl);
12338   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12339
12340   if (isF64)
12341     // Returned in xmm0 and xmm1.
12342     return CallResult.first;
12343
12344   // Returned in bits 0:31 and 32:64 xmm0.
12345   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12346                                CallResult.first, DAG.getIntPtrConstant(0));
12347   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12348                                CallResult.first, DAG.getIntPtrConstant(1));
12349   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12350   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12351 }
12352
12353 /// LowerOperation - Provide custom lowering hooks for some operations.
12354 ///
12355 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12356   switch (Op.getOpcode()) {
12357   default: llvm_unreachable("Should not custom lower this!");
12358   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12359   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12360   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12361   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12362   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12363   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12364   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12365   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12366   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12367   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12368   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12369   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12370   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12371   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12372   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12373   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12374   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12375   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12376   case ISD::SHL_PARTS:
12377   case ISD::SRA_PARTS:
12378   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12379   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12380   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12381   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12382   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12383   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12384   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12385   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12386   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12387   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12388   case ISD::FABS:               return LowerFABS(Op, DAG);
12389   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12390   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12391   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12392   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12393   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12394   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12395   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12396   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12397   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12398   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12399   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12400   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12401   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12402   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12403   case ISD::FRAME_TO_ARGS_OFFSET:
12404                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12405   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12406   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12407   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12408   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12409   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12410   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12411   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12412   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12413   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12414   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12415   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12416   case ISD::SRA:
12417   case ISD::SRL:
12418   case ISD::SHL:                return LowerShift(Op, DAG);
12419   case ISD::SADDO:
12420   case ISD::UADDO:
12421   case ISD::SSUBO:
12422   case ISD::USUBO:
12423   case ISD::SMULO:
12424   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12425   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12426   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12427   case ISD::ADDC:
12428   case ISD::ADDE:
12429   case ISD::SUBC:
12430   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12431   case ISD::ADD:                return LowerADD(Op, DAG);
12432   case ISD::SUB:                return LowerSUB(Op, DAG);
12433   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12434   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12435   }
12436 }
12437
12438 static void ReplaceATOMIC_LOAD(SDNode *Node,
12439                                   SmallVectorImpl<SDValue> &Results,
12440                                   SelectionDAG &DAG) {
12441   DebugLoc dl = Node->getDebugLoc();
12442   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12443
12444   // Convert wide load -> cmpxchg8b/cmpxchg16b
12445   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12446   //        (The only way to get a 16-byte load is cmpxchg16b)
12447   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12448   SDValue Zero = DAG.getConstant(0, VT);
12449   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12450                                Node->getOperand(0),
12451                                Node->getOperand(1), Zero, Zero,
12452                                cast<AtomicSDNode>(Node)->getMemOperand(),
12453                                cast<AtomicSDNode>(Node)->getOrdering(),
12454                                cast<AtomicSDNode>(Node)->getSynchScope());
12455   Results.push_back(Swap.getValue(0));
12456   Results.push_back(Swap.getValue(1));
12457 }
12458
12459 static void
12460 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12461                         SelectionDAG &DAG, unsigned NewOp) {
12462   DebugLoc dl = Node->getDebugLoc();
12463   assert (Node->getValueType(0) == MVT::i64 &&
12464           "Only know how to expand i64 atomics");
12465
12466   SDValue Chain = Node->getOperand(0);
12467   SDValue In1 = Node->getOperand(1);
12468   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12469                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12470   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12471                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12472   SDValue Ops[] = { Chain, In1, In2L, In2H };
12473   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12474   SDValue Result =
12475     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12476                             cast<MemSDNode>(Node)->getMemOperand());
12477   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12478   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12479   Results.push_back(Result.getValue(2));
12480 }
12481
12482 /// ReplaceNodeResults - Replace a node with an illegal result type
12483 /// with a new node built out of custom code.
12484 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12485                                            SmallVectorImpl<SDValue>&Results,
12486                                            SelectionDAG &DAG) const {
12487   DebugLoc dl = N->getDebugLoc();
12488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12489   switch (N->getOpcode()) {
12490   default:
12491     llvm_unreachable("Do not know how to custom type legalize this operation!");
12492   case ISD::SIGN_EXTEND_INREG:
12493   case ISD::ADDC:
12494   case ISD::ADDE:
12495   case ISD::SUBC:
12496   case ISD::SUBE:
12497     // We don't want to expand or promote these.
12498     return;
12499   case ISD::FP_TO_SINT:
12500   case ISD::FP_TO_UINT: {
12501     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12502
12503     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12504       return;
12505
12506     std::pair<SDValue,SDValue> Vals =
12507         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12508     SDValue FIST = Vals.first, StackSlot = Vals.second;
12509     if (FIST.getNode() != 0) {
12510       EVT VT = N->getValueType(0);
12511       // Return a load from the stack slot.
12512       if (StackSlot.getNode() != 0)
12513         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12514                                       MachinePointerInfo(),
12515                                       false, false, false, 0));
12516       else
12517         Results.push_back(FIST);
12518     }
12519     return;
12520   }
12521   case ISD::UINT_TO_FP: {
12522     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12523     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12524         N->getValueType(0) != MVT::v2f32)
12525       return;
12526     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12527                                  N->getOperand(0));
12528     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12529                                      MVT::f64);
12530     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12531     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12532                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12533     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12534     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12535     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12536     return;
12537   }
12538   case ISD::FP_ROUND: {
12539     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12540         return;
12541     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12542     Results.push_back(V);
12543     return;
12544   }
12545   case ISD::READCYCLECOUNTER: {
12546     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12547     SDValue TheChain = N->getOperand(0);
12548     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12549     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12550                                      rd.getValue(1));
12551     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12552                                      eax.getValue(2));
12553     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12554     SDValue Ops[] = { eax, edx };
12555     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12556                                   array_lengthof(Ops)));
12557     Results.push_back(edx.getValue(1));
12558     return;
12559   }
12560   case ISD::ATOMIC_CMP_SWAP: {
12561     EVT T = N->getValueType(0);
12562     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12563     bool Regs64bit = T == MVT::i128;
12564     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12565     SDValue cpInL, cpInH;
12566     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12567                         DAG.getConstant(0, HalfT));
12568     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12569                         DAG.getConstant(1, HalfT));
12570     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12571                              Regs64bit ? X86::RAX : X86::EAX,
12572                              cpInL, SDValue());
12573     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12574                              Regs64bit ? X86::RDX : X86::EDX,
12575                              cpInH, cpInL.getValue(1));
12576     SDValue swapInL, swapInH;
12577     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12578                           DAG.getConstant(0, HalfT));
12579     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12580                           DAG.getConstant(1, HalfT));
12581     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12582                                Regs64bit ? X86::RBX : X86::EBX,
12583                                swapInL, cpInH.getValue(1));
12584     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12585                                Regs64bit ? X86::RCX : X86::ECX,
12586                                swapInH, swapInL.getValue(1));
12587     SDValue Ops[] = { swapInH.getValue(0),
12588                       N->getOperand(1),
12589                       swapInH.getValue(1) };
12590     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12591     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12592     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12593                                   X86ISD::LCMPXCHG8_DAG;
12594     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12595                                              Ops, array_lengthof(Ops), T, MMO);
12596     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12597                                         Regs64bit ? X86::RAX : X86::EAX,
12598                                         HalfT, Result.getValue(1));
12599     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12600                                         Regs64bit ? X86::RDX : X86::EDX,
12601                                         HalfT, cpOutL.getValue(2));
12602     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12603     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12604     Results.push_back(cpOutH.getValue(1));
12605     return;
12606   }
12607   case ISD::ATOMIC_LOAD_ADD:
12608   case ISD::ATOMIC_LOAD_AND:
12609   case ISD::ATOMIC_LOAD_NAND:
12610   case ISD::ATOMIC_LOAD_OR:
12611   case ISD::ATOMIC_LOAD_SUB:
12612   case ISD::ATOMIC_LOAD_XOR:
12613   case ISD::ATOMIC_LOAD_MAX:
12614   case ISD::ATOMIC_LOAD_MIN:
12615   case ISD::ATOMIC_LOAD_UMAX:
12616   case ISD::ATOMIC_LOAD_UMIN:
12617   case ISD::ATOMIC_SWAP: {
12618     unsigned Opc;
12619     switch (N->getOpcode()) {
12620     default: llvm_unreachable("Unexpected opcode");
12621     case ISD::ATOMIC_LOAD_ADD:
12622       Opc = X86ISD::ATOMADD64_DAG;
12623       break;
12624     case ISD::ATOMIC_LOAD_AND:
12625       Opc = X86ISD::ATOMAND64_DAG;
12626       break;
12627     case ISD::ATOMIC_LOAD_NAND:
12628       Opc = X86ISD::ATOMNAND64_DAG;
12629       break;
12630     case ISD::ATOMIC_LOAD_OR:
12631       Opc = X86ISD::ATOMOR64_DAG;
12632       break;
12633     case ISD::ATOMIC_LOAD_SUB:
12634       Opc = X86ISD::ATOMSUB64_DAG;
12635       break;
12636     case ISD::ATOMIC_LOAD_XOR:
12637       Opc = X86ISD::ATOMXOR64_DAG;
12638       break;
12639     case ISD::ATOMIC_LOAD_MAX:
12640       Opc = X86ISD::ATOMMAX64_DAG;
12641       break;
12642     case ISD::ATOMIC_LOAD_MIN:
12643       Opc = X86ISD::ATOMMIN64_DAG;
12644       break;
12645     case ISD::ATOMIC_LOAD_UMAX:
12646       Opc = X86ISD::ATOMUMAX64_DAG;
12647       break;
12648     case ISD::ATOMIC_LOAD_UMIN:
12649       Opc = X86ISD::ATOMUMIN64_DAG;
12650       break;
12651     case ISD::ATOMIC_SWAP:
12652       Opc = X86ISD::ATOMSWAP64_DAG;
12653       break;
12654     }
12655     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12656     return;
12657   }
12658   case ISD::ATOMIC_LOAD:
12659     ReplaceATOMIC_LOAD(N, Results, DAG);
12660   }
12661 }
12662
12663 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12664   switch (Opcode) {
12665   default: return NULL;
12666   case X86ISD::BSF:                return "X86ISD::BSF";
12667   case X86ISD::BSR:                return "X86ISD::BSR";
12668   case X86ISD::SHLD:               return "X86ISD::SHLD";
12669   case X86ISD::SHRD:               return "X86ISD::SHRD";
12670   case X86ISD::FAND:               return "X86ISD::FAND";
12671   case X86ISD::FOR:                return "X86ISD::FOR";
12672   case X86ISD::FXOR:               return "X86ISD::FXOR";
12673   case X86ISD::FSRL:               return "X86ISD::FSRL";
12674   case X86ISD::FILD:               return "X86ISD::FILD";
12675   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12676   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12677   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12678   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12679   case X86ISD::FLD:                return "X86ISD::FLD";
12680   case X86ISD::FST:                return "X86ISD::FST";
12681   case X86ISD::CALL:               return "X86ISD::CALL";
12682   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12683   case X86ISD::BT:                 return "X86ISD::BT";
12684   case X86ISD::CMP:                return "X86ISD::CMP";
12685   case X86ISD::COMI:               return "X86ISD::COMI";
12686   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12687   case X86ISD::SETCC:              return "X86ISD::SETCC";
12688   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12689   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12690   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12691   case X86ISD::CMOV:               return "X86ISD::CMOV";
12692   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12693   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12694   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12695   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12696   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12697   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12698   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12699   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12700   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12701   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12702   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12703   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12704   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12705   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12706   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12707   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12708   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12709   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12710   case X86ISD::HADD:               return "X86ISD::HADD";
12711   case X86ISD::HSUB:               return "X86ISD::HSUB";
12712   case X86ISD::FHADD:              return "X86ISD::FHADD";
12713   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12714   case X86ISD::UMAX:               return "X86ISD::UMAX";
12715   case X86ISD::UMIN:               return "X86ISD::UMIN";
12716   case X86ISD::SMAX:               return "X86ISD::SMAX";
12717   case X86ISD::SMIN:               return "X86ISD::SMIN";
12718   case X86ISD::FMAX:               return "X86ISD::FMAX";
12719   case X86ISD::FMIN:               return "X86ISD::FMIN";
12720   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12721   case X86ISD::FMINC:              return "X86ISD::FMINC";
12722   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12723   case X86ISD::FRCP:               return "X86ISD::FRCP";
12724   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12725   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12726   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12727   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12728   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12729   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12730   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12731   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12732   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12733   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12734   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12735   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12736   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12737   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12738   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12739   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12740   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12741   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12742   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12743   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12744   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12745   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12746   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12747   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12748   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12749   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12750   case X86ISD::VSHL:               return "X86ISD::VSHL";
12751   case X86ISD::VSRL:               return "X86ISD::VSRL";
12752   case X86ISD::VSRA:               return "X86ISD::VSRA";
12753   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12754   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12755   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12756   case X86ISD::CMPP:               return "X86ISD::CMPP";
12757   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12758   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12759   case X86ISD::ADD:                return "X86ISD::ADD";
12760   case X86ISD::SUB:                return "X86ISD::SUB";
12761   case X86ISD::ADC:                return "X86ISD::ADC";
12762   case X86ISD::SBB:                return "X86ISD::SBB";
12763   case X86ISD::SMUL:               return "X86ISD::SMUL";
12764   case X86ISD::UMUL:               return "X86ISD::UMUL";
12765   case X86ISD::INC:                return "X86ISD::INC";
12766   case X86ISD::DEC:                return "X86ISD::DEC";
12767   case X86ISD::OR:                 return "X86ISD::OR";
12768   case X86ISD::XOR:                return "X86ISD::XOR";
12769   case X86ISD::AND:                return "X86ISD::AND";
12770   case X86ISD::BLSI:               return "X86ISD::BLSI";
12771   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12772   case X86ISD::BLSR:               return "X86ISD::BLSR";
12773   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12774   case X86ISD::PTEST:              return "X86ISD::PTEST";
12775   case X86ISD::TESTP:              return "X86ISD::TESTP";
12776   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12777   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12778   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12779   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12780   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12781   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12782   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12783   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12784   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12785   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12786   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12787   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12788   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12789   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12790   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12791   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12792   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12793   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12794   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12795   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12796   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12797   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12798   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12799   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12800   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12801   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12802   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12803   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12804   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12805   case X86ISD::SAHF:               return "X86ISD::SAHF";
12806   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12807   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12808   case X86ISD::FMADD:              return "X86ISD::FMADD";
12809   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12810   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12811   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12812   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12813   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12814   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12815   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12816   case X86ISD::XTEST:              return "X86ISD::XTEST";
12817   }
12818 }
12819
12820 // isLegalAddressingMode - Return true if the addressing mode represented
12821 // by AM is legal for this target, for a load/store of the specified type.
12822 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12823                                               Type *Ty) const {
12824   // X86 supports extremely general addressing modes.
12825   CodeModel::Model M = getTargetMachine().getCodeModel();
12826   Reloc::Model R = getTargetMachine().getRelocationModel();
12827
12828   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12829   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12830     return false;
12831
12832   if (AM.BaseGV) {
12833     unsigned GVFlags =
12834       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12835
12836     // If a reference to this global requires an extra load, we can't fold it.
12837     if (isGlobalStubReference(GVFlags))
12838       return false;
12839
12840     // If BaseGV requires a register for the PIC base, we cannot also have a
12841     // BaseReg specified.
12842     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12843       return false;
12844
12845     // If lower 4G is not available, then we must use rip-relative addressing.
12846     if ((M != CodeModel::Small || R != Reloc::Static) &&
12847         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12848       return false;
12849   }
12850
12851   switch (AM.Scale) {
12852   case 0:
12853   case 1:
12854   case 2:
12855   case 4:
12856   case 8:
12857     // These scales always work.
12858     break;
12859   case 3:
12860   case 5:
12861   case 9:
12862     // These scales are formed with basereg+scalereg.  Only accept if there is
12863     // no basereg yet.
12864     if (AM.HasBaseReg)
12865       return false;
12866     break;
12867   default:  // Other stuff never works.
12868     return false;
12869   }
12870
12871   return true;
12872 }
12873
12874 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12875   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12876     return false;
12877   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12878   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12879   return NumBits1 > NumBits2;
12880 }
12881
12882 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12883   return isInt<32>(Imm);
12884 }
12885
12886 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12887   // Can also use sub to handle negated immediates.
12888   return isInt<32>(Imm);
12889 }
12890
12891 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12892   if (!VT1.isInteger() || !VT2.isInteger())
12893     return false;
12894   unsigned NumBits1 = VT1.getSizeInBits();
12895   unsigned NumBits2 = VT2.getSizeInBits();
12896   return NumBits1 > NumBits2;
12897 }
12898
12899 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12900   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12901   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12902 }
12903
12904 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12905   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12906   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12907 }
12908
12909 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12910   EVT VT1 = Val.getValueType();
12911   if (isZExtFree(VT1, VT2))
12912     return true;
12913
12914   if (Val.getOpcode() != ISD::LOAD)
12915     return false;
12916
12917   if (!VT1.isSimple() || !VT1.isInteger() ||
12918       !VT2.isSimple() || !VT2.isInteger())
12919     return false;
12920
12921   switch (VT1.getSimpleVT().SimpleTy) {
12922   default: break;
12923   case MVT::i8:
12924   case MVT::i16:
12925   case MVT::i32:
12926     // X86 has 8, 16, and 32-bit zero-extending loads.
12927     return true;
12928   }
12929
12930   return false;
12931 }
12932
12933 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12934   // i16 instructions are longer (0x66 prefix) and potentially slower.
12935   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12936 }
12937
12938 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12939 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12940 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12941 /// are assumed to be legal.
12942 bool
12943 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12944                                       EVT VT) const {
12945   // Very little shuffling can be done for 64-bit vectors right now.
12946   if (VT.getSizeInBits() == 64)
12947     return false;
12948
12949   // FIXME: pshufb, blends, shifts.
12950   return (VT.getVectorNumElements() == 2 ||
12951           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12952           isMOVLMask(M, VT) ||
12953           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12954           isPSHUFDMask(M, VT) ||
12955           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12956           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12957           isPALIGNRMask(M, VT, Subtarget) ||
12958           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12959           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12960           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12961           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12962 }
12963
12964 bool
12965 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12966                                           EVT VT) const {
12967   unsigned NumElts = VT.getVectorNumElements();
12968   // FIXME: This collection of masks seems suspect.
12969   if (NumElts == 2)
12970     return true;
12971   if (NumElts == 4 && VT.is128BitVector()) {
12972     return (isMOVLMask(Mask, VT)  ||
12973             isCommutedMOVLMask(Mask, VT, true) ||
12974             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12975             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12976   }
12977   return false;
12978 }
12979
12980 //===----------------------------------------------------------------------===//
12981 //                           X86 Scheduler Hooks
12982 //===----------------------------------------------------------------------===//
12983
12984 /// Utility function to emit xbegin specifying the start of an RTM region.
12985 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12986                                      const TargetInstrInfo *TII) {
12987   DebugLoc DL = MI->getDebugLoc();
12988
12989   const BasicBlock *BB = MBB->getBasicBlock();
12990   MachineFunction::iterator I = MBB;
12991   ++I;
12992
12993   // For the v = xbegin(), we generate
12994   //
12995   // thisMBB:
12996   //  xbegin sinkMBB
12997   //
12998   // mainMBB:
12999   //  eax = -1
13000   //
13001   // sinkMBB:
13002   //  v = eax
13003
13004   MachineBasicBlock *thisMBB = MBB;
13005   MachineFunction *MF = MBB->getParent();
13006   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13007   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13008   MF->insert(I, mainMBB);
13009   MF->insert(I, sinkMBB);
13010
13011   // Transfer the remainder of BB and its successor edges to sinkMBB.
13012   sinkMBB->splice(sinkMBB->begin(), MBB,
13013                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13014   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13015
13016   // thisMBB:
13017   //  xbegin sinkMBB
13018   //  # fallthrough to mainMBB
13019   //  # abortion to sinkMBB
13020   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13021   thisMBB->addSuccessor(mainMBB);
13022   thisMBB->addSuccessor(sinkMBB);
13023
13024   // mainMBB:
13025   //  EAX = -1
13026   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13027   mainMBB->addSuccessor(sinkMBB);
13028
13029   // sinkMBB:
13030   // EAX is live into the sinkMBB
13031   sinkMBB->addLiveIn(X86::EAX);
13032   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13033           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13034     .addReg(X86::EAX);
13035
13036   MI->eraseFromParent();
13037   return sinkMBB;
13038 }
13039
13040 // Get CMPXCHG opcode for the specified data type.
13041 static unsigned getCmpXChgOpcode(EVT VT) {
13042   switch (VT.getSimpleVT().SimpleTy) {
13043   case MVT::i8:  return X86::LCMPXCHG8;
13044   case MVT::i16: return X86::LCMPXCHG16;
13045   case MVT::i32: return X86::LCMPXCHG32;
13046   case MVT::i64: return X86::LCMPXCHG64;
13047   default:
13048     break;
13049   }
13050   llvm_unreachable("Invalid operand size!");
13051 }
13052
13053 // Get LOAD opcode for the specified data type.
13054 static unsigned getLoadOpcode(EVT VT) {
13055   switch (VT.getSimpleVT().SimpleTy) {
13056   case MVT::i8:  return X86::MOV8rm;
13057   case MVT::i16: return X86::MOV16rm;
13058   case MVT::i32: return X86::MOV32rm;
13059   case MVT::i64: return X86::MOV64rm;
13060   default:
13061     break;
13062   }
13063   llvm_unreachable("Invalid operand size!");
13064 }
13065
13066 // Get opcode of the non-atomic one from the specified atomic instruction.
13067 static unsigned getNonAtomicOpcode(unsigned Opc) {
13068   switch (Opc) {
13069   case X86::ATOMAND8:  return X86::AND8rr;
13070   case X86::ATOMAND16: return X86::AND16rr;
13071   case X86::ATOMAND32: return X86::AND32rr;
13072   case X86::ATOMAND64: return X86::AND64rr;
13073   case X86::ATOMOR8:   return X86::OR8rr;
13074   case X86::ATOMOR16:  return X86::OR16rr;
13075   case X86::ATOMOR32:  return X86::OR32rr;
13076   case X86::ATOMOR64:  return X86::OR64rr;
13077   case X86::ATOMXOR8:  return X86::XOR8rr;
13078   case X86::ATOMXOR16: return X86::XOR16rr;
13079   case X86::ATOMXOR32: return X86::XOR32rr;
13080   case X86::ATOMXOR64: return X86::XOR64rr;
13081   }
13082   llvm_unreachable("Unhandled atomic-load-op opcode!");
13083 }
13084
13085 // Get opcode of the non-atomic one from the specified atomic instruction with
13086 // extra opcode.
13087 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13088                                                unsigned &ExtraOpc) {
13089   switch (Opc) {
13090   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13091   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13092   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13093   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13094   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13095   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13096   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13097   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13098   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13099   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13100   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13101   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13102   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13103   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13104   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13105   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13106   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13107   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13108   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13109   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13110   }
13111   llvm_unreachable("Unhandled atomic-load-op opcode!");
13112 }
13113
13114 // Get opcode of the non-atomic one from the specified atomic instruction for
13115 // 64-bit data type on 32-bit target.
13116 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13117   switch (Opc) {
13118   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13119   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13120   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13121   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13122   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13123   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13124   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13125   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13126   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13127   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13128   }
13129   llvm_unreachable("Unhandled atomic-load-op opcode!");
13130 }
13131
13132 // Get opcode of the non-atomic one from the specified atomic instruction for
13133 // 64-bit data type on 32-bit target with extra opcode.
13134 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13135                                                    unsigned &HiOpc,
13136                                                    unsigned &ExtraOpc) {
13137   switch (Opc) {
13138   case X86::ATOMNAND6432:
13139     ExtraOpc = X86::NOT32r;
13140     HiOpc = X86::AND32rr;
13141     return X86::AND32rr;
13142   }
13143   llvm_unreachable("Unhandled atomic-load-op opcode!");
13144 }
13145
13146 // Get pseudo CMOV opcode from the specified data type.
13147 static unsigned getPseudoCMOVOpc(EVT VT) {
13148   switch (VT.getSimpleVT().SimpleTy) {
13149   case MVT::i8:  return X86::CMOV_GR8;
13150   case MVT::i16: return X86::CMOV_GR16;
13151   case MVT::i32: return X86::CMOV_GR32;
13152   default:
13153     break;
13154   }
13155   llvm_unreachable("Unknown CMOV opcode!");
13156 }
13157
13158 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13159 // They will be translated into a spin-loop or compare-exchange loop from
13160 //
13161 //    ...
13162 //    dst = atomic-fetch-op MI.addr, MI.val
13163 //    ...
13164 //
13165 // to
13166 //
13167 //    ...
13168 //    t1 = LOAD MI.addr
13169 // loop:
13170 //    t4 = phi(t1, t3 / loop)
13171 //    t2 = OP MI.val, t4
13172 //    EAX = t4
13173 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13174 //    t3 = EAX
13175 //    JNE loop
13176 // sink:
13177 //    dst = t3
13178 //    ...
13179 MachineBasicBlock *
13180 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13181                                        MachineBasicBlock *MBB) const {
13182   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13183   DebugLoc DL = MI->getDebugLoc();
13184
13185   MachineFunction *MF = MBB->getParent();
13186   MachineRegisterInfo &MRI = MF->getRegInfo();
13187
13188   const BasicBlock *BB = MBB->getBasicBlock();
13189   MachineFunction::iterator I = MBB;
13190   ++I;
13191
13192   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13193          "Unexpected number of operands");
13194
13195   assert(MI->hasOneMemOperand() &&
13196          "Expected atomic-load-op to have one memoperand");
13197
13198   // Memory Reference
13199   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13200   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13201
13202   unsigned DstReg, SrcReg;
13203   unsigned MemOpndSlot;
13204
13205   unsigned CurOp = 0;
13206
13207   DstReg = MI->getOperand(CurOp++).getReg();
13208   MemOpndSlot = CurOp;
13209   CurOp += X86::AddrNumOperands;
13210   SrcReg = MI->getOperand(CurOp++).getReg();
13211
13212   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13213   MVT::SimpleValueType VT = *RC->vt_begin();
13214   unsigned t1 = MRI.createVirtualRegister(RC);
13215   unsigned t2 = MRI.createVirtualRegister(RC);
13216   unsigned t3 = MRI.createVirtualRegister(RC);
13217   unsigned t4 = MRI.createVirtualRegister(RC);
13218   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13219
13220   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13221   unsigned LOADOpc = getLoadOpcode(VT);
13222
13223   // For the atomic load-arith operator, we generate
13224   //
13225   //  thisMBB:
13226   //    t1 = LOAD [MI.addr]
13227   //  mainMBB:
13228   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13229   //    t1 = OP MI.val, EAX
13230   //    EAX = t4
13231   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13232   //    t3 = EAX
13233   //    JNE mainMBB
13234   //  sinkMBB:
13235   //    dst = t3
13236
13237   MachineBasicBlock *thisMBB = MBB;
13238   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13239   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13240   MF->insert(I, mainMBB);
13241   MF->insert(I, sinkMBB);
13242
13243   MachineInstrBuilder MIB;
13244
13245   // Transfer the remainder of BB and its successor edges to sinkMBB.
13246   sinkMBB->splice(sinkMBB->begin(), MBB,
13247                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13248   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13249
13250   // thisMBB:
13251   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13252   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13253     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13254     if (NewMO.isReg())
13255       NewMO.setIsKill(false);
13256     MIB.addOperand(NewMO);
13257   }
13258   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13259     unsigned flags = (*MMOI)->getFlags();
13260     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13261     MachineMemOperand *MMO =
13262       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13263                                (*MMOI)->getSize(),
13264                                (*MMOI)->getBaseAlignment(),
13265                                (*MMOI)->getTBAAInfo(),
13266                                (*MMOI)->getRanges());
13267     MIB.addMemOperand(MMO);
13268   }
13269
13270   thisMBB->addSuccessor(mainMBB);
13271
13272   // mainMBB:
13273   MachineBasicBlock *origMainMBB = mainMBB;
13274
13275   // Add a PHI.
13276   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13277                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13278
13279   unsigned Opc = MI->getOpcode();
13280   switch (Opc) {
13281   default:
13282     llvm_unreachable("Unhandled atomic-load-op opcode!");
13283   case X86::ATOMAND8:
13284   case X86::ATOMAND16:
13285   case X86::ATOMAND32:
13286   case X86::ATOMAND64:
13287   case X86::ATOMOR8:
13288   case X86::ATOMOR16:
13289   case X86::ATOMOR32:
13290   case X86::ATOMOR64:
13291   case X86::ATOMXOR8:
13292   case X86::ATOMXOR16:
13293   case X86::ATOMXOR32:
13294   case X86::ATOMXOR64: {
13295     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13296     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13297       .addReg(t4);
13298     break;
13299   }
13300   case X86::ATOMNAND8:
13301   case X86::ATOMNAND16:
13302   case X86::ATOMNAND32:
13303   case X86::ATOMNAND64: {
13304     unsigned Tmp = MRI.createVirtualRegister(RC);
13305     unsigned NOTOpc;
13306     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13307     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13308       .addReg(t4);
13309     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13310     break;
13311   }
13312   case X86::ATOMMAX8:
13313   case X86::ATOMMAX16:
13314   case X86::ATOMMAX32:
13315   case X86::ATOMMAX64:
13316   case X86::ATOMMIN8:
13317   case X86::ATOMMIN16:
13318   case X86::ATOMMIN32:
13319   case X86::ATOMMIN64:
13320   case X86::ATOMUMAX8:
13321   case X86::ATOMUMAX16:
13322   case X86::ATOMUMAX32:
13323   case X86::ATOMUMAX64:
13324   case X86::ATOMUMIN8:
13325   case X86::ATOMUMIN16:
13326   case X86::ATOMUMIN32:
13327   case X86::ATOMUMIN64: {
13328     unsigned CMPOpc;
13329     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13330
13331     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13332       .addReg(SrcReg)
13333       .addReg(t4);
13334
13335     if (Subtarget->hasCMov()) {
13336       if (VT != MVT::i8) {
13337         // Native support
13338         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13339           .addReg(SrcReg)
13340           .addReg(t4);
13341       } else {
13342         // Promote i8 to i32 to use CMOV32
13343         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13344         const TargetRegisterClass *RC32 =
13345           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13346         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13347         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13348         unsigned Tmp = MRI.createVirtualRegister(RC32);
13349
13350         unsigned Undef = MRI.createVirtualRegister(RC32);
13351         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13352
13353         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13354           .addReg(Undef)
13355           .addReg(SrcReg)
13356           .addImm(X86::sub_8bit);
13357         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13358           .addReg(Undef)
13359           .addReg(t4)
13360           .addImm(X86::sub_8bit);
13361
13362         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13363           .addReg(SrcReg32)
13364           .addReg(AccReg32);
13365
13366         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13367           .addReg(Tmp, 0, X86::sub_8bit);
13368       }
13369     } else {
13370       // Use pseudo select and lower them.
13371       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13372              "Invalid atomic-load-op transformation!");
13373       unsigned SelOpc = getPseudoCMOVOpc(VT);
13374       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13375       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13376       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13377               .addReg(SrcReg).addReg(t4)
13378               .addImm(CC);
13379       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13380       // Replace the original PHI node as mainMBB is changed after CMOV
13381       // lowering.
13382       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13383         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13384       Phi->eraseFromParent();
13385     }
13386     break;
13387   }
13388   }
13389
13390   // Copy PhyReg back from virtual register.
13391   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13392     .addReg(t4);
13393
13394   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13395   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13396     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13397     if (NewMO.isReg())
13398       NewMO.setIsKill(false);
13399     MIB.addOperand(NewMO);
13400   }
13401   MIB.addReg(t2);
13402   MIB.setMemRefs(MMOBegin, MMOEnd);
13403
13404   // Copy PhyReg back to virtual register.
13405   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13406     .addReg(PhyReg);
13407
13408   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13409
13410   mainMBB->addSuccessor(origMainMBB);
13411   mainMBB->addSuccessor(sinkMBB);
13412
13413   // sinkMBB:
13414   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13415           TII->get(TargetOpcode::COPY), DstReg)
13416     .addReg(t3);
13417
13418   MI->eraseFromParent();
13419   return sinkMBB;
13420 }
13421
13422 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13423 // instructions. They will be translated into a spin-loop or compare-exchange
13424 // loop from
13425 //
13426 //    ...
13427 //    dst = atomic-fetch-op MI.addr, MI.val
13428 //    ...
13429 //
13430 // to
13431 //
13432 //    ...
13433 //    t1L = LOAD [MI.addr + 0]
13434 //    t1H = LOAD [MI.addr + 4]
13435 // loop:
13436 //    t4L = phi(t1L, t3L / loop)
13437 //    t4H = phi(t1H, t3H / loop)
13438 //    t2L = OP MI.val.lo, t4L
13439 //    t2H = OP MI.val.hi, t4H
13440 //    EAX = t4L
13441 //    EDX = t4H
13442 //    EBX = t2L
13443 //    ECX = t2H
13444 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13445 //    t3L = EAX
13446 //    t3H = EDX
13447 //    JNE loop
13448 // sink:
13449 //    dstL = t3L
13450 //    dstH = t3H
13451 //    ...
13452 MachineBasicBlock *
13453 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13454                                            MachineBasicBlock *MBB) const {
13455   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13456   DebugLoc DL = MI->getDebugLoc();
13457
13458   MachineFunction *MF = MBB->getParent();
13459   MachineRegisterInfo &MRI = MF->getRegInfo();
13460
13461   const BasicBlock *BB = MBB->getBasicBlock();
13462   MachineFunction::iterator I = MBB;
13463   ++I;
13464
13465   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13466          "Unexpected number of operands");
13467
13468   assert(MI->hasOneMemOperand() &&
13469          "Expected atomic-load-op32 to have one memoperand");
13470
13471   // Memory Reference
13472   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13473   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13474
13475   unsigned DstLoReg, DstHiReg;
13476   unsigned SrcLoReg, SrcHiReg;
13477   unsigned MemOpndSlot;
13478
13479   unsigned CurOp = 0;
13480
13481   DstLoReg = MI->getOperand(CurOp++).getReg();
13482   DstHiReg = MI->getOperand(CurOp++).getReg();
13483   MemOpndSlot = CurOp;
13484   CurOp += X86::AddrNumOperands;
13485   SrcLoReg = MI->getOperand(CurOp++).getReg();
13486   SrcHiReg = MI->getOperand(CurOp++).getReg();
13487
13488   const TargetRegisterClass *RC = &X86::GR32RegClass;
13489   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13490
13491   unsigned t1L = MRI.createVirtualRegister(RC);
13492   unsigned t1H = MRI.createVirtualRegister(RC);
13493   unsigned t2L = MRI.createVirtualRegister(RC);
13494   unsigned t2H = MRI.createVirtualRegister(RC);
13495   unsigned t3L = MRI.createVirtualRegister(RC);
13496   unsigned t3H = MRI.createVirtualRegister(RC);
13497   unsigned t4L = MRI.createVirtualRegister(RC);
13498   unsigned t4H = MRI.createVirtualRegister(RC);
13499
13500   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13501   unsigned LOADOpc = X86::MOV32rm;
13502
13503   // For the atomic load-arith operator, we generate
13504   //
13505   //  thisMBB:
13506   //    t1L = LOAD [MI.addr + 0]
13507   //    t1H = LOAD [MI.addr + 4]
13508   //  mainMBB:
13509   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13510   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13511   //    t2L = OP MI.val.lo, t4L
13512   //    t2H = OP MI.val.hi, t4H
13513   //    EBX = t2L
13514   //    ECX = t2H
13515   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13516   //    t3L = EAX
13517   //    t3H = EDX
13518   //    JNE loop
13519   //  sinkMBB:
13520   //    dstL = t3L
13521   //    dstH = t3H
13522
13523   MachineBasicBlock *thisMBB = MBB;
13524   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13525   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13526   MF->insert(I, mainMBB);
13527   MF->insert(I, sinkMBB);
13528
13529   MachineInstrBuilder MIB;
13530
13531   // Transfer the remainder of BB and its successor edges to sinkMBB.
13532   sinkMBB->splice(sinkMBB->begin(), MBB,
13533                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13534   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13535
13536   // thisMBB:
13537   // Lo
13538   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13539   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13540     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13541     if (NewMO.isReg())
13542       NewMO.setIsKill(false);
13543     MIB.addOperand(NewMO);
13544   }
13545   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13546     unsigned flags = (*MMOI)->getFlags();
13547     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13548     MachineMemOperand *MMO =
13549       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13550                                (*MMOI)->getSize(),
13551                                (*MMOI)->getBaseAlignment(),
13552                                (*MMOI)->getTBAAInfo(),
13553                                (*MMOI)->getRanges());
13554     MIB.addMemOperand(MMO);
13555   };
13556   MachineInstr *LowMI = MIB;
13557
13558   // Hi
13559   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13560   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13561     if (i == X86::AddrDisp) {
13562       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13563     } else {
13564       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13565       if (NewMO.isReg())
13566         NewMO.setIsKill(false);
13567       MIB.addOperand(NewMO);
13568     }
13569   }
13570   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13571
13572   thisMBB->addSuccessor(mainMBB);
13573
13574   // mainMBB:
13575   MachineBasicBlock *origMainMBB = mainMBB;
13576
13577   // Add PHIs.
13578   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13579                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13580   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13581                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13582
13583   unsigned Opc = MI->getOpcode();
13584   switch (Opc) {
13585   default:
13586     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13587   case X86::ATOMAND6432:
13588   case X86::ATOMOR6432:
13589   case X86::ATOMXOR6432:
13590   case X86::ATOMADD6432:
13591   case X86::ATOMSUB6432: {
13592     unsigned HiOpc;
13593     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13594     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13595       .addReg(SrcLoReg);
13596     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13597       .addReg(SrcHiReg);
13598     break;
13599   }
13600   case X86::ATOMNAND6432: {
13601     unsigned HiOpc, NOTOpc;
13602     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13603     unsigned TmpL = MRI.createVirtualRegister(RC);
13604     unsigned TmpH = MRI.createVirtualRegister(RC);
13605     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13606       .addReg(t4L);
13607     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13608       .addReg(t4H);
13609     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13610     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13611     break;
13612   }
13613   case X86::ATOMMAX6432:
13614   case X86::ATOMMIN6432:
13615   case X86::ATOMUMAX6432:
13616   case X86::ATOMUMIN6432: {
13617     unsigned HiOpc;
13618     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13619     unsigned cL = MRI.createVirtualRegister(RC8);
13620     unsigned cH = MRI.createVirtualRegister(RC8);
13621     unsigned cL32 = MRI.createVirtualRegister(RC);
13622     unsigned cH32 = MRI.createVirtualRegister(RC);
13623     unsigned cc = MRI.createVirtualRegister(RC);
13624     // cl := cmp src_lo, lo
13625     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13626       .addReg(SrcLoReg).addReg(t4L);
13627     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13628     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13629     // ch := cmp src_hi, hi
13630     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13631       .addReg(SrcHiReg).addReg(t4H);
13632     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13633     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13634     // cc := if (src_hi == hi) ? cl : ch;
13635     if (Subtarget->hasCMov()) {
13636       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13637         .addReg(cH32).addReg(cL32);
13638     } else {
13639       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13640               .addReg(cH32).addReg(cL32)
13641               .addImm(X86::COND_E);
13642       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13643     }
13644     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13645     if (Subtarget->hasCMov()) {
13646       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13647         .addReg(SrcLoReg).addReg(t4L);
13648       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13649         .addReg(SrcHiReg).addReg(t4H);
13650     } else {
13651       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13652               .addReg(SrcLoReg).addReg(t4L)
13653               .addImm(X86::COND_NE);
13654       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13655       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13656       // 2nd CMOV lowering.
13657       mainMBB->addLiveIn(X86::EFLAGS);
13658       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13659               .addReg(SrcHiReg).addReg(t4H)
13660               .addImm(X86::COND_NE);
13661       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13662       // Replace the original PHI node as mainMBB is changed after CMOV
13663       // lowering.
13664       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13665         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13666       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13667         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13668       PhiL->eraseFromParent();
13669       PhiH->eraseFromParent();
13670     }
13671     break;
13672   }
13673   case X86::ATOMSWAP6432: {
13674     unsigned HiOpc;
13675     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13676     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13677     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13678     break;
13679   }
13680   }
13681
13682   // Copy EDX:EAX back from HiReg:LoReg
13683   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13684   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13685   // Copy ECX:EBX from t1H:t1L
13686   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13687   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13688
13689   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13690   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13691     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13692     if (NewMO.isReg())
13693       NewMO.setIsKill(false);
13694     MIB.addOperand(NewMO);
13695   }
13696   MIB.setMemRefs(MMOBegin, MMOEnd);
13697
13698   // Copy EDX:EAX back to t3H:t3L
13699   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13700   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13701
13702   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13703
13704   mainMBB->addSuccessor(origMainMBB);
13705   mainMBB->addSuccessor(sinkMBB);
13706
13707   // sinkMBB:
13708   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13709           TII->get(TargetOpcode::COPY), DstLoReg)
13710     .addReg(t3L);
13711   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13712           TII->get(TargetOpcode::COPY), DstHiReg)
13713     .addReg(t3H);
13714
13715   MI->eraseFromParent();
13716   return sinkMBB;
13717 }
13718
13719 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13720 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13721 // in the .td file.
13722 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13723                                        const TargetInstrInfo *TII) {
13724   unsigned Opc;
13725   switch (MI->getOpcode()) {
13726   default: llvm_unreachable("illegal opcode!");
13727   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13728   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13729   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13730   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13731   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13732   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13733   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13734   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13735   }
13736
13737   DebugLoc dl = MI->getDebugLoc();
13738   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13739
13740   unsigned NumArgs = MI->getNumOperands();
13741   for (unsigned i = 1; i < NumArgs; ++i) {
13742     MachineOperand &Op = MI->getOperand(i);
13743     if (!(Op.isReg() && Op.isImplicit()))
13744       MIB.addOperand(Op);
13745   }
13746   if (MI->hasOneMemOperand())
13747     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13748
13749   BuildMI(*BB, MI, dl,
13750     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13751     .addReg(X86::XMM0);
13752
13753   MI->eraseFromParent();
13754   return BB;
13755 }
13756
13757 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13758 // defs in an instruction pattern
13759 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13760                                        const TargetInstrInfo *TII) {
13761   unsigned Opc;
13762   switch (MI->getOpcode()) {
13763   default: llvm_unreachable("illegal opcode!");
13764   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13765   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13766   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13767   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13768   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13769   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13770   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13771   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13772   }
13773
13774   DebugLoc dl = MI->getDebugLoc();
13775   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13776
13777   unsigned NumArgs = MI->getNumOperands(); // remove the results
13778   for (unsigned i = 1; i < NumArgs; ++i) {
13779     MachineOperand &Op = MI->getOperand(i);
13780     if (!(Op.isReg() && Op.isImplicit()))
13781       MIB.addOperand(Op);
13782   }
13783   if (MI->hasOneMemOperand())
13784     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13785
13786   BuildMI(*BB, MI, dl,
13787     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13788     .addReg(X86::ECX);
13789
13790   MI->eraseFromParent();
13791   return BB;
13792 }
13793
13794 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13795                                        const TargetInstrInfo *TII,
13796                                        const X86Subtarget* Subtarget) {
13797   DebugLoc dl = MI->getDebugLoc();
13798
13799   // Address into RAX/EAX, other two args into ECX, EDX.
13800   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13801   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13802   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13803   for (int i = 0; i < X86::AddrNumOperands; ++i)
13804     MIB.addOperand(MI->getOperand(i));
13805
13806   unsigned ValOps = X86::AddrNumOperands;
13807   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13808     .addReg(MI->getOperand(ValOps).getReg());
13809   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13810     .addReg(MI->getOperand(ValOps+1).getReg());
13811
13812   // The instruction doesn't actually take any operands though.
13813   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13814
13815   MI->eraseFromParent(); // The pseudo is gone now.
13816   return BB;
13817 }
13818
13819 MachineBasicBlock *
13820 X86TargetLowering::EmitVAARG64WithCustomInserter(
13821                    MachineInstr *MI,
13822                    MachineBasicBlock *MBB) const {
13823   // Emit va_arg instruction on X86-64.
13824
13825   // Operands to this pseudo-instruction:
13826   // 0  ) Output        : destination address (reg)
13827   // 1-5) Input         : va_list address (addr, i64mem)
13828   // 6  ) ArgSize       : Size (in bytes) of vararg type
13829   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13830   // 8  ) Align         : Alignment of type
13831   // 9  ) EFLAGS (implicit-def)
13832
13833   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13834   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13835
13836   unsigned DestReg = MI->getOperand(0).getReg();
13837   MachineOperand &Base = MI->getOperand(1);
13838   MachineOperand &Scale = MI->getOperand(2);
13839   MachineOperand &Index = MI->getOperand(3);
13840   MachineOperand &Disp = MI->getOperand(4);
13841   MachineOperand &Segment = MI->getOperand(5);
13842   unsigned ArgSize = MI->getOperand(6).getImm();
13843   unsigned ArgMode = MI->getOperand(7).getImm();
13844   unsigned Align = MI->getOperand(8).getImm();
13845
13846   // Memory Reference
13847   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13848   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13849   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13850
13851   // Machine Information
13852   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13853   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13854   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13855   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13856   DebugLoc DL = MI->getDebugLoc();
13857
13858   // struct va_list {
13859   //   i32   gp_offset
13860   //   i32   fp_offset
13861   //   i64   overflow_area (address)
13862   //   i64   reg_save_area (address)
13863   // }
13864   // sizeof(va_list) = 24
13865   // alignment(va_list) = 8
13866
13867   unsigned TotalNumIntRegs = 6;
13868   unsigned TotalNumXMMRegs = 8;
13869   bool UseGPOffset = (ArgMode == 1);
13870   bool UseFPOffset = (ArgMode == 2);
13871   unsigned MaxOffset = TotalNumIntRegs * 8 +
13872                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13873
13874   /* Align ArgSize to a multiple of 8 */
13875   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13876   bool NeedsAlign = (Align > 8);
13877
13878   MachineBasicBlock *thisMBB = MBB;
13879   MachineBasicBlock *overflowMBB;
13880   MachineBasicBlock *offsetMBB;
13881   MachineBasicBlock *endMBB;
13882
13883   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13884   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13885   unsigned OffsetReg = 0;
13886
13887   if (!UseGPOffset && !UseFPOffset) {
13888     // If we only pull from the overflow region, we don't create a branch.
13889     // We don't need to alter control flow.
13890     OffsetDestReg = 0; // unused
13891     OverflowDestReg = DestReg;
13892
13893     offsetMBB = NULL;
13894     overflowMBB = thisMBB;
13895     endMBB = thisMBB;
13896   } else {
13897     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13898     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13899     // If not, pull from overflow_area. (branch to overflowMBB)
13900     //
13901     //       thisMBB
13902     //         |     .
13903     //         |        .
13904     //     offsetMBB   overflowMBB
13905     //         |        .
13906     //         |     .
13907     //        endMBB
13908
13909     // Registers for the PHI in endMBB
13910     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13911     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13912
13913     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13914     MachineFunction *MF = MBB->getParent();
13915     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13916     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13917     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13918
13919     MachineFunction::iterator MBBIter = MBB;
13920     ++MBBIter;
13921
13922     // Insert the new basic blocks
13923     MF->insert(MBBIter, offsetMBB);
13924     MF->insert(MBBIter, overflowMBB);
13925     MF->insert(MBBIter, endMBB);
13926
13927     // Transfer the remainder of MBB and its successor edges to endMBB.
13928     endMBB->splice(endMBB->begin(), thisMBB,
13929                     llvm::next(MachineBasicBlock::iterator(MI)),
13930                     thisMBB->end());
13931     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13932
13933     // Make offsetMBB and overflowMBB successors of thisMBB
13934     thisMBB->addSuccessor(offsetMBB);
13935     thisMBB->addSuccessor(overflowMBB);
13936
13937     // endMBB is a successor of both offsetMBB and overflowMBB
13938     offsetMBB->addSuccessor(endMBB);
13939     overflowMBB->addSuccessor(endMBB);
13940
13941     // Load the offset value into a register
13942     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13943     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13944       .addOperand(Base)
13945       .addOperand(Scale)
13946       .addOperand(Index)
13947       .addDisp(Disp, UseFPOffset ? 4 : 0)
13948       .addOperand(Segment)
13949       .setMemRefs(MMOBegin, MMOEnd);
13950
13951     // Check if there is enough room left to pull this argument.
13952     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13953       .addReg(OffsetReg)
13954       .addImm(MaxOffset + 8 - ArgSizeA8);
13955
13956     // Branch to "overflowMBB" if offset >= max
13957     // Fall through to "offsetMBB" otherwise
13958     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13959       .addMBB(overflowMBB);
13960   }
13961
13962   // In offsetMBB, emit code to use the reg_save_area.
13963   if (offsetMBB) {
13964     assert(OffsetReg != 0);
13965
13966     // Read the reg_save_area address.
13967     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13968     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13969       .addOperand(Base)
13970       .addOperand(Scale)
13971       .addOperand(Index)
13972       .addDisp(Disp, 16)
13973       .addOperand(Segment)
13974       .setMemRefs(MMOBegin, MMOEnd);
13975
13976     // Zero-extend the offset
13977     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13978       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13979         .addImm(0)
13980         .addReg(OffsetReg)
13981         .addImm(X86::sub_32bit);
13982
13983     // Add the offset to the reg_save_area to get the final address.
13984     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13985       .addReg(OffsetReg64)
13986       .addReg(RegSaveReg);
13987
13988     // Compute the offset for the next argument
13989     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13990     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13991       .addReg(OffsetReg)
13992       .addImm(UseFPOffset ? 16 : 8);
13993
13994     // Store it back into the va_list.
13995     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13996       .addOperand(Base)
13997       .addOperand(Scale)
13998       .addOperand(Index)
13999       .addDisp(Disp, UseFPOffset ? 4 : 0)
14000       .addOperand(Segment)
14001       .addReg(NextOffsetReg)
14002       .setMemRefs(MMOBegin, MMOEnd);
14003
14004     // Jump to endMBB
14005     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14006       .addMBB(endMBB);
14007   }
14008
14009   //
14010   // Emit code to use overflow area
14011   //
14012
14013   // Load the overflow_area address into a register.
14014   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14015   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14016     .addOperand(Base)
14017     .addOperand(Scale)
14018     .addOperand(Index)
14019     .addDisp(Disp, 8)
14020     .addOperand(Segment)
14021     .setMemRefs(MMOBegin, MMOEnd);
14022
14023   // If we need to align it, do so. Otherwise, just copy the address
14024   // to OverflowDestReg.
14025   if (NeedsAlign) {
14026     // Align the overflow address
14027     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14028     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14029
14030     // aligned_addr = (addr + (align-1)) & ~(align-1)
14031     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14032       .addReg(OverflowAddrReg)
14033       .addImm(Align-1);
14034
14035     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14036       .addReg(TmpReg)
14037       .addImm(~(uint64_t)(Align-1));
14038   } else {
14039     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14040       .addReg(OverflowAddrReg);
14041   }
14042
14043   // Compute the next overflow address after this argument.
14044   // (the overflow address should be kept 8-byte aligned)
14045   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14046   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14047     .addReg(OverflowDestReg)
14048     .addImm(ArgSizeA8);
14049
14050   // Store the new overflow address.
14051   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14052     .addOperand(Base)
14053     .addOperand(Scale)
14054     .addOperand(Index)
14055     .addDisp(Disp, 8)
14056     .addOperand(Segment)
14057     .addReg(NextAddrReg)
14058     .setMemRefs(MMOBegin, MMOEnd);
14059
14060   // If we branched, emit the PHI to the front of endMBB.
14061   if (offsetMBB) {
14062     BuildMI(*endMBB, endMBB->begin(), DL,
14063             TII->get(X86::PHI), DestReg)
14064       .addReg(OffsetDestReg).addMBB(offsetMBB)
14065       .addReg(OverflowDestReg).addMBB(overflowMBB);
14066   }
14067
14068   // Erase the pseudo instruction
14069   MI->eraseFromParent();
14070
14071   return endMBB;
14072 }
14073
14074 MachineBasicBlock *
14075 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14076                                                  MachineInstr *MI,
14077                                                  MachineBasicBlock *MBB) const {
14078   // Emit code to save XMM registers to the stack. The ABI says that the
14079   // number of registers to save is given in %al, so it's theoretically
14080   // possible to do an indirect jump trick to avoid saving all of them,
14081   // however this code takes a simpler approach and just executes all
14082   // of the stores if %al is non-zero. It's less code, and it's probably
14083   // easier on the hardware branch predictor, and stores aren't all that
14084   // expensive anyway.
14085
14086   // Create the new basic blocks. One block contains all the XMM stores,
14087   // and one block is the final destination regardless of whether any
14088   // stores were performed.
14089   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14090   MachineFunction *F = MBB->getParent();
14091   MachineFunction::iterator MBBIter = MBB;
14092   ++MBBIter;
14093   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14094   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14095   F->insert(MBBIter, XMMSaveMBB);
14096   F->insert(MBBIter, EndMBB);
14097
14098   // Transfer the remainder of MBB and its successor edges to EndMBB.
14099   EndMBB->splice(EndMBB->begin(), MBB,
14100                  llvm::next(MachineBasicBlock::iterator(MI)),
14101                  MBB->end());
14102   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14103
14104   // The original block will now fall through to the XMM save block.
14105   MBB->addSuccessor(XMMSaveMBB);
14106   // The XMMSaveMBB will fall through to the end block.
14107   XMMSaveMBB->addSuccessor(EndMBB);
14108
14109   // Now add the instructions.
14110   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14111   DebugLoc DL = MI->getDebugLoc();
14112
14113   unsigned CountReg = MI->getOperand(0).getReg();
14114   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14115   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14116
14117   if (!Subtarget->isTargetWin64()) {
14118     // If %al is 0, branch around the XMM save block.
14119     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14120     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14121     MBB->addSuccessor(EndMBB);
14122   }
14123
14124   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14125   // In the XMM save block, save all the XMM argument registers.
14126   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14127     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14128     MachineMemOperand *MMO =
14129       F->getMachineMemOperand(
14130           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14131         MachineMemOperand::MOStore,
14132         /*Size=*/16, /*Align=*/16);
14133     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14134       .addFrameIndex(RegSaveFrameIndex)
14135       .addImm(/*Scale=*/1)
14136       .addReg(/*IndexReg=*/0)
14137       .addImm(/*Disp=*/Offset)
14138       .addReg(/*Segment=*/0)
14139       .addReg(MI->getOperand(i).getReg())
14140       .addMemOperand(MMO);
14141   }
14142
14143   MI->eraseFromParent();   // The pseudo instruction is gone now.
14144
14145   return EndMBB;
14146 }
14147
14148 // The EFLAGS operand of SelectItr might be missing a kill marker
14149 // because there were multiple uses of EFLAGS, and ISel didn't know
14150 // which to mark. Figure out whether SelectItr should have had a
14151 // kill marker, and set it if it should. Returns the correct kill
14152 // marker value.
14153 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14154                                      MachineBasicBlock* BB,
14155                                      const TargetRegisterInfo* TRI) {
14156   // Scan forward through BB for a use/def of EFLAGS.
14157   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14158   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14159     const MachineInstr& mi = *miI;
14160     if (mi.readsRegister(X86::EFLAGS))
14161       return false;
14162     if (mi.definesRegister(X86::EFLAGS))
14163       break; // Should have kill-flag - update below.
14164   }
14165
14166   // If we hit the end of the block, check whether EFLAGS is live into a
14167   // successor.
14168   if (miI == BB->end()) {
14169     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14170                                           sEnd = BB->succ_end();
14171          sItr != sEnd; ++sItr) {
14172       MachineBasicBlock* succ = *sItr;
14173       if (succ->isLiveIn(X86::EFLAGS))
14174         return false;
14175     }
14176   }
14177
14178   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14179   // out. SelectMI should have a kill flag on EFLAGS.
14180   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14181   return true;
14182 }
14183
14184 MachineBasicBlock *
14185 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14186                                      MachineBasicBlock *BB) const {
14187   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14188   DebugLoc DL = MI->getDebugLoc();
14189
14190   // To "insert" a SELECT_CC instruction, we actually have to insert the
14191   // diamond control-flow pattern.  The incoming instruction knows the
14192   // destination vreg to set, the condition code register to branch on, the
14193   // true/false values to select between, and a branch opcode to use.
14194   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14195   MachineFunction::iterator It = BB;
14196   ++It;
14197
14198   //  thisMBB:
14199   //  ...
14200   //   TrueVal = ...
14201   //   cmpTY ccX, r1, r2
14202   //   bCC copy1MBB
14203   //   fallthrough --> copy0MBB
14204   MachineBasicBlock *thisMBB = BB;
14205   MachineFunction *F = BB->getParent();
14206   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14207   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14208   F->insert(It, copy0MBB);
14209   F->insert(It, sinkMBB);
14210
14211   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14212   // live into the sink and copy blocks.
14213   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14214   if (!MI->killsRegister(X86::EFLAGS) &&
14215       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14216     copy0MBB->addLiveIn(X86::EFLAGS);
14217     sinkMBB->addLiveIn(X86::EFLAGS);
14218   }
14219
14220   // Transfer the remainder of BB and its successor edges to sinkMBB.
14221   sinkMBB->splice(sinkMBB->begin(), BB,
14222                   llvm::next(MachineBasicBlock::iterator(MI)),
14223                   BB->end());
14224   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14225
14226   // Add the true and fallthrough blocks as its successors.
14227   BB->addSuccessor(copy0MBB);
14228   BB->addSuccessor(sinkMBB);
14229
14230   // Create the conditional branch instruction.
14231   unsigned Opc =
14232     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14233   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14234
14235   //  copy0MBB:
14236   //   %FalseValue = ...
14237   //   # fallthrough to sinkMBB
14238   copy0MBB->addSuccessor(sinkMBB);
14239
14240   //  sinkMBB:
14241   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14242   //  ...
14243   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14244           TII->get(X86::PHI), MI->getOperand(0).getReg())
14245     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14246     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14247
14248   MI->eraseFromParent();   // The pseudo instruction is gone now.
14249   return sinkMBB;
14250 }
14251
14252 MachineBasicBlock *
14253 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14254                                         bool Is64Bit) const {
14255   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14256   DebugLoc DL = MI->getDebugLoc();
14257   MachineFunction *MF = BB->getParent();
14258   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14259
14260   assert(getTargetMachine().Options.EnableSegmentedStacks);
14261
14262   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14263   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14264
14265   // BB:
14266   //  ... [Till the alloca]
14267   // If stacklet is not large enough, jump to mallocMBB
14268   //
14269   // bumpMBB:
14270   //  Allocate by subtracting from RSP
14271   //  Jump to continueMBB
14272   //
14273   // mallocMBB:
14274   //  Allocate by call to runtime
14275   //
14276   // continueMBB:
14277   //  ...
14278   //  [rest of original BB]
14279   //
14280
14281   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14282   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14283   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14284
14285   MachineRegisterInfo &MRI = MF->getRegInfo();
14286   const TargetRegisterClass *AddrRegClass =
14287     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14288
14289   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14290     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14291     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14292     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14293     sizeVReg = MI->getOperand(1).getReg(),
14294     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14295
14296   MachineFunction::iterator MBBIter = BB;
14297   ++MBBIter;
14298
14299   MF->insert(MBBIter, bumpMBB);
14300   MF->insert(MBBIter, mallocMBB);
14301   MF->insert(MBBIter, continueMBB);
14302
14303   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14304                       (MachineBasicBlock::iterator(MI)), BB->end());
14305   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14306
14307   // Add code to the main basic block to check if the stack limit has been hit,
14308   // and if so, jump to mallocMBB otherwise to bumpMBB.
14309   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14310   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14311     .addReg(tmpSPVReg).addReg(sizeVReg);
14312   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14313     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14314     .addReg(SPLimitVReg);
14315   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14316
14317   // bumpMBB simply decreases the stack pointer, since we know the current
14318   // stacklet has enough space.
14319   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14320     .addReg(SPLimitVReg);
14321   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14322     .addReg(SPLimitVReg);
14323   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14324
14325   // Calls into a routine in libgcc to allocate more space from the heap.
14326   const uint32_t *RegMask =
14327     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14328   if (Is64Bit) {
14329     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14330       .addReg(sizeVReg);
14331     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14332       .addExternalSymbol("__morestack_allocate_stack_space")
14333       .addRegMask(RegMask)
14334       .addReg(X86::RDI, RegState::Implicit)
14335       .addReg(X86::RAX, RegState::ImplicitDefine);
14336   } else {
14337     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14338       .addImm(12);
14339     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14340     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14341       .addExternalSymbol("__morestack_allocate_stack_space")
14342       .addRegMask(RegMask)
14343       .addReg(X86::EAX, RegState::ImplicitDefine);
14344   }
14345
14346   if (!Is64Bit)
14347     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14348       .addImm(16);
14349
14350   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14351     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14352   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14353
14354   // Set up the CFG correctly.
14355   BB->addSuccessor(bumpMBB);
14356   BB->addSuccessor(mallocMBB);
14357   mallocMBB->addSuccessor(continueMBB);
14358   bumpMBB->addSuccessor(continueMBB);
14359
14360   // Take care of the PHI nodes.
14361   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14362           MI->getOperand(0).getReg())
14363     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14364     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14365
14366   // Delete the original pseudo instruction.
14367   MI->eraseFromParent();
14368
14369   // And we're done.
14370   return continueMBB;
14371 }
14372
14373 MachineBasicBlock *
14374 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14375                                           MachineBasicBlock *BB) const {
14376   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14377   DebugLoc DL = MI->getDebugLoc();
14378
14379   assert(!Subtarget->isTargetEnvMacho());
14380
14381   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14382   // non-trivial part is impdef of ESP.
14383
14384   if (Subtarget->isTargetWin64()) {
14385     if (Subtarget->isTargetCygMing()) {
14386       // ___chkstk(Mingw64):
14387       // Clobbers R10, R11, RAX and EFLAGS.
14388       // Updates RSP.
14389       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14390         .addExternalSymbol("___chkstk")
14391         .addReg(X86::RAX, RegState::Implicit)
14392         .addReg(X86::RSP, RegState::Implicit)
14393         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14394         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14395         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14396     } else {
14397       // __chkstk(MSVCRT): does not update stack pointer.
14398       // Clobbers R10, R11 and EFLAGS.
14399       // FIXME: RAX(allocated size) might be reused and not killed.
14400       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14401         .addExternalSymbol("__chkstk")
14402         .addReg(X86::RAX, RegState::Implicit)
14403         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14404       // RAX has the offset to subtracted from RSP.
14405       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14406         .addReg(X86::RSP)
14407         .addReg(X86::RAX);
14408     }
14409   } else {
14410     const char *StackProbeSymbol =
14411       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14412
14413     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14414       .addExternalSymbol(StackProbeSymbol)
14415       .addReg(X86::EAX, RegState::Implicit)
14416       .addReg(X86::ESP, RegState::Implicit)
14417       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14418       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14419       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14420   }
14421
14422   MI->eraseFromParent();   // The pseudo instruction is gone now.
14423   return BB;
14424 }
14425
14426 MachineBasicBlock *
14427 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14428                                       MachineBasicBlock *BB) const {
14429   // This is pretty easy.  We're taking the value that we received from
14430   // our load from the relocation, sticking it in either RDI (x86-64)
14431   // or EAX and doing an indirect call.  The return value will then
14432   // be in the normal return register.
14433   const X86InstrInfo *TII
14434     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14435   DebugLoc DL = MI->getDebugLoc();
14436   MachineFunction *F = BB->getParent();
14437
14438   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14439   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14440
14441   // Get a register mask for the lowered call.
14442   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14443   // proper register mask.
14444   const uint32_t *RegMask =
14445     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14446   if (Subtarget->is64Bit()) {
14447     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14448                                       TII->get(X86::MOV64rm), X86::RDI)
14449     .addReg(X86::RIP)
14450     .addImm(0).addReg(0)
14451     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14452                       MI->getOperand(3).getTargetFlags())
14453     .addReg(0);
14454     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14455     addDirectMem(MIB, X86::RDI);
14456     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14457   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14458     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14459                                       TII->get(X86::MOV32rm), X86::EAX)
14460     .addReg(0)
14461     .addImm(0).addReg(0)
14462     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14463                       MI->getOperand(3).getTargetFlags())
14464     .addReg(0);
14465     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14466     addDirectMem(MIB, X86::EAX);
14467     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14468   } else {
14469     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14470                                       TII->get(X86::MOV32rm), X86::EAX)
14471     .addReg(TII->getGlobalBaseReg(F))
14472     .addImm(0).addReg(0)
14473     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14474                       MI->getOperand(3).getTargetFlags())
14475     .addReg(0);
14476     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14477     addDirectMem(MIB, X86::EAX);
14478     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14479   }
14480
14481   MI->eraseFromParent(); // The pseudo instruction is gone now.
14482   return BB;
14483 }
14484
14485 MachineBasicBlock *
14486 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14487                                     MachineBasicBlock *MBB) const {
14488   DebugLoc DL = MI->getDebugLoc();
14489   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14490
14491   MachineFunction *MF = MBB->getParent();
14492   MachineRegisterInfo &MRI = MF->getRegInfo();
14493
14494   const BasicBlock *BB = MBB->getBasicBlock();
14495   MachineFunction::iterator I = MBB;
14496   ++I;
14497
14498   // Memory Reference
14499   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14500   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14501
14502   unsigned DstReg;
14503   unsigned MemOpndSlot = 0;
14504
14505   unsigned CurOp = 0;
14506
14507   DstReg = MI->getOperand(CurOp++).getReg();
14508   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14509   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14510   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14511   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14512
14513   MemOpndSlot = CurOp;
14514
14515   MVT PVT = getPointerTy();
14516   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14517          "Invalid Pointer Size!");
14518
14519   // For v = setjmp(buf), we generate
14520   //
14521   // thisMBB:
14522   //  buf[LabelOffset] = restoreMBB
14523   //  SjLjSetup restoreMBB
14524   //
14525   // mainMBB:
14526   //  v_main = 0
14527   //
14528   // sinkMBB:
14529   //  v = phi(main, restore)
14530   //
14531   // restoreMBB:
14532   //  v_restore = 1
14533
14534   MachineBasicBlock *thisMBB = MBB;
14535   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14536   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14537   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14538   MF->insert(I, mainMBB);
14539   MF->insert(I, sinkMBB);
14540   MF->push_back(restoreMBB);
14541
14542   MachineInstrBuilder MIB;
14543
14544   // Transfer the remainder of BB and its successor edges to sinkMBB.
14545   sinkMBB->splice(sinkMBB->begin(), MBB,
14546                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14547   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14548
14549   // thisMBB:
14550   unsigned PtrStoreOpc = 0;
14551   unsigned LabelReg = 0;
14552   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14553   Reloc::Model RM = getTargetMachine().getRelocationModel();
14554   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14555                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14556
14557   // Prepare IP either in reg or imm.
14558   if (!UseImmLabel) {
14559     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14560     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14561     LabelReg = MRI.createVirtualRegister(PtrRC);
14562     if (Subtarget->is64Bit()) {
14563       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14564               .addReg(X86::RIP)
14565               .addImm(0)
14566               .addReg(0)
14567               .addMBB(restoreMBB)
14568               .addReg(0);
14569     } else {
14570       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14571       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14572               .addReg(XII->getGlobalBaseReg(MF))
14573               .addImm(0)
14574               .addReg(0)
14575               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14576               .addReg(0);
14577     }
14578   } else
14579     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14580   // Store IP
14581   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14582   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14583     if (i == X86::AddrDisp)
14584       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14585     else
14586       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14587   }
14588   if (!UseImmLabel)
14589     MIB.addReg(LabelReg);
14590   else
14591     MIB.addMBB(restoreMBB);
14592   MIB.setMemRefs(MMOBegin, MMOEnd);
14593   // Setup
14594   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14595           .addMBB(restoreMBB);
14596   MIB.addRegMask(RegInfo->getNoPreservedMask());
14597   thisMBB->addSuccessor(mainMBB);
14598   thisMBB->addSuccessor(restoreMBB);
14599
14600   // mainMBB:
14601   //  EAX = 0
14602   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14603   mainMBB->addSuccessor(sinkMBB);
14604
14605   // sinkMBB:
14606   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14607           TII->get(X86::PHI), DstReg)
14608     .addReg(mainDstReg).addMBB(mainMBB)
14609     .addReg(restoreDstReg).addMBB(restoreMBB);
14610
14611   // restoreMBB:
14612   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14613   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14614   restoreMBB->addSuccessor(sinkMBB);
14615
14616   MI->eraseFromParent();
14617   return sinkMBB;
14618 }
14619
14620 MachineBasicBlock *
14621 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14622                                      MachineBasicBlock *MBB) const {
14623   DebugLoc DL = MI->getDebugLoc();
14624   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14625
14626   MachineFunction *MF = MBB->getParent();
14627   MachineRegisterInfo &MRI = MF->getRegInfo();
14628
14629   // Memory Reference
14630   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14631   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14632
14633   MVT PVT = getPointerTy();
14634   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14635          "Invalid Pointer Size!");
14636
14637   const TargetRegisterClass *RC =
14638     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14639   unsigned Tmp = MRI.createVirtualRegister(RC);
14640   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14641   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14642   unsigned SP = RegInfo->getStackRegister();
14643
14644   MachineInstrBuilder MIB;
14645
14646   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14647   const int64_t SPOffset = 2 * PVT.getStoreSize();
14648
14649   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14650   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14651
14652   // Reload FP
14653   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14654   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14655     MIB.addOperand(MI->getOperand(i));
14656   MIB.setMemRefs(MMOBegin, MMOEnd);
14657   // Reload IP
14658   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14659   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14660     if (i == X86::AddrDisp)
14661       MIB.addDisp(MI->getOperand(i), LabelOffset);
14662     else
14663       MIB.addOperand(MI->getOperand(i));
14664   }
14665   MIB.setMemRefs(MMOBegin, MMOEnd);
14666   // Reload SP
14667   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14668   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14669     if (i == X86::AddrDisp)
14670       MIB.addDisp(MI->getOperand(i), SPOffset);
14671     else
14672       MIB.addOperand(MI->getOperand(i));
14673   }
14674   MIB.setMemRefs(MMOBegin, MMOEnd);
14675   // Jump
14676   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14677
14678   MI->eraseFromParent();
14679   return MBB;
14680 }
14681
14682 MachineBasicBlock *
14683 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14684                                                MachineBasicBlock *BB) const {
14685   switch (MI->getOpcode()) {
14686   default: llvm_unreachable("Unexpected instr type to insert");
14687   case X86::TAILJMPd64:
14688   case X86::TAILJMPr64:
14689   case X86::TAILJMPm64:
14690     llvm_unreachable("TAILJMP64 would not be touched here.");
14691   case X86::TCRETURNdi64:
14692   case X86::TCRETURNri64:
14693   case X86::TCRETURNmi64:
14694     return BB;
14695   case X86::WIN_ALLOCA:
14696     return EmitLoweredWinAlloca(MI, BB);
14697   case X86::SEG_ALLOCA_32:
14698     return EmitLoweredSegAlloca(MI, BB, false);
14699   case X86::SEG_ALLOCA_64:
14700     return EmitLoweredSegAlloca(MI, BB, true);
14701   case X86::TLSCall_32:
14702   case X86::TLSCall_64:
14703     return EmitLoweredTLSCall(MI, BB);
14704   case X86::CMOV_GR8:
14705   case X86::CMOV_FR32:
14706   case X86::CMOV_FR64:
14707   case X86::CMOV_V4F32:
14708   case X86::CMOV_V2F64:
14709   case X86::CMOV_V2I64:
14710   case X86::CMOV_V8F32:
14711   case X86::CMOV_V4F64:
14712   case X86::CMOV_V4I64:
14713   case X86::CMOV_GR16:
14714   case X86::CMOV_GR32:
14715   case X86::CMOV_RFP32:
14716   case X86::CMOV_RFP64:
14717   case X86::CMOV_RFP80:
14718     return EmitLoweredSelect(MI, BB);
14719
14720   case X86::FP32_TO_INT16_IN_MEM:
14721   case X86::FP32_TO_INT32_IN_MEM:
14722   case X86::FP32_TO_INT64_IN_MEM:
14723   case X86::FP64_TO_INT16_IN_MEM:
14724   case X86::FP64_TO_INT32_IN_MEM:
14725   case X86::FP64_TO_INT64_IN_MEM:
14726   case X86::FP80_TO_INT16_IN_MEM:
14727   case X86::FP80_TO_INT32_IN_MEM:
14728   case X86::FP80_TO_INT64_IN_MEM: {
14729     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14730     DebugLoc DL = MI->getDebugLoc();
14731
14732     // Change the floating point control register to use "round towards zero"
14733     // mode when truncating to an integer value.
14734     MachineFunction *F = BB->getParent();
14735     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14736     addFrameReference(BuildMI(*BB, MI, DL,
14737                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14738
14739     // Load the old value of the high byte of the control word...
14740     unsigned OldCW =
14741       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14742     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14743                       CWFrameIdx);
14744
14745     // Set the high part to be round to zero...
14746     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14747       .addImm(0xC7F);
14748
14749     // Reload the modified control word now...
14750     addFrameReference(BuildMI(*BB, MI, DL,
14751                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14752
14753     // Restore the memory image of control word to original value
14754     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14755       .addReg(OldCW);
14756
14757     // Get the X86 opcode to use.
14758     unsigned Opc;
14759     switch (MI->getOpcode()) {
14760     default: llvm_unreachable("illegal opcode!");
14761     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14762     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14763     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14764     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14765     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14766     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14767     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14768     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14769     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14770     }
14771
14772     X86AddressMode AM;
14773     MachineOperand &Op = MI->getOperand(0);
14774     if (Op.isReg()) {
14775       AM.BaseType = X86AddressMode::RegBase;
14776       AM.Base.Reg = Op.getReg();
14777     } else {
14778       AM.BaseType = X86AddressMode::FrameIndexBase;
14779       AM.Base.FrameIndex = Op.getIndex();
14780     }
14781     Op = MI->getOperand(1);
14782     if (Op.isImm())
14783       AM.Scale = Op.getImm();
14784     Op = MI->getOperand(2);
14785     if (Op.isImm())
14786       AM.IndexReg = Op.getImm();
14787     Op = MI->getOperand(3);
14788     if (Op.isGlobal()) {
14789       AM.GV = Op.getGlobal();
14790     } else {
14791       AM.Disp = Op.getImm();
14792     }
14793     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14794                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14795
14796     // Reload the original control word now.
14797     addFrameReference(BuildMI(*BB, MI, DL,
14798                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14799
14800     MI->eraseFromParent();   // The pseudo instruction is gone now.
14801     return BB;
14802   }
14803     // String/text processing lowering.
14804   case X86::PCMPISTRM128REG:
14805   case X86::VPCMPISTRM128REG:
14806   case X86::PCMPISTRM128MEM:
14807   case X86::VPCMPISTRM128MEM:
14808   case X86::PCMPESTRM128REG:
14809   case X86::VPCMPESTRM128REG:
14810   case X86::PCMPESTRM128MEM:
14811   case X86::VPCMPESTRM128MEM:
14812     assert(Subtarget->hasSSE42() &&
14813            "Target must have SSE4.2 or AVX features enabled");
14814     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14815
14816   // String/text processing lowering.
14817   case X86::PCMPISTRIREG:
14818   case X86::VPCMPISTRIREG:
14819   case X86::PCMPISTRIMEM:
14820   case X86::VPCMPISTRIMEM:
14821   case X86::PCMPESTRIREG:
14822   case X86::VPCMPESTRIREG:
14823   case X86::PCMPESTRIMEM:
14824   case X86::VPCMPESTRIMEM:
14825     assert(Subtarget->hasSSE42() &&
14826            "Target must have SSE4.2 or AVX features enabled");
14827     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14828
14829   // Thread synchronization.
14830   case X86::MONITOR:
14831     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14832
14833   // xbegin
14834   case X86::XBEGIN:
14835     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14836
14837   // Atomic Lowering.
14838   case X86::ATOMAND8:
14839   case X86::ATOMAND16:
14840   case X86::ATOMAND32:
14841   case X86::ATOMAND64:
14842     // Fall through
14843   case X86::ATOMOR8:
14844   case X86::ATOMOR16:
14845   case X86::ATOMOR32:
14846   case X86::ATOMOR64:
14847     // Fall through
14848   case X86::ATOMXOR16:
14849   case X86::ATOMXOR8:
14850   case X86::ATOMXOR32:
14851   case X86::ATOMXOR64:
14852     // Fall through
14853   case X86::ATOMNAND8:
14854   case X86::ATOMNAND16:
14855   case X86::ATOMNAND32:
14856   case X86::ATOMNAND64:
14857     // Fall through
14858   case X86::ATOMMAX8:
14859   case X86::ATOMMAX16:
14860   case X86::ATOMMAX32:
14861   case X86::ATOMMAX64:
14862     // Fall through
14863   case X86::ATOMMIN8:
14864   case X86::ATOMMIN16:
14865   case X86::ATOMMIN32:
14866   case X86::ATOMMIN64:
14867     // Fall through
14868   case X86::ATOMUMAX8:
14869   case X86::ATOMUMAX16:
14870   case X86::ATOMUMAX32:
14871   case X86::ATOMUMAX64:
14872     // Fall through
14873   case X86::ATOMUMIN8:
14874   case X86::ATOMUMIN16:
14875   case X86::ATOMUMIN32:
14876   case X86::ATOMUMIN64:
14877     return EmitAtomicLoadArith(MI, BB);
14878
14879   // This group does 64-bit operations on a 32-bit host.
14880   case X86::ATOMAND6432:
14881   case X86::ATOMOR6432:
14882   case X86::ATOMXOR6432:
14883   case X86::ATOMNAND6432:
14884   case X86::ATOMADD6432:
14885   case X86::ATOMSUB6432:
14886   case X86::ATOMMAX6432:
14887   case X86::ATOMMIN6432:
14888   case X86::ATOMUMAX6432:
14889   case X86::ATOMUMIN6432:
14890   case X86::ATOMSWAP6432:
14891     return EmitAtomicLoadArith6432(MI, BB);
14892
14893   case X86::VASTART_SAVE_XMM_REGS:
14894     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14895
14896   case X86::VAARG_64:
14897     return EmitVAARG64WithCustomInserter(MI, BB);
14898
14899   case X86::EH_SjLj_SetJmp32:
14900   case X86::EH_SjLj_SetJmp64:
14901     return emitEHSjLjSetJmp(MI, BB);
14902
14903   case X86::EH_SjLj_LongJmp32:
14904   case X86::EH_SjLj_LongJmp64:
14905     return emitEHSjLjLongJmp(MI, BB);
14906   }
14907 }
14908
14909 //===----------------------------------------------------------------------===//
14910 //                           X86 Optimization Hooks
14911 //===----------------------------------------------------------------------===//
14912
14913 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14914                                                        APInt &KnownZero,
14915                                                        APInt &KnownOne,
14916                                                        const SelectionDAG &DAG,
14917                                                        unsigned Depth) const {
14918   unsigned BitWidth = KnownZero.getBitWidth();
14919   unsigned Opc = Op.getOpcode();
14920   assert((Opc >= ISD::BUILTIN_OP_END ||
14921           Opc == ISD::INTRINSIC_WO_CHAIN ||
14922           Opc == ISD::INTRINSIC_W_CHAIN ||
14923           Opc == ISD::INTRINSIC_VOID) &&
14924          "Should use MaskedValueIsZero if you don't know whether Op"
14925          " is a target node!");
14926
14927   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14928   switch (Opc) {
14929   default: break;
14930   case X86ISD::ADD:
14931   case X86ISD::SUB:
14932   case X86ISD::ADC:
14933   case X86ISD::SBB:
14934   case X86ISD::SMUL:
14935   case X86ISD::UMUL:
14936   case X86ISD::INC:
14937   case X86ISD::DEC:
14938   case X86ISD::OR:
14939   case X86ISD::XOR:
14940   case X86ISD::AND:
14941     // These nodes' second result is a boolean.
14942     if (Op.getResNo() == 0)
14943       break;
14944     // Fallthrough
14945   case X86ISD::SETCC:
14946     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14947     break;
14948   case ISD::INTRINSIC_WO_CHAIN: {
14949     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14950     unsigned NumLoBits = 0;
14951     switch (IntId) {
14952     default: break;
14953     case Intrinsic::x86_sse_movmsk_ps:
14954     case Intrinsic::x86_avx_movmsk_ps_256:
14955     case Intrinsic::x86_sse2_movmsk_pd:
14956     case Intrinsic::x86_avx_movmsk_pd_256:
14957     case Intrinsic::x86_mmx_pmovmskb:
14958     case Intrinsic::x86_sse2_pmovmskb_128:
14959     case Intrinsic::x86_avx2_pmovmskb: {
14960       // High bits of movmskp{s|d}, pmovmskb are known zero.
14961       switch (IntId) {
14962         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14963         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14964         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14965         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14966         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14967         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14968         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14969         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14970       }
14971       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14972       break;
14973     }
14974     }
14975     break;
14976   }
14977   }
14978 }
14979
14980 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14981                                                          unsigned Depth) const {
14982   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14983   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14984     return Op.getValueType().getScalarType().getSizeInBits();
14985
14986   // Fallback case.
14987   return 1;
14988 }
14989
14990 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14991 /// node is a GlobalAddress + offset.
14992 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14993                                        const GlobalValue* &GA,
14994                                        int64_t &Offset) const {
14995   if (N->getOpcode() == X86ISD::Wrapper) {
14996     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14997       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14998       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14999       return true;
15000     }
15001   }
15002   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15003 }
15004
15005 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15006 /// same as extracting the high 128-bit part of 256-bit vector and then
15007 /// inserting the result into the low part of a new 256-bit vector
15008 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15009   EVT VT = SVOp->getValueType(0);
15010   unsigned NumElems = VT.getVectorNumElements();
15011
15012   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15013   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15014     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15015         SVOp->getMaskElt(j) >= 0)
15016       return false;
15017
15018   return true;
15019 }
15020
15021 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15022 /// same as extracting the low 128-bit part of 256-bit vector and then
15023 /// inserting the result into the high part of a new 256-bit vector
15024 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15025   EVT VT = SVOp->getValueType(0);
15026   unsigned NumElems = VT.getVectorNumElements();
15027
15028   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15029   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15030     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15031         SVOp->getMaskElt(j) >= 0)
15032       return false;
15033
15034   return true;
15035 }
15036
15037 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15038 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15039                                         TargetLowering::DAGCombinerInfo &DCI,
15040                                         const X86Subtarget* Subtarget) {
15041   DebugLoc dl = N->getDebugLoc();
15042   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15043   SDValue V1 = SVOp->getOperand(0);
15044   SDValue V2 = SVOp->getOperand(1);
15045   EVT VT = SVOp->getValueType(0);
15046   unsigned NumElems = VT.getVectorNumElements();
15047
15048   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15049       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15050     //
15051     //                   0,0,0,...
15052     //                      |
15053     //    V      UNDEF    BUILD_VECTOR    UNDEF
15054     //     \      /           \           /
15055     //  CONCAT_VECTOR         CONCAT_VECTOR
15056     //         \                  /
15057     //          \                /
15058     //          RESULT: V + zero extended
15059     //
15060     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15061         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15062         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15063       return SDValue();
15064
15065     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15066       return SDValue();
15067
15068     // To match the shuffle mask, the first half of the mask should
15069     // be exactly the first vector, and all the rest a splat with the
15070     // first element of the second one.
15071     for (unsigned i = 0; i != NumElems/2; ++i)
15072       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15073           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15074         return SDValue();
15075
15076     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15077     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15078       if (Ld->hasNUsesOfValue(1, 0)) {
15079         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15080         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15081         SDValue ResNode =
15082           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15083                                   array_lengthof(Ops),
15084                                   Ld->getMemoryVT(),
15085                                   Ld->getPointerInfo(),
15086                                   Ld->getAlignment(),
15087                                   false/*isVolatile*/, true/*ReadMem*/,
15088                                   false/*WriteMem*/);
15089
15090         // Make sure the newly-created LOAD is in the same position as Ld in
15091         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15092         // and update uses of Ld's output chain to use the TokenFactor.
15093         if (Ld->hasAnyUseOfValue(1)) {
15094           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15095                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15096           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15097           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15098                                  SDValue(ResNode.getNode(), 1));
15099         }
15100
15101         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15102       }
15103     }
15104
15105     // Emit a zeroed vector and insert the desired subvector on its
15106     // first half.
15107     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15108     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15109     return DCI.CombineTo(N, InsV);
15110   }
15111
15112   //===--------------------------------------------------------------------===//
15113   // Combine some shuffles into subvector extracts and inserts:
15114   //
15115
15116   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15117   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15118     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15119     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15120     return DCI.CombineTo(N, InsV);
15121   }
15122
15123   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15124   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15125     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15126     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15127     return DCI.CombineTo(N, InsV);
15128   }
15129
15130   return SDValue();
15131 }
15132
15133 /// PerformShuffleCombine - Performs several different shuffle combines.
15134 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15135                                      TargetLowering::DAGCombinerInfo &DCI,
15136                                      const X86Subtarget *Subtarget) {
15137   DebugLoc dl = N->getDebugLoc();
15138   EVT VT = N->getValueType(0);
15139
15140   // Don't create instructions with illegal types after legalize types has run.
15141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15142   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15143     return SDValue();
15144
15145   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15146   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15147       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15148     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15149
15150   // Only handle 128 wide vector from here on.
15151   if (!VT.is128BitVector())
15152     return SDValue();
15153
15154   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15155   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15156   // consecutive, non-overlapping, and in the right order.
15157   SmallVector<SDValue, 16> Elts;
15158   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15159     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15160
15161   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15162 }
15163
15164 /// PerformTruncateCombine - Converts truncate operation to
15165 /// a sequence of vector shuffle operations.
15166 /// It is possible when we truncate 256-bit vector to 128-bit vector
15167 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15168                                       TargetLowering::DAGCombinerInfo &DCI,
15169                                       const X86Subtarget *Subtarget)  {
15170   return SDValue();
15171 }
15172
15173 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15174 /// specific shuffle of a load can be folded into a single element load.
15175 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15176 /// shuffles have been customed lowered so we need to handle those here.
15177 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15178                                          TargetLowering::DAGCombinerInfo &DCI) {
15179   if (DCI.isBeforeLegalizeOps())
15180     return SDValue();
15181
15182   SDValue InVec = N->getOperand(0);
15183   SDValue EltNo = N->getOperand(1);
15184
15185   if (!isa<ConstantSDNode>(EltNo))
15186     return SDValue();
15187
15188   EVT VT = InVec.getValueType();
15189
15190   bool HasShuffleIntoBitcast = false;
15191   if (InVec.getOpcode() == ISD::BITCAST) {
15192     // Don't duplicate a load with other uses.
15193     if (!InVec.hasOneUse())
15194       return SDValue();
15195     EVT BCVT = InVec.getOperand(0).getValueType();
15196     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15197       return SDValue();
15198     InVec = InVec.getOperand(0);
15199     HasShuffleIntoBitcast = true;
15200   }
15201
15202   if (!isTargetShuffle(InVec.getOpcode()))
15203     return SDValue();
15204
15205   // Don't duplicate a load with other uses.
15206   if (!InVec.hasOneUse())
15207     return SDValue();
15208
15209   SmallVector<int, 16> ShuffleMask;
15210   bool UnaryShuffle;
15211   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15212                             UnaryShuffle))
15213     return SDValue();
15214
15215   // Select the input vector, guarding against out of range extract vector.
15216   unsigned NumElems = VT.getVectorNumElements();
15217   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15218   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15219   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15220                                          : InVec.getOperand(1);
15221
15222   // If inputs to shuffle are the same for both ops, then allow 2 uses
15223   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15224
15225   if (LdNode.getOpcode() == ISD::BITCAST) {
15226     // Don't duplicate a load with other uses.
15227     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15228       return SDValue();
15229
15230     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15231     LdNode = LdNode.getOperand(0);
15232   }
15233
15234   if (!ISD::isNormalLoad(LdNode.getNode()))
15235     return SDValue();
15236
15237   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15238
15239   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15240     return SDValue();
15241
15242   if (HasShuffleIntoBitcast) {
15243     // If there's a bitcast before the shuffle, check if the load type and
15244     // alignment is valid.
15245     unsigned Align = LN0->getAlignment();
15246     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15247     unsigned NewAlign = TLI.getDataLayout()->
15248       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15249
15250     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15251       return SDValue();
15252   }
15253
15254   // All checks match so transform back to vector_shuffle so that DAG combiner
15255   // can finish the job
15256   DebugLoc dl = N->getDebugLoc();
15257
15258   // Create shuffle node taking into account the case that its a unary shuffle
15259   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15260   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15261                                  InVec.getOperand(0), Shuffle,
15262                                  &ShuffleMask[0]);
15263   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15264   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15265                      EltNo);
15266 }
15267
15268 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15269 /// generation and convert it from being a bunch of shuffles and extracts
15270 /// to a simple store and scalar loads to extract the elements.
15271 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15272                                          TargetLowering::DAGCombinerInfo &DCI) {
15273   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15274   if (NewOp.getNode())
15275     return NewOp;
15276
15277   SDValue InputVector = N->getOperand(0);
15278   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15279   // from mmx to v2i32 has a single usage.
15280   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15281       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15282       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15283     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15284                        N->getValueType(0),
15285                        InputVector.getNode()->getOperand(0));
15286
15287   // Only operate on vectors of 4 elements, where the alternative shuffling
15288   // gets to be more expensive.
15289   if (InputVector.getValueType() != MVT::v4i32)
15290     return SDValue();
15291
15292   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15293   // single use which is a sign-extend or zero-extend, and all elements are
15294   // used.
15295   SmallVector<SDNode *, 4> Uses;
15296   unsigned ExtractedElements = 0;
15297   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15298        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15299     if (UI.getUse().getResNo() != InputVector.getResNo())
15300       return SDValue();
15301
15302     SDNode *Extract = *UI;
15303     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15304       return SDValue();
15305
15306     if (Extract->getValueType(0) != MVT::i32)
15307       return SDValue();
15308     if (!Extract->hasOneUse())
15309       return SDValue();
15310     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15311         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15312       return SDValue();
15313     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15314       return SDValue();
15315
15316     // Record which element was extracted.
15317     ExtractedElements |=
15318       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15319
15320     Uses.push_back(Extract);
15321   }
15322
15323   // If not all the elements were used, this may not be worthwhile.
15324   if (ExtractedElements != 15)
15325     return SDValue();
15326
15327   // Ok, we've now decided to do the transformation.
15328   DebugLoc dl = InputVector.getDebugLoc();
15329
15330   // Store the value to a temporary stack slot.
15331   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15332   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15333                             MachinePointerInfo(), false, false, 0);
15334
15335   // Replace each use (extract) with a load of the appropriate element.
15336   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15337        UE = Uses.end(); UI != UE; ++UI) {
15338     SDNode *Extract = *UI;
15339
15340     // cOMpute the element's address.
15341     SDValue Idx = Extract->getOperand(1);
15342     unsigned EltSize =
15343         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15344     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15345     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15346     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15347
15348     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15349                                      StackPtr, OffsetVal);
15350
15351     // Load the scalar.
15352     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15353                                      ScalarAddr, MachinePointerInfo(),
15354                                      false, false, false, 0);
15355
15356     // Replace the exact with the load.
15357     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15358   }
15359
15360   // The replacement was made in place; don't return anything.
15361   return SDValue();
15362 }
15363
15364 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15365 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15366                                    SDValue RHS, SelectionDAG &DAG,
15367                                    const X86Subtarget *Subtarget) {
15368   if (!VT.isVector())
15369     return 0;
15370
15371   switch (VT.getSimpleVT().SimpleTy) {
15372   default: return 0;
15373   case MVT::v32i8:
15374   case MVT::v16i16:
15375   case MVT::v8i32:
15376     if (!Subtarget->hasAVX2())
15377       return 0;
15378   case MVT::v16i8:
15379   case MVT::v8i16:
15380   case MVT::v4i32:
15381     if (!Subtarget->hasSSE2())
15382       return 0;
15383   }
15384
15385   // SSE2 has only a small subset of the operations.
15386   bool hasUnsigned = Subtarget->hasSSE41() ||
15387                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15388   bool hasSigned = Subtarget->hasSSE41() ||
15389                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15390
15391   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15392
15393   // Check for x CC y ? x : y.
15394   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15395       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15396     switch (CC) {
15397     default: break;
15398     case ISD::SETULT:
15399     case ISD::SETULE:
15400       return hasUnsigned ? X86ISD::UMIN : 0;
15401     case ISD::SETUGT:
15402     case ISD::SETUGE:
15403       return hasUnsigned ? X86ISD::UMAX : 0;
15404     case ISD::SETLT:
15405     case ISD::SETLE:
15406       return hasSigned ? X86ISD::SMIN : 0;
15407     case ISD::SETGT:
15408     case ISD::SETGE:
15409       return hasSigned ? X86ISD::SMAX : 0;
15410     }
15411   // Check for x CC y ? y : x -- a min/max with reversed arms.
15412   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15413              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15414     switch (CC) {
15415     default: break;
15416     case ISD::SETULT:
15417     case ISD::SETULE:
15418       return hasUnsigned ? X86ISD::UMAX : 0;
15419     case ISD::SETUGT:
15420     case ISD::SETUGE:
15421       return hasUnsigned ? X86ISD::UMIN : 0;
15422     case ISD::SETLT:
15423     case ISD::SETLE:
15424       return hasSigned ? X86ISD::SMAX : 0;
15425     case ISD::SETGT:
15426     case ISD::SETGE:
15427       return hasSigned ? X86ISD::SMIN : 0;
15428     }
15429   }
15430
15431   return 0;
15432 }
15433
15434 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15435 /// nodes.
15436 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15437                                     TargetLowering::DAGCombinerInfo &DCI,
15438                                     const X86Subtarget *Subtarget) {
15439   DebugLoc DL = N->getDebugLoc();
15440   SDValue Cond = N->getOperand(0);
15441   // Get the LHS/RHS of the select.
15442   SDValue LHS = N->getOperand(1);
15443   SDValue RHS = N->getOperand(2);
15444   EVT VT = LHS.getValueType();
15445
15446   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15447   // instructions match the semantics of the common C idiom x<y?x:y but not
15448   // x<=y?x:y, because of how they handle negative zero (which can be
15449   // ignored in unsafe-math mode).
15450   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15451       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15452       (Subtarget->hasSSE2() ||
15453        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15454     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15455
15456     unsigned Opcode = 0;
15457     // Check for x CC y ? x : y.
15458     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15459         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15460       switch (CC) {
15461       default: break;
15462       case ISD::SETULT:
15463         // Converting this to a min would handle NaNs incorrectly, and swapping
15464         // the operands would cause it to handle comparisons between positive
15465         // and negative zero incorrectly.
15466         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15467           if (!DAG.getTarget().Options.UnsafeFPMath &&
15468               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15469             break;
15470           std::swap(LHS, RHS);
15471         }
15472         Opcode = X86ISD::FMIN;
15473         break;
15474       case ISD::SETOLE:
15475         // Converting this to a min would handle comparisons between positive
15476         // and negative zero incorrectly.
15477         if (!DAG.getTarget().Options.UnsafeFPMath &&
15478             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15479           break;
15480         Opcode = X86ISD::FMIN;
15481         break;
15482       case ISD::SETULE:
15483         // Converting this to a min would handle both negative zeros and NaNs
15484         // incorrectly, but we can swap the operands to fix both.
15485         std::swap(LHS, RHS);
15486       case ISD::SETOLT:
15487       case ISD::SETLT:
15488       case ISD::SETLE:
15489         Opcode = X86ISD::FMIN;
15490         break;
15491
15492       case ISD::SETOGE:
15493         // Converting this to a max would handle comparisons between positive
15494         // and negative zero incorrectly.
15495         if (!DAG.getTarget().Options.UnsafeFPMath &&
15496             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15497           break;
15498         Opcode = X86ISD::FMAX;
15499         break;
15500       case ISD::SETUGT:
15501         // Converting this to a max would handle NaNs incorrectly, and swapping
15502         // the operands would cause it to handle comparisons between positive
15503         // and negative zero incorrectly.
15504         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15505           if (!DAG.getTarget().Options.UnsafeFPMath &&
15506               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15507             break;
15508           std::swap(LHS, RHS);
15509         }
15510         Opcode = X86ISD::FMAX;
15511         break;
15512       case ISD::SETUGE:
15513         // Converting this to a max would handle both negative zeros and NaNs
15514         // incorrectly, but we can swap the operands to fix both.
15515         std::swap(LHS, RHS);
15516       case ISD::SETOGT:
15517       case ISD::SETGT:
15518       case ISD::SETGE:
15519         Opcode = X86ISD::FMAX;
15520         break;
15521       }
15522     // Check for x CC y ? y : x -- a min/max with reversed arms.
15523     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15524                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15525       switch (CC) {
15526       default: break;
15527       case ISD::SETOGE:
15528         // Converting this to a min would handle comparisons between positive
15529         // and negative zero incorrectly, and swapping the operands would
15530         // cause it to handle NaNs incorrectly.
15531         if (!DAG.getTarget().Options.UnsafeFPMath &&
15532             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15533           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15534             break;
15535           std::swap(LHS, RHS);
15536         }
15537         Opcode = X86ISD::FMIN;
15538         break;
15539       case ISD::SETUGT:
15540         // Converting this to a min would handle NaNs incorrectly.
15541         if (!DAG.getTarget().Options.UnsafeFPMath &&
15542             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15543           break;
15544         Opcode = X86ISD::FMIN;
15545         break;
15546       case ISD::SETUGE:
15547         // Converting this to a min would handle both negative zeros and NaNs
15548         // incorrectly, but we can swap the operands to fix both.
15549         std::swap(LHS, RHS);
15550       case ISD::SETOGT:
15551       case ISD::SETGT:
15552       case ISD::SETGE:
15553         Opcode = X86ISD::FMIN;
15554         break;
15555
15556       case ISD::SETULT:
15557         // Converting this to a max would handle NaNs incorrectly.
15558         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15559           break;
15560         Opcode = X86ISD::FMAX;
15561         break;
15562       case ISD::SETOLE:
15563         // Converting this to a max would handle comparisons between positive
15564         // and negative zero incorrectly, and swapping the operands would
15565         // cause it to handle NaNs incorrectly.
15566         if (!DAG.getTarget().Options.UnsafeFPMath &&
15567             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15568           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15569             break;
15570           std::swap(LHS, RHS);
15571         }
15572         Opcode = X86ISD::FMAX;
15573         break;
15574       case ISD::SETULE:
15575         // Converting this to a max would handle both negative zeros and NaNs
15576         // incorrectly, but we can swap the operands to fix both.
15577         std::swap(LHS, RHS);
15578       case ISD::SETOLT:
15579       case ISD::SETLT:
15580       case ISD::SETLE:
15581         Opcode = X86ISD::FMAX;
15582         break;
15583       }
15584     }
15585
15586     if (Opcode)
15587       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15588   }
15589
15590   // If this is a select between two integer constants, try to do some
15591   // optimizations.
15592   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15593     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15594       // Don't do this for crazy integer types.
15595       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15596         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15597         // so that TrueC (the true value) is larger than FalseC.
15598         bool NeedsCondInvert = false;
15599
15600         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15601             // Efficiently invertible.
15602             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15603              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15604               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15605           NeedsCondInvert = true;
15606           std::swap(TrueC, FalseC);
15607         }
15608
15609         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15610         if (FalseC->getAPIntValue() == 0 &&
15611             TrueC->getAPIntValue().isPowerOf2()) {
15612           if (NeedsCondInvert) // Invert the condition if needed.
15613             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15614                                DAG.getConstant(1, Cond.getValueType()));
15615
15616           // Zero extend the condition if needed.
15617           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15618
15619           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15620           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15621                              DAG.getConstant(ShAmt, MVT::i8));
15622         }
15623
15624         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15625         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15626           if (NeedsCondInvert) // Invert the condition if needed.
15627             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15628                                DAG.getConstant(1, Cond.getValueType()));
15629
15630           // Zero extend the condition if needed.
15631           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15632                              FalseC->getValueType(0), Cond);
15633           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15634                              SDValue(FalseC, 0));
15635         }
15636
15637         // Optimize cases that will turn into an LEA instruction.  This requires
15638         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15639         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15640           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15641           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15642
15643           bool isFastMultiplier = false;
15644           if (Diff < 10) {
15645             switch ((unsigned char)Diff) {
15646               default: break;
15647               case 1:  // result = add base, cond
15648               case 2:  // result = lea base(    , cond*2)
15649               case 3:  // result = lea base(cond, cond*2)
15650               case 4:  // result = lea base(    , cond*4)
15651               case 5:  // result = lea base(cond, cond*4)
15652               case 8:  // result = lea base(    , cond*8)
15653               case 9:  // result = lea base(cond, cond*8)
15654                 isFastMultiplier = true;
15655                 break;
15656             }
15657           }
15658
15659           if (isFastMultiplier) {
15660             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15661             if (NeedsCondInvert) // Invert the condition if needed.
15662               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15663                                  DAG.getConstant(1, Cond.getValueType()));
15664
15665             // Zero extend the condition if needed.
15666             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15667                                Cond);
15668             // Scale the condition by the difference.
15669             if (Diff != 1)
15670               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15671                                  DAG.getConstant(Diff, Cond.getValueType()));
15672
15673             // Add the base if non-zero.
15674             if (FalseC->getAPIntValue() != 0)
15675               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15676                                  SDValue(FalseC, 0));
15677             return Cond;
15678           }
15679         }
15680       }
15681   }
15682
15683   // Canonicalize max and min:
15684   // (x > y) ? x : y -> (x >= y) ? x : y
15685   // (x < y) ? x : y -> (x <= y) ? x : y
15686   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15687   // the need for an extra compare
15688   // against zero. e.g.
15689   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15690   // subl   %esi, %edi
15691   // testl  %edi, %edi
15692   // movl   $0, %eax
15693   // cmovgl %edi, %eax
15694   // =>
15695   // xorl   %eax, %eax
15696   // subl   %esi, $edi
15697   // cmovsl %eax, %edi
15698   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15699       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15700       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15701     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15702     switch (CC) {
15703     default: break;
15704     case ISD::SETLT:
15705     case ISD::SETGT: {
15706       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15707       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15708                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15709       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15710     }
15711     }
15712   }
15713
15714   // Match VSELECTs into subs with unsigned saturation.
15715   if (!DCI.isBeforeLegalize() &&
15716       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15717       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15718       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15719        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15720     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15721
15722     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15723     // left side invert the predicate to simplify logic below.
15724     SDValue Other;
15725     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15726       Other = RHS;
15727       CC = ISD::getSetCCInverse(CC, true);
15728     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15729       Other = LHS;
15730     }
15731
15732     if (Other.getNode() && Other->getNumOperands() == 2 &&
15733         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15734       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15735       SDValue CondRHS = Cond->getOperand(1);
15736
15737       // Look for a general sub with unsigned saturation first.
15738       // x >= y ? x-y : 0 --> subus x, y
15739       // x >  y ? x-y : 0 --> subus x, y
15740       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15741           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15742         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15743
15744       // If the RHS is a constant we have to reverse the const canonicalization.
15745       // x > C-1 ? x+-C : 0 --> subus x, C
15746       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15747           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15748         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15749         if (CondRHS.getConstantOperandVal(0) == -A-1)
15750           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15751                              DAG.getConstant(-A, VT));
15752       }
15753
15754       // Another special case: If C was a sign bit, the sub has been
15755       // canonicalized into a xor.
15756       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15757       //        it's safe to decanonicalize the xor?
15758       // x s< 0 ? x^C : 0 --> subus x, C
15759       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15760           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15761           isSplatVector(OpRHS.getNode())) {
15762         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15763         if (A.isSignBit())
15764           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15765       }
15766     }
15767   }
15768
15769   // Try to match a min/max vector operation.
15770   if (!DCI.isBeforeLegalize() &&
15771       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15772     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15773       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15774
15775   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15776   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15777       Cond.getOpcode() == ISD::SETCC) {
15778
15779     assert(Cond.getValueType().isVector() &&
15780            "vector select expects a vector selector!");
15781
15782     EVT IntVT = Cond.getValueType();
15783     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15784     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15785
15786     if (!TValIsAllOnes && !FValIsAllZeros) {
15787       // Try invert the condition if true value is not all 1s and false value
15788       // is not all 0s.
15789       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15790       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15791
15792       if (TValIsAllZeros || FValIsAllOnes) {
15793         SDValue CC = Cond.getOperand(2);
15794         ISD::CondCode NewCC =
15795           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15796                                Cond.getOperand(0).getValueType().isInteger());
15797         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15798         std::swap(LHS, RHS);
15799         TValIsAllOnes = FValIsAllOnes;
15800         FValIsAllZeros = TValIsAllZeros;
15801       }
15802     }
15803
15804     if (TValIsAllOnes || FValIsAllZeros) {
15805       SDValue Ret;
15806
15807       if (TValIsAllOnes && FValIsAllZeros)
15808         Ret = Cond;
15809       else if (TValIsAllOnes)
15810         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15811                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15812       else if (FValIsAllZeros)
15813         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15814                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15815
15816       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15817     }
15818   }
15819
15820   // If we know that this node is legal then we know that it is going to be
15821   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15822   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15823   // to simplify previous instructions.
15824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15825   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15826       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15827     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15828
15829     // Don't optimize vector selects that map to mask-registers.
15830     if (BitWidth == 1)
15831       return SDValue();
15832
15833     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15834     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15835
15836     APInt KnownZero, KnownOne;
15837     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15838                                           DCI.isBeforeLegalizeOps());
15839     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15840         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15841       DCI.CommitTargetLoweringOpt(TLO);
15842   }
15843
15844   return SDValue();
15845 }
15846
15847 // Check whether a boolean test is testing a boolean value generated by
15848 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15849 // code.
15850 //
15851 // Simplify the following patterns:
15852 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15853 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15854 // to (Op EFLAGS Cond)
15855 //
15856 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15857 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15858 // to (Op EFLAGS !Cond)
15859 //
15860 // where Op could be BRCOND or CMOV.
15861 //
15862 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15863   // Quit if not CMP and SUB with its value result used.
15864   if (Cmp.getOpcode() != X86ISD::CMP &&
15865       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15866       return SDValue();
15867
15868   // Quit if not used as a boolean value.
15869   if (CC != X86::COND_E && CC != X86::COND_NE)
15870     return SDValue();
15871
15872   // Check CMP operands. One of them should be 0 or 1 and the other should be
15873   // an SetCC or extended from it.
15874   SDValue Op1 = Cmp.getOperand(0);
15875   SDValue Op2 = Cmp.getOperand(1);
15876
15877   SDValue SetCC;
15878   const ConstantSDNode* C = 0;
15879   bool needOppositeCond = (CC == X86::COND_E);
15880   bool checkAgainstTrue = false; // Is it a comparison against 1?
15881
15882   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15883     SetCC = Op2;
15884   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15885     SetCC = Op1;
15886   else // Quit if all operands are not constants.
15887     return SDValue();
15888
15889   if (C->getZExtValue() == 1) {
15890     needOppositeCond = !needOppositeCond;
15891     checkAgainstTrue = true;
15892   } else if (C->getZExtValue() != 0)
15893     // Quit if the constant is neither 0 or 1.
15894     return SDValue();
15895
15896   bool truncatedToBoolWithAnd = false;
15897   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15898   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15899          SetCC.getOpcode() == ISD::TRUNCATE ||
15900          SetCC.getOpcode() == ISD::AND) {
15901     if (SetCC.getOpcode() == ISD::AND) {
15902       int OpIdx = -1;
15903       ConstantSDNode *CS;
15904       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15905           CS->getZExtValue() == 1)
15906         OpIdx = 1;
15907       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15908           CS->getZExtValue() == 1)
15909         OpIdx = 0;
15910       if (OpIdx == -1)
15911         break;
15912       SetCC = SetCC.getOperand(OpIdx);
15913       truncatedToBoolWithAnd = true;
15914     } else
15915       SetCC = SetCC.getOperand(0);
15916   }
15917
15918   switch (SetCC.getOpcode()) {
15919   case X86ISD::SETCC_CARRY:
15920     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15921     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15922     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15923     // truncated to i1 using 'and'.
15924     if (checkAgainstTrue && !truncatedToBoolWithAnd)
15925       break;
15926     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15927            "Invalid use of SETCC_CARRY!");
15928     // FALL THROUGH
15929   case X86ISD::SETCC:
15930     // Set the condition code or opposite one if necessary.
15931     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15932     if (needOppositeCond)
15933       CC = X86::GetOppositeBranchCondition(CC);
15934     return SetCC.getOperand(1);
15935   case X86ISD::CMOV: {
15936     // Check whether false/true value has canonical one, i.e. 0 or 1.
15937     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15938     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15939     // Quit if true value is not a constant.
15940     if (!TVal)
15941       return SDValue();
15942     // Quit if false value is not a constant.
15943     if (!FVal) {
15944       SDValue Op = SetCC.getOperand(0);
15945       // Skip 'zext' or 'trunc' node.
15946       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15947           Op.getOpcode() == ISD::TRUNCATE)
15948         Op = Op.getOperand(0);
15949       // A special case for rdrand/rdseed, where 0 is set if false cond is
15950       // found.
15951       if ((Op.getOpcode() != X86ISD::RDRAND &&
15952            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15953         return SDValue();
15954     }
15955     // Quit if false value is not the constant 0 or 1.
15956     bool FValIsFalse = true;
15957     if (FVal && FVal->getZExtValue() != 0) {
15958       if (FVal->getZExtValue() != 1)
15959         return SDValue();
15960       // If FVal is 1, opposite cond is needed.
15961       needOppositeCond = !needOppositeCond;
15962       FValIsFalse = false;
15963     }
15964     // Quit if TVal is not the constant opposite of FVal.
15965     if (FValIsFalse && TVal->getZExtValue() != 1)
15966       return SDValue();
15967     if (!FValIsFalse && TVal->getZExtValue() != 0)
15968       return SDValue();
15969     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15970     if (needOppositeCond)
15971       CC = X86::GetOppositeBranchCondition(CC);
15972     return SetCC.getOperand(3);
15973   }
15974   }
15975
15976   return SDValue();
15977 }
15978
15979 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15980 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15981                                   TargetLowering::DAGCombinerInfo &DCI,
15982                                   const X86Subtarget *Subtarget) {
15983   DebugLoc DL = N->getDebugLoc();
15984
15985   // If the flag operand isn't dead, don't touch this CMOV.
15986   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15987     return SDValue();
15988
15989   SDValue FalseOp = N->getOperand(0);
15990   SDValue TrueOp = N->getOperand(1);
15991   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15992   SDValue Cond = N->getOperand(3);
15993
15994   if (CC == X86::COND_E || CC == X86::COND_NE) {
15995     switch (Cond.getOpcode()) {
15996     default: break;
15997     case X86ISD::BSR:
15998     case X86ISD::BSF:
15999       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16000       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16001         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16002     }
16003   }
16004
16005   SDValue Flags;
16006
16007   Flags = checkBoolTestSetCCCombine(Cond, CC);
16008   if (Flags.getNode() &&
16009       // Extra check as FCMOV only supports a subset of X86 cond.
16010       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16011     SDValue Ops[] = { FalseOp, TrueOp,
16012                       DAG.getConstant(CC, MVT::i8), Flags };
16013     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16014                        Ops, array_lengthof(Ops));
16015   }
16016
16017   // If this is a select between two integer constants, try to do some
16018   // optimizations.  Note that the operands are ordered the opposite of SELECT
16019   // operands.
16020   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16021     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16022       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16023       // larger than FalseC (the false value).
16024       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16025         CC = X86::GetOppositeBranchCondition(CC);
16026         std::swap(TrueC, FalseC);
16027         std::swap(TrueOp, FalseOp);
16028       }
16029
16030       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16031       // This is efficient for any integer data type (including i8/i16) and
16032       // shift amount.
16033       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16034         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16035                            DAG.getConstant(CC, MVT::i8), Cond);
16036
16037         // Zero extend the condition if needed.
16038         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16039
16040         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16041         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16042                            DAG.getConstant(ShAmt, MVT::i8));
16043         if (N->getNumValues() == 2)  // Dead flag value?
16044           return DCI.CombineTo(N, Cond, SDValue());
16045         return Cond;
16046       }
16047
16048       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16049       // for any integer data type, including i8/i16.
16050       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16051         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16052                            DAG.getConstant(CC, MVT::i8), Cond);
16053
16054         // Zero extend the condition if needed.
16055         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16056                            FalseC->getValueType(0), Cond);
16057         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16058                            SDValue(FalseC, 0));
16059
16060         if (N->getNumValues() == 2)  // Dead flag value?
16061           return DCI.CombineTo(N, Cond, SDValue());
16062         return Cond;
16063       }
16064
16065       // Optimize cases that will turn into an LEA instruction.  This requires
16066       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16067       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16068         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16069         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16070
16071         bool isFastMultiplier = false;
16072         if (Diff < 10) {
16073           switch ((unsigned char)Diff) {
16074           default: break;
16075           case 1:  // result = add base, cond
16076           case 2:  // result = lea base(    , cond*2)
16077           case 3:  // result = lea base(cond, cond*2)
16078           case 4:  // result = lea base(    , cond*4)
16079           case 5:  // result = lea base(cond, cond*4)
16080           case 8:  // result = lea base(    , cond*8)
16081           case 9:  // result = lea base(cond, cond*8)
16082             isFastMultiplier = true;
16083             break;
16084           }
16085         }
16086
16087         if (isFastMultiplier) {
16088           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16089           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16090                              DAG.getConstant(CC, MVT::i8), Cond);
16091           // Zero extend the condition if needed.
16092           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16093                              Cond);
16094           // Scale the condition by the difference.
16095           if (Diff != 1)
16096             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16097                                DAG.getConstant(Diff, Cond.getValueType()));
16098
16099           // Add the base if non-zero.
16100           if (FalseC->getAPIntValue() != 0)
16101             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16102                                SDValue(FalseC, 0));
16103           if (N->getNumValues() == 2)  // Dead flag value?
16104             return DCI.CombineTo(N, Cond, SDValue());
16105           return Cond;
16106         }
16107       }
16108     }
16109   }
16110
16111   // Handle these cases:
16112   //   (select (x != c), e, c) -> select (x != c), e, x),
16113   //   (select (x == c), c, e) -> select (x == c), x, e)
16114   // where the c is an integer constant, and the "select" is the combination
16115   // of CMOV and CMP.
16116   //
16117   // The rationale for this change is that the conditional-move from a constant
16118   // needs two instructions, however, conditional-move from a register needs
16119   // only one instruction.
16120   //
16121   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16122   //  some instruction-combining opportunities. This opt needs to be
16123   //  postponed as late as possible.
16124   //
16125   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16126     // the DCI.xxxx conditions are provided to postpone the optimization as
16127     // late as possible.
16128
16129     ConstantSDNode *CmpAgainst = 0;
16130     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16131         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16132         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16133
16134       if (CC == X86::COND_NE &&
16135           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16136         CC = X86::GetOppositeBranchCondition(CC);
16137         std::swap(TrueOp, FalseOp);
16138       }
16139
16140       if (CC == X86::COND_E &&
16141           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16142         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16143                           DAG.getConstant(CC, MVT::i8), Cond };
16144         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16145                            array_lengthof(Ops));
16146       }
16147     }
16148   }
16149
16150   return SDValue();
16151 }
16152
16153 /// PerformMulCombine - Optimize a single multiply with constant into two
16154 /// in order to implement it with two cheaper instructions, e.g.
16155 /// LEA + SHL, LEA + LEA.
16156 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16157                                  TargetLowering::DAGCombinerInfo &DCI) {
16158   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16159     return SDValue();
16160
16161   EVT VT = N->getValueType(0);
16162   if (VT != MVT::i64)
16163     return SDValue();
16164
16165   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16166   if (!C)
16167     return SDValue();
16168   uint64_t MulAmt = C->getZExtValue();
16169   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16170     return SDValue();
16171
16172   uint64_t MulAmt1 = 0;
16173   uint64_t MulAmt2 = 0;
16174   if ((MulAmt % 9) == 0) {
16175     MulAmt1 = 9;
16176     MulAmt2 = MulAmt / 9;
16177   } else if ((MulAmt % 5) == 0) {
16178     MulAmt1 = 5;
16179     MulAmt2 = MulAmt / 5;
16180   } else if ((MulAmt % 3) == 0) {
16181     MulAmt1 = 3;
16182     MulAmt2 = MulAmt / 3;
16183   }
16184   if (MulAmt2 &&
16185       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16186     DebugLoc DL = N->getDebugLoc();
16187
16188     if (isPowerOf2_64(MulAmt2) &&
16189         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16190       // If second multiplifer is pow2, issue it first. We want the multiply by
16191       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16192       // is an add.
16193       std::swap(MulAmt1, MulAmt2);
16194
16195     SDValue NewMul;
16196     if (isPowerOf2_64(MulAmt1))
16197       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16198                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16199     else
16200       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16201                            DAG.getConstant(MulAmt1, VT));
16202
16203     if (isPowerOf2_64(MulAmt2))
16204       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16205                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16206     else
16207       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16208                            DAG.getConstant(MulAmt2, VT));
16209
16210     // Do not add new nodes to DAG combiner worklist.
16211     DCI.CombineTo(N, NewMul, false);
16212   }
16213   return SDValue();
16214 }
16215
16216 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16217   SDValue N0 = N->getOperand(0);
16218   SDValue N1 = N->getOperand(1);
16219   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16220   EVT VT = N0.getValueType();
16221
16222   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16223   // since the result of setcc_c is all zero's or all ones.
16224   if (VT.isInteger() && !VT.isVector() &&
16225       N1C && N0.getOpcode() == ISD::AND &&
16226       N0.getOperand(1).getOpcode() == ISD::Constant) {
16227     SDValue N00 = N0.getOperand(0);
16228     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16229         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16230           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16231          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16232       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16233       APInt ShAmt = N1C->getAPIntValue();
16234       Mask = Mask.shl(ShAmt);
16235       if (Mask != 0)
16236         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16237                            N00, DAG.getConstant(Mask, VT));
16238     }
16239   }
16240
16241   // Hardware support for vector shifts is sparse which makes us scalarize the
16242   // vector operations in many cases. Also, on sandybridge ADD is faster than
16243   // shl.
16244   // (shl V, 1) -> add V,V
16245   if (isSplatVector(N1.getNode())) {
16246     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16247     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16248     // We shift all of the values by one. In many cases we do not have
16249     // hardware support for this operation. This is better expressed as an ADD
16250     // of two values.
16251     if (N1C && (1 == N1C->getZExtValue())) {
16252       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16253     }
16254   }
16255
16256   return SDValue();
16257 }
16258
16259 /// PerformShiftCombine - Combine shifts.
16260 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16261                                    TargetLowering::DAGCombinerInfo &DCI,
16262                                    const X86Subtarget *Subtarget) {
16263   if (N->getOpcode() == ISD::SHL) {
16264     SDValue V = PerformSHLCombine(N, DAG);
16265     if (V.getNode()) return V;
16266   }
16267
16268   return SDValue();
16269 }
16270
16271 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16272 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16273 // and friends.  Likewise for OR -> CMPNEQSS.
16274 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16275                             TargetLowering::DAGCombinerInfo &DCI,
16276                             const X86Subtarget *Subtarget) {
16277   unsigned opcode;
16278
16279   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16280   // we're requiring SSE2 for both.
16281   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16282     SDValue N0 = N->getOperand(0);
16283     SDValue N1 = N->getOperand(1);
16284     SDValue CMP0 = N0->getOperand(1);
16285     SDValue CMP1 = N1->getOperand(1);
16286     DebugLoc DL = N->getDebugLoc();
16287
16288     // The SETCCs should both refer to the same CMP.
16289     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16290       return SDValue();
16291
16292     SDValue CMP00 = CMP0->getOperand(0);
16293     SDValue CMP01 = CMP0->getOperand(1);
16294     EVT     VT    = CMP00.getValueType();
16295
16296     if (VT == MVT::f32 || VT == MVT::f64) {
16297       bool ExpectingFlags = false;
16298       // Check for any users that want flags:
16299       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16300            !ExpectingFlags && UI != UE; ++UI)
16301         switch (UI->getOpcode()) {
16302         default:
16303         case ISD::BR_CC:
16304         case ISD::BRCOND:
16305         case ISD::SELECT:
16306           ExpectingFlags = true;
16307           break;
16308         case ISD::CopyToReg:
16309         case ISD::SIGN_EXTEND:
16310         case ISD::ZERO_EXTEND:
16311         case ISD::ANY_EXTEND:
16312           break;
16313         }
16314
16315       if (!ExpectingFlags) {
16316         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16317         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16318
16319         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16320           X86::CondCode tmp = cc0;
16321           cc0 = cc1;
16322           cc1 = tmp;
16323         }
16324
16325         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16326             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16327           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16328           X86ISD::NodeType NTOperator = is64BitFP ?
16329             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16330           // FIXME: need symbolic constants for these magic numbers.
16331           // See X86ATTInstPrinter.cpp:printSSECC().
16332           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16333           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16334                                               DAG.getConstant(x86cc, MVT::i8));
16335           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16336                                               OnesOrZeroesF);
16337           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16338                                       DAG.getConstant(1, MVT::i32));
16339           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16340           return OneBitOfTruth;
16341         }
16342       }
16343     }
16344   }
16345   return SDValue();
16346 }
16347
16348 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16349 /// so it can be folded inside ANDNP.
16350 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16351   EVT VT = N->getValueType(0);
16352
16353   // Match direct AllOnes for 128 and 256-bit vectors
16354   if (ISD::isBuildVectorAllOnes(N))
16355     return true;
16356
16357   // Look through a bit convert.
16358   if (N->getOpcode() == ISD::BITCAST)
16359     N = N->getOperand(0).getNode();
16360
16361   // Sometimes the operand may come from a insert_subvector building a 256-bit
16362   // allones vector
16363   if (VT.is256BitVector() &&
16364       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16365     SDValue V1 = N->getOperand(0);
16366     SDValue V2 = N->getOperand(1);
16367
16368     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16369         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16370         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16371         ISD::isBuildVectorAllOnes(V2.getNode()))
16372       return true;
16373   }
16374
16375   return false;
16376 }
16377
16378 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16379 // register. In most cases we actually compare or select YMM-sized registers
16380 // and mixing the two types creates horrible code. This method optimizes
16381 // some of the transition sequences.
16382 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16383                                  TargetLowering::DAGCombinerInfo &DCI,
16384                                  const X86Subtarget *Subtarget) {
16385   EVT VT = N->getValueType(0);
16386   if (!VT.is256BitVector())
16387     return SDValue();
16388
16389   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16390           N->getOpcode() == ISD::ZERO_EXTEND ||
16391           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16392
16393   SDValue Narrow = N->getOperand(0);
16394   EVT NarrowVT = Narrow->getValueType(0);
16395   if (!NarrowVT.is128BitVector())
16396     return SDValue();
16397
16398   if (Narrow->getOpcode() != ISD::XOR &&
16399       Narrow->getOpcode() != ISD::AND &&
16400       Narrow->getOpcode() != ISD::OR)
16401     return SDValue();
16402
16403   SDValue N0  = Narrow->getOperand(0);
16404   SDValue N1  = Narrow->getOperand(1);
16405   DebugLoc DL = Narrow->getDebugLoc();
16406
16407   // The Left side has to be a trunc.
16408   if (N0.getOpcode() != ISD::TRUNCATE)
16409     return SDValue();
16410
16411   // The type of the truncated inputs.
16412   EVT WideVT = N0->getOperand(0)->getValueType(0);
16413   if (WideVT != VT)
16414     return SDValue();
16415
16416   // The right side has to be a 'trunc' or a constant vector.
16417   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16418   bool RHSConst = (isSplatVector(N1.getNode()) &&
16419                    isa<ConstantSDNode>(N1->getOperand(0)));
16420   if (!RHSTrunc && !RHSConst)
16421     return SDValue();
16422
16423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16424
16425   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16426     return SDValue();
16427
16428   // Set N0 and N1 to hold the inputs to the new wide operation.
16429   N0 = N0->getOperand(0);
16430   if (RHSConst) {
16431     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16432                      N1->getOperand(0));
16433     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16434     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16435   } else if (RHSTrunc) {
16436     N1 = N1->getOperand(0);
16437   }
16438
16439   // Generate the wide operation.
16440   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16441   unsigned Opcode = N->getOpcode();
16442   switch (Opcode) {
16443   case ISD::ANY_EXTEND:
16444     return Op;
16445   case ISD::ZERO_EXTEND: {
16446     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16447     APInt Mask = APInt::getAllOnesValue(InBits);
16448     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16449     return DAG.getNode(ISD::AND, DL, VT,
16450                        Op, DAG.getConstant(Mask, VT));
16451   }
16452   case ISD::SIGN_EXTEND:
16453     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16454                        Op, DAG.getValueType(NarrowVT));
16455   default:
16456     llvm_unreachable("Unexpected opcode");
16457   }
16458 }
16459
16460 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16461                                  TargetLowering::DAGCombinerInfo &DCI,
16462                                  const X86Subtarget *Subtarget) {
16463   EVT VT = N->getValueType(0);
16464   if (DCI.isBeforeLegalizeOps())
16465     return SDValue();
16466
16467   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16468   if (R.getNode())
16469     return R;
16470
16471   // Create BLSI, and BLSR instructions
16472   // BLSI is X & (-X)
16473   // BLSR is X & (X-1)
16474   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16475     SDValue N0 = N->getOperand(0);
16476     SDValue N1 = N->getOperand(1);
16477     DebugLoc DL = N->getDebugLoc();
16478
16479     // Check LHS for neg
16480     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16481         isZero(N0.getOperand(0)))
16482       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16483
16484     // Check RHS for neg
16485     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16486         isZero(N1.getOperand(0)))
16487       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16488
16489     // Check LHS for X-1
16490     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16491         isAllOnes(N0.getOperand(1)))
16492       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16493
16494     // Check RHS for X-1
16495     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16496         isAllOnes(N1.getOperand(1)))
16497       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16498
16499     return SDValue();
16500   }
16501
16502   // Want to form ANDNP nodes:
16503   // 1) In the hopes of then easily combining them with OR and AND nodes
16504   //    to form PBLEND/PSIGN.
16505   // 2) To match ANDN packed intrinsics
16506   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16507     return SDValue();
16508
16509   SDValue N0 = N->getOperand(0);
16510   SDValue N1 = N->getOperand(1);
16511   DebugLoc DL = N->getDebugLoc();
16512
16513   // Check LHS for vnot
16514   if (N0.getOpcode() == ISD::XOR &&
16515       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16516       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16517     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16518
16519   // Check RHS for vnot
16520   if (N1.getOpcode() == ISD::XOR &&
16521       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16522       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16523     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16524
16525   return SDValue();
16526 }
16527
16528 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16529                                 TargetLowering::DAGCombinerInfo &DCI,
16530                                 const X86Subtarget *Subtarget) {
16531   EVT VT = N->getValueType(0);
16532   if (DCI.isBeforeLegalizeOps())
16533     return SDValue();
16534
16535   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16536   if (R.getNode())
16537     return R;
16538
16539   SDValue N0 = N->getOperand(0);
16540   SDValue N1 = N->getOperand(1);
16541
16542   // look for psign/blend
16543   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16544     if (!Subtarget->hasSSSE3() ||
16545         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16546       return SDValue();
16547
16548     // Canonicalize pandn to RHS
16549     if (N0.getOpcode() == X86ISD::ANDNP)
16550       std::swap(N0, N1);
16551     // or (and (m, y), (pandn m, x))
16552     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16553       SDValue Mask = N1.getOperand(0);
16554       SDValue X    = N1.getOperand(1);
16555       SDValue Y;
16556       if (N0.getOperand(0) == Mask)
16557         Y = N0.getOperand(1);
16558       if (N0.getOperand(1) == Mask)
16559         Y = N0.getOperand(0);
16560
16561       // Check to see if the mask appeared in both the AND and ANDNP and
16562       if (!Y.getNode())
16563         return SDValue();
16564
16565       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16566       // Look through mask bitcast.
16567       if (Mask.getOpcode() == ISD::BITCAST)
16568         Mask = Mask.getOperand(0);
16569       if (X.getOpcode() == ISD::BITCAST)
16570         X = X.getOperand(0);
16571       if (Y.getOpcode() == ISD::BITCAST)
16572         Y = Y.getOperand(0);
16573
16574       EVT MaskVT = Mask.getValueType();
16575
16576       // Validate that the Mask operand is a vector sra node.
16577       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16578       // there is no psrai.b
16579       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16580       unsigned SraAmt = ~0;
16581       if (Mask.getOpcode() == ISD::SRA) {
16582         SDValue Amt = Mask.getOperand(1);
16583         if (isSplatVector(Amt.getNode())) {
16584           SDValue SclrAmt = Amt->getOperand(0);
16585           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16586             SraAmt = C->getZExtValue();
16587         }
16588       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16589         SDValue SraC = Mask.getOperand(1);
16590         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16591       }
16592       if ((SraAmt + 1) != EltBits)
16593         return SDValue();
16594
16595       DebugLoc DL = N->getDebugLoc();
16596
16597       // Now we know we at least have a plendvb with the mask val.  See if
16598       // we can form a psignb/w/d.
16599       // psign = x.type == y.type == mask.type && y = sub(0, x);
16600       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16601           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16602           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16603         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16604                "Unsupported VT for PSIGN");
16605         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16606         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16607       }
16608       // PBLENDVB only available on SSE 4.1
16609       if (!Subtarget->hasSSE41())
16610         return SDValue();
16611
16612       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16613
16614       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16615       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16616       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16617       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16618       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16619     }
16620   }
16621
16622   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16623     return SDValue();
16624
16625   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16626   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16627     std::swap(N0, N1);
16628   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16629     return SDValue();
16630   if (!N0.hasOneUse() || !N1.hasOneUse())
16631     return SDValue();
16632
16633   SDValue ShAmt0 = N0.getOperand(1);
16634   if (ShAmt0.getValueType() != MVT::i8)
16635     return SDValue();
16636   SDValue ShAmt1 = N1.getOperand(1);
16637   if (ShAmt1.getValueType() != MVT::i8)
16638     return SDValue();
16639   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16640     ShAmt0 = ShAmt0.getOperand(0);
16641   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16642     ShAmt1 = ShAmt1.getOperand(0);
16643
16644   DebugLoc DL = N->getDebugLoc();
16645   unsigned Opc = X86ISD::SHLD;
16646   SDValue Op0 = N0.getOperand(0);
16647   SDValue Op1 = N1.getOperand(0);
16648   if (ShAmt0.getOpcode() == ISD::SUB) {
16649     Opc = X86ISD::SHRD;
16650     std::swap(Op0, Op1);
16651     std::swap(ShAmt0, ShAmt1);
16652   }
16653
16654   unsigned Bits = VT.getSizeInBits();
16655   if (ShAmt1.getOpcode() == ISD::SUB) {
16656     SDValue Sum = ShAmt1.getOperand(0);
16657     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16658       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16659       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16660         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16661       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16662         return DAG.getNode(Opc, DL, VT,
16663                            Op0, Op1,
16664                            DAG.getNode(ISD::TRUNCATE, DL,
16665                                        MVT::i8, ShAmt0));
16666     }
16667   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16668     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16669     if (ShAmt0C &&
16670         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16671       return DAG.getNode(Opc, DL, VT,
16672                          N0.getOperand(0), N1.getOperand(0),
16673                          DAG.getNode(ISD::TRUNCATE, DL,
16674                                        MVT::i8, ShAmt0));
16675   }
16676
16677   return SDValue();
16678 }
16679
16680 // Generate NEG and CMOV for integer abs.
16681 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16682   EVT VT = N->getValueType(0);
16683
16684   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16685   // 8-bit integer abs to NEG and CMOV.
16686   if (VT.isInteger() && VT.getSizeInBits() == 8)
16687     return SDValue();
16688
16689   SDValue N0 = N->getOperand(0);
16690   SDValue N1 = N->getOperand(1);
16691   DebugLoc DL = N->getDebugLoc();
16692
16693   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16694   // and change it to SUB and CMOV.
16695   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16696       N0.getOpcode() == ISD::ADD &&
16697       N0.getOperand(1) == N1 &&
16698       N1.getOpcode() == ISD::SRA &&
16699       N1.getOperand(0) == N0.getOperand(0))
16700     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16701       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16702         // Generate SUB & CMOV.
16703         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16704                                   DAG.getConstant(0, VT), N0.getOperand(0));
16705
16706         SDValue Ops[] = { N0.getOperand(0), Neg,
16707                           DAG.getConstant(X86::COND_GE, MVT::i8),
16708                           SDValue(Neg.getNode(), 1) };
16709         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16710                            Ops, array_lengthof(Ops));
16711       }
16712   return SDValue();
16713 }
16714
16715 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16716 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16717                                  TargetLowering::DAGCombinerInfo &DCI,
16718                                  const X86Subtarget *Subtarget) {
16719   EVT VT = N->getValueType(0);
16720   if (DCI.isBeforeLegalizeOps())
16721     return SDValue();
16722
16723   if (Subtarget->hasCMov()) {
16724     SDValue RV = performIntegerAbsCombine(N, DAG);
16725     if (RV.getNode())
16726       return RV;
16727   }
16728
16729   // Try forming BMI if it is available.
16730   if (!Subtarget->hasBMI())
16731     return SDValue();
16732
16733   if (VT != MVT::i32 && VT != MVT::i64)
16734     return SDValue();
16735
16736   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16737
16738   // Create BLSMSK instructions by finding X ^ (X-1)
16739   SDValue N0 = N->getOperand(0);
16740   SDValue N1 = N->getOperand(1);
16741   DebugLoc DL = N->getDebugLoc();
16742
16743   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16744       isAllOnes(N0.getOperand(1)))
16745     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16746
16747   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16748       isAllOnes(N1.getOperand(1)))
16749     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16750
16751   return SDValue();
16752 }
16753
16754 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16755 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16756                                   TargetLowering::DAGCombinerInfo &DCI,
16757                                   const X86Subtarget *Subtarget) {
16758   LoadSDNode *Ld = cast<LoadSDNode>(N);
16759   EVT RegVT = Ld->getValueType(0);
16760   EVT MemVT = Ld->getMemoryVT();
16761   DebugLoc dl = Ld->getDebugLoc();
16762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16763   unsigned RegSz = RegVT.getSizeInBits();
16764
16765   // On Sandybridge unaligned 256bit loads are inefficient.
16766   ISD::LoadExtType Ext = Ld->getExtensionType();
16767   unsigned Alignment = Ld->getAlignment();
16768   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16769   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16770       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16771     unsigned NumElems = RegVT.getVectorNumElements();
16772     if (NumElems < 2)
16773       return SDValue();
16774
16775     SDValue Ptr = Ld->getBasePtr();
16776     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16777
16778     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16779                                   NumElems/2);
16780     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16781                                 Ld->getPointerInfo(), Ld->isVolatile(),
16782                                 Ld->isNonTemporal(), Ld->isInvariant(),
16783                                 Alignment);
16784     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16785     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16786                                 Ld->getPointerInfo(), Ld->isVolatile(),
16787                                 Ld->isNonTemporal(), Ld->isInvariant(),
16788                                 std::min(16U, Alignment));
16789     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16790                              Load1.getValue(1),
16791                              Load2.getValue(1));
16792
16793     SDValue NewVec = DAG.getUNDEF(RegVT);
16794     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16795     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16796     return DCI.CombineTo(N, NewVec, TF, true);
16797   }
16798
16799   // If this is a vector EXT Load then attempt to optimize it using a
16800   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16801   // expansion is still better than scalar code.
16802   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16803   // emit a shuffle and a arithmetic shift.
16804   // TODO: It is possible to support ZExt by zeroing the undef values
16805   // during the shuffle phase or after the shuffle.
16806   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16807       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16808     assert(MemVT != RegVT && "Cannot extend to the same type");
16809     assert(MemVT.isVector() && "Must load a vector from memory");
16810
16811     unsigned NumElems = RegVT.getVectorNumElements();
16812     unsigned MemSz = MemVT.getSizeInBits();
16813     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16814
16815     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16816       return SDValue();
16817
16818     // All sizes must be a power of two.
16819     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16820       return SDValue();
16821
16822     // Attempt to load the original value using scalar loads.
16823     // Find the largest scalar type that divides the total loaded size.
16824     MVT SclrLoadTy = MVT::i8;
16825     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16826          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16827       MVT Tp = (MVT::SimpleValueType)tp;
16828       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16829         SclrLoadTy = Tp;
16830       }
16831     }
16832
16833     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16834     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16835         (64 <= MemSz))
16836       SclrLoadTy = MVT::f64;
16837
16838     // Calculate the number of scalar loads that we need to perform
16839     // in order to load our vector from memory.
16840     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16841     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16842       return SDValue();
16843
16844     unsigned loadRegZize = RegSz;
16845     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16846       loadRegZize /= 2;
16847
16848     // Represent our vector as a sequence of elements which are the
16849     // largest scalar that we can load.
16850     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16851       loadRegZize/SclrLoadTy.getSizeInBits());
16852
16853     // Represent the data using the same element type that is stored in
16854     // memory. In practice, we ''widen'' MemVT.
16855     EVT WideVecVT =
16856           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16857                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16858
16859     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16860       "Invalid vector type");
16861
16862     // We can't shuffle using an illegal type.
16863     if (!TLI.isTypeLegal(WideVecVT))
16864       return SDValue();
16865
16866     SmallVector<SDValue, 8> Chains;
16867     SDValue Ptr = Ld->getBasePtr();
16868     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16869                                         TLI.getPointerTy());
16870     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16871
16872     for (unsigned i = 0; i < NumLoads; ++i) {
16873       // Perform a single load.
16874       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16875                                        Ptr, Ld->getPointerInfo(),
16876                                        Ld->isVolatile(), Ld->isNonTemporal(),
16877                                        Ld->isInvariant(), Ld->getAlignment());
16878       Chains.push_back(ScalarLoad.getValue(1));
16879       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16880       // another round of DAGCombining.
16881       if (i == 0)
16882         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16883       else
16884         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16885                           ScalarLoad, DAG.getIntPtrConstant(i));
16886
16887       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16888     }
16889
16890     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16891                                Chains.size());
16892
16893     // Bitcast the loaded value to a vector of the original element type, in
16894     // the size of the target vector type.
16895     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16896     unsigned SizeRatio = RegSz/MemSz;
16897
16898     if (Ext == ISD::SEXTLOAD) {
16899       // If we have SSE4.1 we can directly emit a VSEXT node.
16900       if (Subtarget->hasSSE41()) {
16901         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16902         return DCI.CombineTo(N, Sext, TF, true);
16903       }
16904
16905       // Otherwise we'll shuffle the small elements in the high bits of the
16906       // larger type and perform an arithmetic shift. If the shift is not legal
16907       // it's better to scalarize.
16908       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16909         return SDValue();
16910
16911       // Redistribute the loaded elements into the different locations.
16912       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16913       for (unsigned i = 0; i != NumElems; ++i)
16914         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16915
16916       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16917                                            DAG.getUNDEF(WideVecVT),
16918                                            &ShuffleVec[0]);
16919
16920       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16921
16922       // Build the arithmetic shift.
16923       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16924                      MemVT.getVectorElementType().getSizeInBits();
16925       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16926                           DAG.getConstant(Amt, RegVT));
16927
16928       return DCI.CombineTo(N, Shuff, TF, true);
16929     }
16930
16931     // Redistribute the loaded elements into the different locations.
16932     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16933     for (unsigned i = 0; i != NumElems; ++i)
16934       ShuffleVec[i*SizeRatio] = i;
16935
16936     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16937                                          DAG.getUNDEF(WideVecVT),
16938                                          &ShuffleVec[0]);
16939
16940     // Bitcast to the requested type.
16941     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16942     // Replace the original load with the new sequence
16943     // and return the new chain.
16944     return DCI.CombineTo(N, Shuff, TF, true);
16945   }
16946
16947   return SDValue();
16948 }
16949
16950 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16951 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16952                                    const X86Subtarget *Subtarget) {
16953   StoreSDNode *St = cast<StoreSDNode>(N);
16954   EVT VT = St->getValue().getValueType();
16955   EVT StVT = St->getMemoryVT();
16956   DebugLoc dl = St->getDebugLoc();
16957   SDValue StoredVal = St->getOperand(1);
16958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16959
16960   // If we are saving a concatenation of two XMM registers, perform two stores.
16961   // On Sandy Bridge, 256-bit memory operations are executed by two
16962   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16963   // memory  operation.
16964   unsigned Alignment = St->getAlignment();
16965   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
16966   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16967       StVT == VT && !IsAligned) {
16968     unsigned NumElems = VT.getVectorNumElements();
16969     if (NumElems < 2)
16970       return SDValue();
16971
16972     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16973     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16974
16975     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16976     SDValue Ptr0 = St->getBasePtr();
16977     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16978
16979     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16980                                 St->getPointerInfo(), St->isVolatile(),
16981                                 St->isNonTemporal(), Alignment);
16982     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16983                                 St->getPointerInfo(), St->isVolatile(),
16984                                 St->isNonTemporal(),
16985                                 std::min(16U, Alignment));
16986     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16987   }
16988
16989   // Optimize trunc store (of multiple scalars) to shuffle and store.
16990   // First, pack all of the elements in one place. Next, store to memory
16991   // in fewer chunks.
16992   if (St->isTruncatingStore() && VT.isVector()) {
16993     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16994     unsigned NumElems = VT.getVectorNumElements();
16995     assert(StVT != VT && "Cannot truncate to the same type");
16996     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16997     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16998
16999     // From, To sizes and ElemCount must be pow of two
17000     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17001     // We are going to use the original vector elt for storing.
17002     // Accumulated smaller vector elements must be a multiple of the store size.
17003     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17004
17005     unsigned SizeRatio  = FromSz / ToSz;
17006
17007     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17008
17009     // Create a type on which we perform the shuffle
17010     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17011             StVT.getScalarType(), NumElems*SizeRatio);
17012
17013     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17014
17015     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17016     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17017     for (unsigned i = 0; i != NumElems; ++i)
17018       ShuffleVec[i] = i * SizeRatio;
17019
17020     // Can't shuffle using an illegal type.
17021     if (!TLI.isTypeLegal(WideVecVT))
17022       return SDValue();
17023
17024     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17025                                          DAG.getUNDEF(WideVecVT),
17026                                          &ShuffleVec[0]);
17027     // At this point all of the data is stored at the bottom of the
17028     // register. We now need to save it to mem.
17029
17030     // Find the largest store unit
17031     MVT StoreType = MVT::i8;
17032     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17033          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17034       MVT Tp = (MVT::SimpleValueType)tp;
17035       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17036         StoreType = Tp;
17037     }
17038
17039     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17040     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17041         (64 <= NumElems * ToSz))
17042       StoreType = MVT::f64;
17043
17044     // Bitcast the original vector into a vector of store-size units
17045     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17046             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17047     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17048     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17049     SmallVector<SDValue, 8> Chains;
17050     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17051                                         TLI.getPointerTy());
17052     SDValue Ptr = St->getBasePtr();
17053
17054     // Perform one or more big stores into memory.
17055     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17056       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17057                                    StoreType, ShuffWide,
17058                                    DAG.getIntPtrConstant(i));
17059       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17060                                 St->getPointerInfo(), St->isVolatile(),
17061                                 St->isNonTemporal(), St->getAlignment());
17062       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17063       Chains.push_back(Ch);
17064     }
17065
17066     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17067                                Chains.size());
17068   }
17069
17070   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17071   // the FP state in cases where an emms may be missing.
17072   // A preferable solution to the general problem is to figure out the right
17073   // places to insert EMMS.  This qualifies as a quick hack.
17074
17075   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17076   if (VT.getSizeInBits() != 64)
17077     return SDValue();
17078
17079   const Function *F = DAG.getMachineFunction().getFunction();
17080   bool NoImplicitFloatOps = F->getAttributes().
17081     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17082   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17083                      && Subtarget->hasSSE2();
17084   if ((VT.isVector() ||
17085        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17086       isa<LoadSDNode>(St->getValue()) &&
17087       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17088       St->getChain().hasOneUse() && !St->isVolatile()) {
17089     SDNode* LdVal = St->getValue().getNode();
17090     LoadSDNode *Ld = 0;
17091     int TokenFactorIndex = -1;
17092     SmallVector<SDValue, 8> Ops;
17093     SDNode* ChainVal = St->getChain().getNode();
17094     // Must be a store of a load.  We currently handle two cases:  the load
17095     // is a direct child, and it's under an intervening TokenFactor.  It is
17096     // possible to dig deeper under nested TokenFactors.
17097     if (ChainVal == LdVal)
17098       Ld = cast<LoadSDNode>(St->getChain());
17099     else if (St->getValue().hasOneUse() &&
17100              ChainVal->getOpcode() == ISD::TokenFactor) {
17101       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17102         if (ChainVal->getOperand(i).getNode() == LdVal) {
17103           TokenFactorIndex = i;
17104           Ld = cast<LoadSDNode>(St->getValue());
17105         } else
17106           Ops.push_back(ChainVal->getOperand(i));
17107       }
17108     }
17109
17110     if (!Ld || !ISD::isNormalLoad(Ld))
17111       return SDValue();
17112
17113     // If this is not the MMX case, i.e. we are just turning i64 load/store
17114     // into f64 load/store, avoid the transformation if there are multiple
17115     // uses of the loaded value.
17116     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17117       return SDValue();
17118
17119     DebugLoc LdDL = Ld->getDebugLoc();
17120     DebugLoc StDL = N->getDebugLoc();
17121     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17122     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17123     // pair instead.
17124     if (Subtarget->is64Bit() || F64IsLegal) {
17125       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17126       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17127                                   Ld->getPointerInfo(), Ld->isVolatile(),
17128                                   Ld->isNonTemporal(), Ld->isInvariant(),
17129                                   Ld->getAlignment());
17130       SDValue NewChain = NewLd.getValue(1);
17131       if (TokenFactorIndex != -1) {
17132         Ops.push_back(NewChain);
17133         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17134                                Ops.size());
17135       }
17136       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17137                           St->getPointerInfo(),
17138                           St->isVolatile(), St->isNonTemporal(),
17139                           St->getAlignment());
17140     }
17141
17142     // Otherwise, lower to two pairs of 32-bit loads / stores.
17143     SDValue LoAddr = Ld->getBasePtr();
17144     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17145                                  DAG.getConstant(4, MVT::i32));
17146
17147     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17148                                Ld->getPointerInfo(),
17149                                Ld->isVolatile(), Ld->isNonTemporal(),
17150                                Ld->isInvariant(), Ld->getAlignment());
17151     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17152                                Ld->getPointerInfo().getWithOffset(4),
17153                                Ld->isVolatile(), Ld->isNonTemporal(),
17154                                Ld->isInvariant(),
17155                                MinAlign(Ld->getAlignment(), 4));
17156
17157     SDValue NewChain = LoLd.getValue(1);
17158     if (TokenFactorIndex != -1) {
17159       Ops.push_back(LoLd);
17160       Ops.push_back(HiLd);
17161       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17162                              Ops.size());
17163     }
17164
17165     LoAddr = St->getBasePtr();
17166     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17167                          DAG.getConstant(4, MVT::i32));
17168
17169     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17170                                 St->getPointerInfo(),
17171                                 St->isVolatile(), St->isNonTemporal(),
17172                                 St->getAlignment());
17173     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17174                                 St->getPointerInfo().getWithOffset(4),
17175                                 St->isVolatile(),
17176                                 St->isNonTemporal(),
17177                                 MinAlign(St->getAlignment(), 4));
17178     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17179   }
17180   return SDValue();
17181 }
17182
17183 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17184 /// and return the operands for the horizontal operation in LHS and RHS.  A
17185 /// horizontal operation performs the binary operation on successive elements
17186 /// of its first operand, then on successive elements of its second operand,
17187 /// returning the resulting values in a vector.  For example, if
17188 ///   A = < float a0, float a1, float a2, float a3 >
17189 /// and
17190 ///   B = < float b0, float b1, float b2, float b3 >
17191 /// then the result of doing a horizontal operation on A and B is
17192 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17193 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17194 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17195 /// set to A, RHS to B, and the routine returns 'true'.
17196 /// Note that the binary operation should have the property that if one of the
17197 /// operands is UNDEF then the result is UNDEF.
17198 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17199   // Look for the following pattern: if
17200   //   A = < float a0, float a1, float a2, float a3 >
17201   //   B = < float b0, float b1, float b2, float b3 >
17202   // and
17203   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17204   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17205   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17206   // which is A horizontal-op B.
17207
17208   // At least one of the operands should be a vector shuffle.
17209   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17210       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17211     return false;
17212
17213   EVT VT = LHS.getValueType();
17214
17215   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17216          "Unsupported vector type for horizontal add/sub");
17217
17218   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17219   // operate independently on 128-bit lanes.
17220   unsigned NumElts = VT.getVectorNumElements();
17221   unsigned NumLanes = VT.getSizeInBits()/128;
17222   unsigned NumLaneElts = NumElts / NumLanes;
17223   assert((NumLaneElts % 2 == 0) &&
17224          "Vector type should have an even number of elements in each lane");
17225   unsigned HalfLaneElts = NumLaneElts/2;
17226
17227   // View LHS in the form
17228   //   LHS = VECTOR_SHUFFLE A, B, LMask
17229   // If LHS is not a shuffle then pretend it is the shuffle
17230   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17231   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17232   // type VT.
17233   SDValue A, B;
17234   SmallVector<int, 16> LMask(NumElts);
17235   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17236     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17237       A = LHS.getOperand(0);
17238     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17239       B = LHS.getOperand(1);
17240     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17241     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17242   } else {
17243     if (LHS.getOpcode() != ISD::UNDEF)
17244       A = LHS;
17245     for (unsigned i = 0; i != NumElts; ++i)
17246       LMask[i] = i;
17247   }
17248
17249   // Likewise, view RHS in the form
17250   //   RHS = VECTOR_SHUFFLE C, D, RMask
17251   SDValue C, D;
17252   SmallVector<int, 16> RMask(NumElts);
17253   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17254     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17255       C = RHS.getOperand(0);
17256     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17257       D = RHS.getOperand(1);
17258     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17259     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17260   } else {
17261     if (RHS.getOpcode() != ISD::UNDEF)
17262       C = RHS;
17263     for (unsigned i = 0; i != NumElts; ++i)
17264       RMask[i] = i;
17265   }
17266
17267   // Check that the shuffles are both shuffling the same vectors.
17268   if (!(A == C && B == D) && !(A == D && B == C))
17269     return false;
17270
17271   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17272   if (!A.getNode() && !B.getNode())
17273     return false;
17274
17275   // If A and B occur in reverse order in RHS, then "swap" them (which means
17276   // rewriting the mask).
17277   if (A != C)
17278     CommuteVectorShuffleMask(RMask, NumElts);
17279
17280   // At this point LHS and RHS are equivalent to
17281   //   LHS = VECTOR_SHUFFLE A, B, LMask
17282   //   RHS = VECTOR_SHUFFLE A, B, RMask
17283   // Check that the masks correspond to performing a horizontal operation.
17284   for (unsigned i = 0; i != NumElts; ++i) {
17285     int LIdx = LMask[i], RIdx = RMask[i];
17286
17287     // Ignore any UNDEF components.
17288     if (LIdx < 0 || RIdx < 0 ||
17289         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17290         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17291       continue;
17292
17293     // Check that successive elements are being operated on.  If not, this is
17294     // not a horizontal operation.
17295     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17296     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17297     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17298     if (!(LIdx == Index && RIdx == Index + 1) &&
17299         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17300       return false;
17301   }
17302
17303   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17304   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17305   return true;
17306 }
17307
17308 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17309 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17310                                   const X86Subtarget *Subtarget) {
17311   EVT VT = N->getValueType(0);
17312   SDValue LHS = N->getOperand(0);
17313   SDValue RHS = N->getOperand(1);
17314
17315   // Try to synthesize horizontal adds from adds of shuffles.
17316   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17317        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17318       isHorizontalBinOp(LHS, RHS, true))
17319     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17320   return SDValue();
17321 }
17322
17323 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17324 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17325                                   const X86Subtarget *Subtarget) {
17326   EVT VT = N->getValueType(0);
17327   SDValue LHS = N->getOperand(0);
17328   SDValue RHS = N->getOperand(1);
17329
17330   // Try to synthesize horizontal subs from subs of shuffles.
17331   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17332        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17333       isHorizontalBinOp(LHS, RHS, false))
17334     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17335   return SDValue();
17336 }
17337
17338 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17339 /// X86ISD::FXOR nodes.
17340 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17341   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17342   // F[X]OR(0.0, x) -> x
17343   // F[X]OR(x, 0.0) -> x
17344   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17345     if (C->getValueAPF().isPosZero())
17346       return N->getOperand(1);
17347   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17348     if (C->getValueAPF().isPosZero())
17349       return N->getOperand(0);
17350   return SDValue();
17351 }
17352
17353 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17354 /// X86ISD::FMAX nodes.
17355 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17356   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17357
17358   // Only perform optimizations if UnsafeMath is used.
17359   if (!DAG.getTarget().Options.UnsafeFPMath)
17360     return SDValue();
17361
17362   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17363   // into FMINC and FMAXC, which are Commutative operations.
17364   unsigned NewOp = 0;
17365   switch (N->getOpcode()) {
17366     default: llvm_unreachable("unknown opcode");
17367     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17368     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17369   }
17370
17371   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17372                      N->getOperand(0), N->getOperand(1));
17373 }
17374
17375 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17376 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17377   // FAND(0.0, x) -> 0.0
17378   // FAND(x, 0.0) -> 0.0
17379   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17380     if (C->getValueAPF().isPosZero())
17381       return N->getOperand(0);
17382   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17383     if (C->getValueAPF().isPosZero())
17384       return N->getOperand(1);
17385   return SDValue();
17386 }
17387
17388 static SDValue PerformBTCombine(SDNode *N,
17389                                 SelectionDAG &DAG,
17390                                 TargetLowering::DAGCombinerInfo &DCI) {
17391   // BT ignores high bits in the bit index operand.
17392   SDValue Op1 = N->getOperand(1);
17393   if (Op1.hasOneUse()) {
17394     unsigned BitWidth = Op1.getValueSizeInBits();
17395     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17396     APInt KnownZero, KnownOne;
17397     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17398                                           !DCI.isBeforeLegalizeOps());
17399     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17400     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17401         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17402       DCI.CommitTargetLoweringOpt(TLO);
17403   }
17404   return SDValue();
17405 }
17406
17407 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17408   SDValue Op = N->getOperand(0);
17409   if (Op.getOpcode() == ISD::BITCAST)
17410     Op = Op.getOperand(0);
17411   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17412   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17413       VT.getVectorElementType().getSizeInBits() ==
17414       OpVT.getVectorElementType().getSizeInBits()) {
17415     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17416   }
17417   return SDValue();
17418 }
17419
17420 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 
17421                                                const X86Subtarget *Subtarget) {
17422   EVT VT = N->getValueType(0);
17423   if (!VT.isVector())
17424     return SDValue();
17425
17426   SDValue N0 = N->getOperand(0);
17427   SDValue N1 = N->getOperand(1);
17428   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17429   DebugLoc dl = N->getDebugLoc();
17430
17431   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17432   // both SSE and AVX2 since there is no sign-extended shift right
17433   // operation on a vector with 64-bit elements.
17434   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17435   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17436   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17437       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17438     SDValue N00 = N0.getOperand(0);
17439
17440     // EXTLOAD has a better solution on AVX2, 
17441     // it may be replaced with X86ISD::VSEXT node.
17442     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17443       if (!ISD::isNormalLoad(N00.getNode()))
17444         return SDValue();
17445
17446     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17447         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 
17448                                   N00, N1);
17449       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17450     }
17451   }
17452   return SDValue();
17453 }
17454
17455 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17456                                   TargetLowering::DAGCombinerInfo &DCI,
17457                                   const X86Subtarget *Subtarget) {
17458   if (!DCI.isBeforeLegalizeOps())
17459     return SDValue();
17460
17461   if (!Subtarget->hasFp256())
17462     return SDValue();
17463
17464   EVT VT = N->getValueType(0);
17465   if (VT.isVector() && VT.getSizeInBits() == 256) {
17466     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17467     if (R.getNode())
17468       return R;
17469   }
17470
17471   return SDValue();
17472 }
17473
17474 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17475                                  const X86Subtarget* Subtarget) {
17476   DebugLoc dl = N->getDebugLoc();
17477   EVT VT = N->getValueType(0);
17478
17479   // Let legalize expand this if it isn't a legal type yet.
17480   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17481     return SDValue();
17482
17483   EVT ScalarVT = VT.getScalarType();
17484   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17485       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17486     return SDValue();
17487
17488   SDValue A = N->getOperand(0);
17489   SDValue B = N->getOperand(1);
17490   SDValue C = N->getOperand(2);
17491
17492   bool NegA = (A.getOpcode() == ISD::FNEG);
17493   bool NegB = (B.getOpcode() == ISD::FNEG);
17494   bool NegC = (C.getOpcode() == ISD::FNEG);
17495
17496   // Negative multiplication when NegA xor NegB
17497   bool NegMul = (NegA != NegB);
17498   if (NegA)
17499     A = A.getOperand(0);
17500   if (NegB)
17501     B = B.getOperand(0);
17502   if (NegC)
17503     C = C.getOperand(0);
17504
17505   unsigned Opcode;
17506   if (!NegMul)
17507     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17508   else
17509     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17510
17511   return DAG.getNode(Opcode, dl, VT, A, B, C);
17512 }
17513
17514 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17515                                   TargetLowering::DAGCombinerInfo &DCI,
17516                                   const X86Subtarget *Subtarget) {
17517   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17518   //           (and (i32 x86isd::setcc_carry), 1)
17519   // This eliminates the zext. This transformation is necessary because
17520   // ISD::SETCC is always legalized to i8.
17521   DebugLoc dl = N->getDebugLoc();
17522   SDValue N0 = N->getOperand(0);
17523   EVT VT = N->getValueType(0);
17524
17525   if (N0.getOpcode() == ISD::AND &&
17526       N0.hasOneUse() &&
17527       N0.getOperand(0).hasOneUse()) {
17528     SDValue N00 = N0.getOperand(0);
17529     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17530       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17531       if (!C || C->getZExtValue() != 1)
17532         return SDValue();
17533       return DAG.getNode(ISD::AND, dl, VT,
17534                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17535                                      N00.getOperand(0), N00.getOperand(1)),
17536                          DAG.getConstant(1, VT));
17537     }
17538   }
17539
17540   if (VT.is256BitVector()) {
17541     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17542     if (R.getNode())
17543       return R;
17544   }
17545
17546   return SDValue();
17547 }
17548
17549 // Optimize x == -y --> x+y == 0
17550 //          x != -y --> x+y != 0
17551 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17552   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17553   SDValue LHS = N->getOperand(0);
17554   SDValue RHS = N->getOperand(1);
17555
17556   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17557     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17558       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17559         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17560                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17561         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17562                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17563       }
17564   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17565     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17566       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17567         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17568                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17569         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17570                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17571       }
17572   return SDValue();
17573 }
17574
17575 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17576 // as "sbb reg,reg", since it can be extended without zext and produces
17577 // an all-ones bit which is more useful than 0/1 in some cases.
17578 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17579   return DAG.getNode(ISD::AND, DL, MVT::i8,
17580                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17581                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17582                      DAG.getConstant(1, MVT::i8));
17583 }
17584
17585 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17586 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17587                                    TargetLowering::DAGCombinerInfo &DCI,
17588                                    const X86Subtarget *Subtarget) {
17589   DebugLoc DL = N->getDebugLoc();
17590   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17591   SDValue EFLAGS = N->getOperand(1);
17592
17593   if (CC == X86::COND_A) {
17594     // Try to convert COND_A into COND_B in an attempt to facilitate
17595     // materializing "setb reg".
17596     //
17597     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17598     // cannot take an immediate as its first operand.
17599     //
17600     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17601         EFLAGS.getValueType().isInteger() &&
17602         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17603       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17604                                    EFLAGS.getNode()->getVTList(),
17605                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17606       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17607       return MaterializeSETB(DL, NewEFLAGS, DAG);
17608     }
17609   }
17610
17611   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17612   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17613   // cases.
17614   if (CC == X86::COND_B)
17615     return MaterializeSETB(DL, EFLAGS, DAG);
17616
17617   SDValue Flags;
17618
17619   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17620   if (Flags.getNode()) {
17621     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17622     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17623   }
17624
17625   return SDValue();
17626 }
17627
17628 // Optimize branch condition evaluation.
17629 //
17630 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17631                                     TargetLowering::DAGCombinerInfo &DCI,
17632                                     const X86Subtarget *Subtarget) {
17633   DebugLoc DL = N->getDebugLoc();
17634   SDValue Chain = N->getOperand(0);
17635   SDValue Dest = N->getOperand(1);
17636   SDValue EFLAGS = N->getOperand(3);
17637   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17638
17639   SDValue Flags;
17640
17641   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17642   if (Flags.getNode()) {
17643     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17644     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17645                        Flags);
17646   }
17647
17648   return SDValue();
17649 }
17650
17651 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17652                                         const X86TargetLowering *XTLI) {
17653   SDValue Op0 = N->getOperand(0);
17654   EVT InVT = Op0->getValueType(0);
17655
17656   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17657   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17658     DebugLoc dl = N->getDebugLoc();
17659     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17660     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17661     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17662   }
17663
17664   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17665   // a 32-bit target where SSE doesn't support i64->FP operations.
17666   if (Op0.getOpcode() == ISD::LOAD) {
17667     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17668     EVT VT = Ld->getValueType(0);
17669     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17670         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17671         !XTLI->getSubtarget()->is64Bit() &&
17672         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17673       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17674                                           Ld->getChain(), Op0, DAG);
17675       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17676       return FILDChain;
17677     }
17678   }
17679   return SDValue();
17680 }
17681
17682 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17683 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17684                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17685   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17686   // the result is either zero or one (depending on the input carry bit).
17687   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17688   if (X86::isZeroNode(N->getOperand(0)) &&
17689       X86::isZeroNode(N->getOperand(1)) &&
17690       // We don't have a good way to replace an EFLAGS use, so only do this when
17691       // dead right now.
17692       SDValue(N, 1).use_empty()) {
17693     DebugLoc DL = N->getDebugLoc();
17694     EVT VT = N->getValueType(0);
17695     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17696     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17697                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17698                                            DAG.getConstant(X86::COND_B,MVT::i8),
17699                                            N->getOperand(2)),
17700                                DAG.getConstant(1, VT));
17701     return DCI.CombineTo(N, Res1, CarryOut);
17702   }
17703
17704   return SDValue();
17705 }
17706
17707 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17708 //      (add Y, (setne X, 0)) -> sbb -1, Y
17709 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17710 //      (sub (setne X, 0), Y) -> adc -1, Y
17711 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17712   DebugLoc DL = N->getDebugLoc();
17713
17714   // Look through ZExts.
17715   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17716   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17717     return SDValue();
17718
17719   SDValue SetCC = Ext.getOperand(0);
17720   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17721     return SDValue();
17722
17723   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17724   if (CC != X86::COND_E && CC != X86::COND_NE)
17725     return SDValue();
17726
17727   SDValue Cmp = SetCC.getOperand(1);
17728   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17729       !X86::isZeroNode(Cmp.getOperand(1)) ||
17730       !Cmp.getOperand(0).getValueType().isInteger())
17731     return SDValue();
17732
17733   SDValue CmpOp0 = Cmp.getOperand(0);
17734   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17735                                DAG.getConstant(1, CmpOp0.getValueType()));
17736
17737   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17738   if (CC == X86::COND_NE)
17739     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17740                        DL, OtherVal.getValueType(), OtherVal,
17741                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17742   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17743                      DL, OtherVal.getValueType(), OtherVal,
17744                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17745 }
17746
17747 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17748 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17749                                  const X86Subtarget *Subtarget) {
17750   EVT VT = N->getValueType(0);
17751   SDValue Op0 = N->getOperand(0);
17752   SDValue Op1 = N->getOperand(1);
17753
17754   // Try to synthesize horizontal adds from adds of shuffles.
17755   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17756        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17757       isHorizontalBinOp(Op0, Op1, true))
17758     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17759
17760   return OptimizeConditionalInDecrement(N, DAG);
17761 }
17762
17763 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17764                                  const X86Subtarget *Subtarget) {
17765   SDValue Op0 = N->getOperand(0);
17766   SDValue Op1 = N->getOperand(1);
17767
17768   // X86 can't encode an immediate LHS of a sub. See if we can push the
17769   // negation into a preceding instruction.
17770   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17771     // If the RHS of the sub is a XOR with one use and a constant, invert the
17772     // immediate. Then add one to the LHS of the sub so we can turn
17773     // X-Y -> X+~Y+1, saving one register.
17774     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17775         isa<ConstantSDNode>(Op1.getOperand(1))) {
17776       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17777       EVT VT = Op0.getValueType();
17778       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17779                                    Op1.getOperand(0),
17780                                    DAG.getConstant(~XorC, VT));
17781       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17782                          DAG.getConstant(C->getAPIntValue()+1, VT));
17783     }
17784   }
17785
17786   // Try to synthesize horizontal adds from adds of shuffles.
17787   EVT VT = N->getValueType(0);
17788   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17789        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17790       isHorizontalBinOp(Op0, Op1, true))
17791     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17792
17793   return OptimizeConditionalInDecrement(N, DAG);
17794 }
17795
17796 /// performVZEXTCombine - Performs build vector combines
17797 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17798                                         TargetLowering::DAGCombinerInfo &DCI,
17799                                         const X86Subtarget *Subtarget) {
17800   // (vzext (bitcast (vzext (x)) -> (vzext x)
17801   SDValue In = N->getOperand(0);
17802   while (In.getOpcode() == ISD::BITCAST)
17803     In = In.getOperand(0);
17804
17805   if (In.getOpcode() != X86ISD::VZEXT)
17806     return SDValue();
17807
17808   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17809                      In.getOperand(0));
17810 }
17811
17812 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17813                                              DAGCombinerInfo &DCI) const {
17814   SelectionDAG &DAG = DCI.DAG;
17815   switch (N->getOpcode()) {
17816   default: break;
17817   case ISD::EXTRACT_VECTOR_ELT:
17818     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17819   case ISD::VSELECT:
17820   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17821   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17822   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17823   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17824   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17825   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17826   case ISD::SHL:
17827   case ISD::SRA:
17828   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17829   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17830   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17831   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17832   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17833   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17834   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17835   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17836   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17837   case X86ISD::FXOR:
17838   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17839   case X86ISD::FMIN:
17840   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17841   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17842   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17843   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17844   case ISD::ANY_EXTEND:
17845   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17846   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17847   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17848   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17849   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17850   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17851   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17852   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17853   case X86ISD::SHUFP:       // Handle all target specific shuffles
17854   case X86ISD::PALIGNR:
17855   case X86ISD::UNPCKH:
17856   case X86ISD::UNPCKL:
17857   case X86ISD::MOVHLPS:
17858   case X86ISD::MOVLHPS:
17859   case X86ISD::PSHUFD:
17860   case X86ISD::PSHUFHW:
17861   case X86ISD::PSHUFLW:
17862   case X86ISD::MOVSS:
17863   case X86ISD::MOVSD:
17864   case X86ISD::VPERMILP:
17865   case X86ISD::VPERM2X128:
17866   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17867   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17868   }
17869
17870   return SDValue();
17871 }
17872
17873 /// isTypeDesirableForOp - Return true if the target has native support for
17874 /// the specified value type and it is 'desirable' to use the type for the
17875 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17876 /// instruction encodings are longer and some i16 instructions are slow.
17877 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17878   if (!isTypeLegal(VT))
17879     return false;
17880   if (VT != MVT::i16)
17881     return true;
17882
17883   switch (Opc) {
17884   default:
17885     return true;
17886   case ISD::LOAD:
17887   case ISD::SIGN_EXTEND:
17888   case ISD::ZERO_EXTEND:
17889   case ISD::ANY_EXTEND:
17890   case ISD::SHL:
17891   case ISD::SRL:
17892   case ISD::SUB:
17893   case ISD::ADD:
17894   case ISD::MUL:
17895   case ISD::AND:
17896   case ISD::OR:
17897   case ISD::XOR:
17898     return false;
17899   }
17900 }
17901
17902 /// IsDesirableToPromoteOp - This method query the target whether it is
17903 /// beneficial for dag combiner to promote the specified node. If true, it
17904 /// should return the desired promotion type by reference.
17905 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17906   EVT VT = Op.getValueType();
17907   if (VT != MVT::i16)
17908     return false;
17909
17910   bool Promote = false;
17911   bool Commute = false;
17912   switch (Op.getOpcode()) {
17913   default: break;
17914   case ISD::LOAD: {
17915     LoadSDNode *LD = cast<LoadSDNode>(Op);
17916     // If the non-extending load has a single use and it's not live out, then it
17917     // might be folded.
17918     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17919                                                      Op.hasOneUse()*/) {
17920       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17921              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17922         // The only case where we'd want to promote LOAD (rather then it being
17923         // promoted as an operand is when it's only use is liveout.
17924         if (UI->getOpcode() != ISD::CopyToReg)
17925           return false;
17926       }
17927     }
17928     Promote = true;
17929     break;
17930   }
17931   case ISD::SIGN_EXTEND:
17932   case ISD::ZERO_EXTEND:
17933   case ISD::ANY_EXTEND:
17934     Promote = true;
17935     break;
17936   case ISD::SHL:
17937   case ISD::SRL: {
17938     SDValue N0 = Op.getOperand(0);
17939     // Look out for (store (shl (load), x)).
17940     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17941       return false;
17942     Promote = true;
17943     break;
17944   }
17945   case ISD::ADD:
17946   case ISD::MUL:
17947   case ISD::AND:
17948   case ISD::OR:
17949   case ISD::XOR:
17950     Commute = true;
17951     // fallthrough
17952   case ISD::SUB: {
17953     SDValue N0 = Op.getOperand(0);
17954     SDValue N1 = Op.getOperand(1);
17955     if (!Commute && MayFoldLoad(N1))
17956       return false;
17957     // Avoid disabling potential load folding opportunities.
17958     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17959       return false;
17960     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17961       return false;
17962     Promote = true;
17963   }
17964   }
17965
17966   PVT = MVT::i32;
17967   return Promote;
17968 }
17969
17970 //===----------------------------------------------------------------------===//
17971 //                           X86 Inline Assembly Support
17972 //===----------------------------------------------------------------------===//
17973
17974 namespace {
17975   // Helper to match a string separated by whitespace.
17976   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17977     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17978
17979     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17980       StringRef piece(*args[i]);
17981       if (!s.startswith(piece)) // Check if the piece matches.
17982         return false;
17983
17984       s = s.substr(piece.size());
17985       StringRef::size_type pos = s.find_first_not_of(" \t");
17986       if (pos == 0) // We matched a prefix.
17987         return false;
17988
17989       s = s.substr(pos);
17990     }
17991
17992     return s.empty();
17993   }
17994   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17995 }
17996
17997 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17998   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17999
18000   std::string AsmStr = IA->getAsmString();
18001
18002   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18003   if (!Ty || Ty->getBitWidth() % 16 != 0)
18004     return false;
18005
18006   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18007   SmallVector<StringRef, 4> AsmPieces;
18008   SplitString(AsmStr, AsmPieces, ";\n");
18009
18010   switch (AsmPieces.size()) {
18011   default: return false;
18012   case 1:
18013     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18014     // we will turn this bswap into something that will be lowered to logical
18015     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18016     // lower so don't worry about this.
18017     // bswap $0
18018     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18019         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18020         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18021         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18022         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18023         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18024       // No need to check constraints, nothing other than the equivalent of
18025       // "=r,0" would be valid here.
18026       return IntrinsicLowering::LowerToByteSwap(CI);
18027     }
18028
18029     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18030     if (CI->getType()->isIntegerTy(16) &&
18031         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18032         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18033          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18034       AsmPieces.clear();
18035       const std::string &ConstraintsStr = IA->getConstraintString();
18036       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18037       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18038       if (AsmPieces.size() == 4 &&
18039           AsmPieces[0] == "~{cc}" &&
18040           AsmPieces[1] == "~{dirflag}" &&
18041           AsmPieces[2] == "~{flags}" &&
18042           AsmPieces[3] == "~{fpsr}")
18043       return IntrinsicLowering::LowerToByteSwap(CI);
18044     }
18045     break;
18046   case 3:
18047     if (CI->getType()->isIntegerTy(32) &&
18048         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18049         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18050         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18051         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18052       AsmPieces.clear();
18053       const std::string &ConstraintsStr = IA->getConstraintString();
18054       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18055       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18056       if (AsmPieces.size() == 4 &&
18057           AsmPieces[0] == "~{cc}" &&
18058           AsmPieces[1] == "~{dirflag}" &&
18059           AsmPieces[2] == "~{flags}" &&
18060           AsmPieces[3] == "~{fpsr}")
18061         return IntrinsicLowering::LowerToByteSwap(CI);
18062     }
18063
18064     if (CI->getType()->isIntegerTy(64)) {
18065       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18066       if (Constraints.size() >= 2 &&
18067           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18068           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18069         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18070         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18071             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18072             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18073           return IntrinsicLowering::LowerToByteSwap(CI);
18074       }
18075     }
18076     break;
18077   }
18078   return false;
18079 }
18080
18081 /// getConstraintType - Given a constraint letter, return the type of
18082 /// constraint it is for this target.
18083 X86TargetLowering::ConstraintType
18084 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18085   if (Constraint.size() == 1) {
18086     switch (Constraint[0]) {
18087     case 'R':
18088     case 'q':
18089     case 'Q':
18090     case 'f':
18091     case 't':
18092     case 'u':
18093     case 'y':
18094     case 'x':
18095     case 'Y':
18096     case 'l':
18097       return C_RegisterClass;
18098     case 'a':
18099     case 'b':
18100     case 'c':
18101     case 'd':
18102     case 'S':
18103     case 'D':
18104     case 'A':
18105       return C_Register;
18106     case 'I':
18107     case 'J':
18108     case 'K':
18109     case 'L':
18110     case 'M':
18111     case 'N':
18112     case 'G':
18113     case 'C':
18114     case 'e':
18115     case 'Z':
18116       return C_Other;
18117     default:
18118       break;
18119     }
18120   }
18121   return TargetLowering::getConstraintType(Constraint);
18122 }
18123
18124 /// Examine constraint type and operand type and determine a weight value.
18125 /// This object must already have been set up with the operand type
18126 /// and the current alternative constraint selected.
18127 TargetLowering::ConstraintWeight
18128   X86TargetLowering::getSingleConstraintMatchWeight(
18129     AsmOperandInfo &info, const char *constraint) const {
18130   ConstraintWeight weight = CW_Invalid;
18131   Value *CallOperandVal = info.CallOperandVal;
18132     // If we don't have a value, we can't do a match,
18133     // but allow it at the lowest weight.
18134   if (CallOperandVal == NULL)
18135     return CW_Default;
18136   Type *type = CallOperandVal->getType();
18137   // Look at the constraint type.
18138   switch (*constraint) {
18139   default:
18140     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18141   case 'R':
18142   case 'q':
18143   case 'Q':
18144   case 'a':
18145   case 'b':
18146   case 'c':
18147   case 'd':
18148   case 'S':
18149   case 'D':
18150   case 'A':
18151     if (CallOperandVal->getType()->isIntegerTy())
18152       weight = CW_SpecificReg;
18153     break;
18154   case 'f':
18155   case 't':
18156   case 'u':
18157     if (type->isFloatingPointTy())
18158       weight = CW_SpecificReg;
18159     break;
18160   case 'y':
18161     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18162       weight = CW_SpecificReg;
18163     break;
18164   case 'x':
18165   case 'Y':
18166     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18167         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18168       weight = CW_Register;
18169     break;
18170   case 'I':
18171     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18172       if (C->getZExtValue() <= 31)
18173         weight = CW_Constant;
18174     }
18175     break;
18176   case 'J':
18177     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18178       if (C->getZExtValue() <= 63)
18179         weight = CW_Constant;
18180     }
18181     break;
18182   case 'K':
18183     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18184       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18185         weight = CW_Constant;
18186     }
18187     break;
18188   case 'L':
18189     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18190       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18191         weight = CW_Constant;
18192     }
18193     break;
18194   case 'M':
18195     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18196       if (C->getZExtValue() <= 3)
18197         weight = CW_Constant;
18198     }
18199     break;
18200   case 'N':
18201     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18202       if (C->getZExtValue() <= 0xff)
18203         weight = CW_Constant;
18204     }
18205     break;
18206   case 'G':
18207   case 'C':
18208     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18209       weight = CW_Constant;
18210     }
18211     break;
18212   case 'e':
18213     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18214       if ((C->getSExtValue() >= -0x80000000LL) &&
18215           (C->getSExtValue() <= 0x7fffffffLL))
18216         weight = CW_Constant;
18217     }
18218     break;
18219   case 'Z':
18220     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18221       if (C->getZExtValue() <= 0xffffffff)
18222         weight = CW_Constant;
18223     }
18224     break;
18225   }
18226   return weight;
18227 }
18228
18229 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18230 /// with another that has more specific requirements based on the type of the
18231 /// corresponding operand.
18232 const char *X86TargetLowering::
18233 LowerXConstraint(EVT ConstraintVT) const {
18234   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18235   // 'f' like normal targets.
18236   if (ConstraintVT.isFloatingPoint()) {
18237     if (Subtarget->hasSSE2())
18238       return "Y";
18239     if (Subtarget->hasSSE1())
18240       return "x";
18241   }
18242
18243   return TargetLowering::LowerXConstraint(ConstraintVT);
18244 }
18245
18246 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18247 /// vector.  If it is invalid, don't add anything to Ops.
18248 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18249                                                      std::string &Constraint,
18250                                                      std::vector<SDValue>&Ops,
18251                                                      SelectionDAG &DAG) const {
18252   SDValue Result(0, 0);
18253
18254   // Only support length 1 constraints for now.
18255   if (Constraint.length() > 1) return;
18256
18257   char ConstraintLetter = Constraint[0];
18258   switch (ConstraintLetter) {
18259   default: break;
18260   case 'I':
18261     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18262       if (C->getZExtValue() <= 31) {
18263         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18264         break;
18265       }
18266     }
18267     return;
18268   case 'J':
18269     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18270       if (C->getZExtValue() <= 63) {
18271         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18272         break;
18273       }
18274     }
18275     return;
18276   case 'K':
18277     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18278       if (isInt<8>(C->getSExtValue())) {
18279         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18280         break;
18281       }
18282     }
18283     return;
18284   case 'N':
18285     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18286       if (C->getZExtValue() <= 255) {
18287         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18288         break;
18289       }
18290     }
18291     return;
18292   case 'e': {
18293     // 32-bit signed value
18294     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18295       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18296                                            C->getSExtValue())) {
18297         // Widen to 64 bits here to get it sign extended.
18298         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18299         break;
18300       }
18301     // FIXME gcc accepts some relocatable values here too, but only in certain
18302     // memory models; it's complicated.
18303     }
18304     return;
18305   }
18306   case 'Z': {
18307     // 32-bit unsigned value
18308     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18309       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18310                                            C->getZExtValue())) {
18311         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18312         break;
18313       }
18314     }
18315     // FIXME gcc accepts some relocatable values here too, but only in certain
18316     // memory models; it's complicated.
18317     return;
18318   }
18319   case 'i': {
18320     // Literal immediates are always ok.
18321     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18322       // Widen to 64 bits here to get it sign extended.
18323       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18324       break;
18325     }
18326
18327     // In any sort of PIC mode addresses need to be computed at runtime by
18328     // adding in a register or some sort of table lookup.  These can't
18329     // be used as immediates.
18330     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18331       return;
18332
18333     // If we are in non-pic codegen mode, we allow the address of a global (with
18334     // an optional displacement) to be used with 'i'.
18335     GlobalAddressSDNode *GA = 0;
18336     int64_t Offset = 0;
18337
18338     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18339     while (1) {
18340       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18341         Offset += GA->getOffset();
18342         break;
18343       } else if (Op.getOpcode() == ISD::ADD) {
18344         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18345           Offset += C->getZExtValue();
18346           Op = Op.getOperand(0);
18347           continue;
18348         }
18349       } else if (Op.getOpcode() == ISD::SUB) {
18350         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18351           Offset += -C->getZExtValue();
18352           Op = Op.getOperand(0);
18353           continue;
18354         }
18355       }
18356
18357       // Otherwise, this isn't something we can handle, reject it.
18358       return;
18359     }
18360
18361     const GlobalValue *GV = GA->getGlobal();
18362     // If we require an extra load to get this address, as in PIC mode, we
18363     // can't accept it.
18364     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18365                                                         getTargetMachine())))
18366       return;
18367
18368     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18369                                         GA->getValueType(0), Offset);
18370     break;
18371   }
18372   }
18373
18374   if (Result.getNode()) {
18375     Ops.push_back(Result);
18376     return;
18377   }
18378   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18379 }
18380
18381 std::pair<unsigned, const TargetRegisterClass*>
18382 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18383                                                 EVT VT) const {
18384   // First, see if this is a constraint that directly corresponds to an LLVM
18385   // register class.
18386   if (Constraint.size() == 1) {
18387     // GCC Constraint Letters
18388     switch (Constraint[0]) {
18389     default: break;
18390       // TODO: Slight differences here in allocation order and leaving
18391       // RIP in the class. Do they matter any more here than they do
18392       // in the normal allocation?
18393     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18394       if (Subtarget->is64Bit()) {
18395         if (VT == MVT::i32 || VT == MVT::f32)
18396           return std::make_pair(0U, &X86::GR32RegClass);
18397         if (VT == MVT::i16)
18398           return std::make_pair(0U, &X86::GR16RegClass);
18399         if (VT == MVT::i8 || VT == MVT::i1)
18400           return std::make_pair(0U, &X86::GR8RegClass);
18401         if (VT == MVT::i64 || VT == MVT::f64)
18402           return std::make_pair(0U, &X86::GR64RegClass);
18403         break;
18404       }
18405       // 32-bit fallthrough
18406     case 'Q':   // Q_REGS
18407       if (VT == MVT::i32 || VT == MVT::f32)
18408         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18409       if (VT == MVT::i16)
18410         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18411       if (VT == MVT::i8 || VT == MVT::i1)
18412         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18413       if (VT == MVT::i64)
18414         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18415       break;
18416     case 'r':   // GENERAL_REGS
18417     case 'l':   // INDEX_REGS
18418       if (VT == MVT::i8 || VT == MVT::i1)
18419         return std::make_pair(0U, &X86::GR8RegClass);
18420       if (VT == MVT::i16)
18421         return std::make_pair(0U, &X86::GR16RegClass);
18422       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18423         return std::make_pair(0U, &X86::GR32RegClass);
18424       return std::make_pair(0U, &X86::GR64RegClass);
18425     case 'R':   // LEGACY_REGS
18426       if (VT == MVT::i8 || VT == MVT::i1)
18427         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18428       if (VT == MVT::i16)
18429         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18430       if (VT == MVT::i32 || !Subtarget->is64Bit())
18431         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18432       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18433     case 'f':  // FP Stack registers.
18434       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18435       // value to the correct fpstack register class.
18436       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18437         return std::make_pair(0U, &X86::RFP32RegClass);
18438       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18439         return std::make_pair(0U, &X86::RFP64RegClass);
18440       return std::make_pair(0U, &X86::RFP80RegClass);
18441     case 'y':   // MMX_REGS if MMX allowed.
18442       if (!Subtarget->hasMMX()) break;
18443       return std::make_pair(0U, &X86::VR64RegClass);
18444     case 'Y':   // SSE_REGS if SSE2 allowed
18445       if (!Subtarget->hasSSE2()) break;
18446       // FALL THROUGH.
18447     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18448       if (!Subtarget->hasSSE1()) break;
18449
18450       switch (VT.getSimpleVT().SimpleTy) {
18451       default: break;
18452       // Scalar SSE types.
18453       case MVT::f32:
18454       case MVT::i32:
18455         return std::make_pair(0U, &X86::FR32RegClass);
18456       case MVT::f64:
18457       case MVT::i64:
18458         return std::make_pair(0U, &X86::FR64RegClass);
18459       // Vector types.
18460       case MVT::v16i8:
18461       case MVT::v8i16:
18462       case MVT::v4i32:
18463       case MVT::v2i64:
18464       case MVT::v4f32:
18465       case MVT::v2f64:
18466         return std::make_pair(0U, &X86::VR128RegClass);
18467       // AVX types.
18468       case MVT::v32i8:
18469       case MVT::v16i16:
18470       case MVT::v8i32:
18471       case MVT::v4i64:
18472       case MVT::v8f32:
18473       case MVT::v4f64:
18474         return std::make_pair(0U, &X86::VR256RegClass);
18475       }
18476       break;
18477     }
18478   }
18479
18480   // Use the default implementation in TargetLowering to convert the register
18481   // constraint into a member of a register class.
18482   std::pair<unsigned, const TargetRegisterClass*> Res;
18483   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18484
18485   // Not found as a standard register?
18486   if (Res.second == 0) {
18487     // Map st(0) -> st(7) -> ST0
18488     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18489         tolower(Constraint[1]) == 's' &&
18490         tolower(Constraint[2]) == 't' &&
18491         Constraint[3] == '(' &&
18492         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18493         Constraint[5] == ')' &&
18494         Constraint[6] == '}') {
18495
18496       Res.first = X86::ST0+Constraint[4]-'0';
18497       Res.second = &X86::RFP80RegClass;
18498       return Res;
18499     }
18500
18501     // GCC allows "st(0)" to be called just plain "st".
18502     if (StringRef("{st}").equals_lower(Constraint)) {
18503       Res.first = X86::ST0;
18504       Res.second = &X86::RFP80RegClass;
18505       return Res;
18506     }
18507
18508     // flags -> EFLAGS
18509     if (StringRef("{flags}").equals_lower(Constraint)) {
18510       Res.first = X86::EFLAGS;
18511       Res.second = &X86::CCRRegClass;
18512       return Res;
18513     }
18514
18515     // 'A' means EAX + EDX.
18516     if (Constraint == "A") {
18517       Res.first = X86::EAX;
18518       Res.second = &X86::GR32_ADRegClass;
18519       return Res;
18520     }
18521     return Res;
18522   }
18523
18524   // Otherwise, check to see if this is a register class of the wrong value
18525   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18526   // turn into {ax},{dx}.
18527   if (Res.second->hasType(VT))
18528     return Res;   // Correct type already, nothing to do.
18529
18530   // All of the single-register GCC register classes map their values onto
18531   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18532   // really want an 8-bit or 32-bit register, map to the appropriate register
18533   // class and return the appropriate register.
18534   if (Res.second == &X86::GR16RegClass) {
18535     if (VT == MVT::i8 || VT == MVT::i1) {
18536       unsigned DestReg = 0;
18537       switch (Res.first) {
18538       default: break;
18539       case X86::AX: DestReg = X86::AL; break;
18540       case X86::DX: DestReg = X86::DL; break;
18541       case X86::CX: DestReg = X86::CL; break;
18542       case X86::BX: DestReg = X86::BL; break;
18543       }
18544       if (DestReg) {
18545         Res.first = DestReg;
18546         Res.second = &X86::GR8RegClass;
18547       }
18548     } else if (VT == MVT::i32 || VT == MVT::f32) {
18549       unsigned DestReg = 0;
18550       switch (Res.first) {
18551       default: break;
18552       case X86::AX: DestReg = X86::EAX; break;
18553       case X86::DX: DestReg = X86::EDX; break;
18554       case X86::CX: DestReg = X86::ECX; break;
18555       case X86::BX: DestReg = X86::EBX; break;
18556       case X86::SI: DestReg = X86::ESI; break;
18557       case X86::DI: DestReg = X86::EDI; break;
18558       case X86::BP: DestReg = X86::EBP; break;
18559       case X86::SP: DestReg = X86::ESP; break;
18560       }
18561       if (DestReg) {
18562         Res.first = DestReg;
18563         Res.second = &X86::GR32RegClass;
18564       }
18565     } else if (VT == MVT::i64 || VT == MVT::f64) {
18566       unsigned DestReg = 0;
18567       switch (Res.first) {
18568       default: break;
18569       case X86::AX: DestReg = X86::RAX; break;
18570       case X86::DX: DestReg = X86::RDX; break;
18571       case X86::CX: DestReg = X86::RCX; break;
18572       case X86::BX: DestReg = X86::RBX; break;
18573       case X86::SI: DestReg = X86::RSI; break;
18574       case X86::DI: DestReg = X86::RDI; break;
18575       case X86::BP: DestReg = X86::RBP; break;
18576       case X86::SP: DestReg = X86::RSP; break;
18577       }
18578       if (DestReg) {
18579         Res.first = DestReg;
18580         Res.second = &X86::GR64RegClass;
18581       }
18582     }
18583   } else if (Res.second == &X86::FR32RegClass ||
18584              Res.second == &X86::FR64RegClass ||
18585              Res.second == &X86::VR128RegClass) {
18586     // Handle references to XMM physical registers that got mapped into the
18587     // wrong class.  This can happen with constraints like {xmm0} where the
18588     // target independent register mapper will just pick the first match it can
18589     // find, ignoring the required type.
18590
18591     if (VT == MVT::f32 || VT == MVT::i32)
18592       Res.second = &X86::FR32RegClass;
18593     else if (VT == MVT::f64 || VT == MVT::i64)
18594       Res.second = &X86::FR64RegClass;
18595     else if (X86::VR128RegClass.hasType(VT))
18596       Res.second = &X86::VR128RegClass;
18597     else if (X86::VR256RegClass.hasType(VT))
18598       Res.second = &X86::VR256RegClass;
18599   }
18600
18601   return Res;
18602 }