94370ae4ee8bdfd16528763563724521153f1b75
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "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   // On X86 and X86-64, atomic operations are lowered to locked instructions.
532   // Locked instructions, in turn, have implicit fence semantics (all memory
533   // operations are flushed before issuing the locked instruction, and they
534   // are not buffered), so we can fold away the common pattern of
535   // fence-atomic-fence.
536   setShouldFoldAtomicFences(true);
537
538   // Expand certain atomics
539   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
540     MVT VT = IntVTs[i];
541     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
542     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
543     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
544   }
545
546   if (!Subtarget->is64Bit()) {
547     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
548     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
549     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
550     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
551     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
552     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
553     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
554     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
555     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
556     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
557     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
558     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
559   }
560
561   if (Subtarget->hasCmpxchg16b()) {
562     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
563   }
564
565   // FIXME - use subtarget debug flags
566   if (!Subtarget->isTargetDarwin() &&
567       !Subtarget->isTargetELF() &&
568       !Subtarget->isTargetCygMing()) {
569     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
570   }
571
572   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
573   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
574   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
575   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
576   if (Subtarget->is64Bit()) {
577     setExceptionPointerRegister(X86::RAX);
578     setExceptionSelectorRegister(X86::RDX);
579   } else {
580     setExceptionPointerRegister(X86::EAX);
581     setExceptionSelectorRegister(X86::EDX);
582   }
583   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
584   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
585
586   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
587   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
588
589   setOperationAction(ISD::TRAP, MVT::Other, Legal);
590   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
591
592   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
593   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
594   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
595   if (Subtarget->is64Bit()) {
596     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
597     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
598   } else {
599     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
600     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
601   }
602
603   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
604   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
605
606   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
607     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
608                        MVT::i64 : MVT::i32, Custom);
609   else if (TM.Options.EnableSegmentedStacks)
610     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
611                        MVT::i64 : MVT::i32, Custom);
612   else
613     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
614                        MVT::i64 : MVT::i32, Expand);
615
616   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
617     // f32 and f64 use SSE.
618     // Set up the FP register classes.
619     addRegisterClass(MVT::f32, &X86::FR32RegClass);
620     addRegisterClass(MVT::f64, &X86::FR64RegClass);
621
622     // Use ANDPD to simulate FABS.
623     setOperationAction(ISD::FABS , MVT::f64, Custom);
624     setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626     // Use XORP to simulate FNEG.
627     setOperationAction(ISD::FNEG , MVT::f64, Custom);
628     setOperationAction(ISD::FNEG , MVT::f32, Custom);
629
630     // Use ANDPD and ORPD to simulate FCOPYSIGN.
631     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
632     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
633
634     // Lower this to FGETSIGNx86 plus an AND.
635     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
636     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
637
638     // We don't support sin/cos/fmod
639     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
640     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
641     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
642     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
643     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
644     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
645
646     // Expand FP immediates into loads from the stack, except for the special
647     // cases we handle.
648     addLegalFPImmediate(APFloat(+0.0)); // xorpd
649     addLegalFPImmediate(APFloat(+0.0f)); // xorps
650   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
651     // Use SSE for f32, x87 for f64.
652     // Set up the FP register classes.
653     addRegisterClass(MVT::f32, &X86::FR32RegClass);
654     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
655
656     // Use ANDPS to simulate FABS.
657     setOperationAction(ISD::FABS , MVT::f32, Custom);
658
659     // Use XORP to simulate FNEG.
660     setOperationAction(ISD::FNEG , MVT::f32, Custom);
661
662     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
663
664     // Use ANDPS and ORPS to simulate FCOPYSIGN.
665     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
666     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
667
668     // We don't support sin/cos/fmod
669     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
670     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
671     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672
673     // Special cases we handle for FP constants.
674     addLegalFPImmediate(APFloat(+0.0f)); // xorps
675     addLegalFPImmediate(APFloat(+0.0)); // FLD0
676     addLegalFPImmediate(APFloat(+1.0)); // FLD1
677     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
678     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
679
680     if (!TM.Options.UnsafeFPMath) {
681       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
682       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
683       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
684     }
685   } else if (!TM.Options.UseSoftFloat) {
686     // f32 and f64 in x87.
687     // Set up the FP register classes.
688     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
689     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
690
691     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
692     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
693     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
695
696     if (!TM.Options.UnsafeFPMath) {
697       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
698       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
699       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
700       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
701       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
702       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
703     }
704     addLegalFPImmediate(APFloat(+0.0)); // FLD0
705     addLegalFPImmediate(APFloat(+1.0)); // FLD1
706     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
707     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
708     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
709     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
710     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
711     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
712   }
713
714   // We don't support FMA.
715   setOperationAction(ISD::FMA, MVT::f64, Expand);
716   setOperationAction(ISD::FMA, MVT::f32, Expand);
717
718   // Long double always uses X87.
719   if (!TM.Options.UseSoftFloat) {
720     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
721     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
723     {
724       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
725       addLegalFPImmediate(TmpFlt);  // FLD0
726       TmpFlt.changeSign();
727       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
728
729       bool ignored;
730       APFloat TmpFlt2(+1.0);
731       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
732                       &ignored);
733       addLegalFPImmediate(TmpFlt2);  // FLD1
734       TmpFlt2.changeSign();
735       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
736     }
737
738     if (!TM.Options.UnsafeFPMath) {
739       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
740       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
741       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
742     }
743
744     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
745     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
746     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
747     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
748     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
749     setOperationAction(ISD::FMA, MVT::f80, Expand);
750   }
751
752   // Always use a library call for pow.
753   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
754   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
755   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
756
757   setOperationAction(ISD::FLOG, MVT::f80, Expand);
758   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
759   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
760   setOperationAction(ISD::FEXP, MVT::f80, Expand);
761   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
762
763   // First set operation action for all vector types to either promote
764   // (for widening) or expand (for scalarization). Then we will selectively
765   // turn on ones that can be effectively codegen'd.
766   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
767            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
768     MVT VT = (MVT::SimpleValueType)i;
769     setOperationAction(ISD::ADD , VT, Expand);
770     setOperationAction(ISD::SUB , VT, Expand);
771     setOperationAction(ISD::FADD, VT, Expand);
772     setOperationAction(ISD::FNEG, VT, Expand);
773     setOperationAction(ISD::FSUB, VT, Expand);
774     setOperationAction(ISD::MUL , VT, Expand);
775     setOperationAction(ISD::FMUL, VT, Expand);
776     setOperationAction(ISD::SDIV, VT, Expand);
777     setOperationAction(ISD::UDIV, VT, Expand);
778     setOperationAction(ISD::FDIV, VT, Expand);
779     setOperationAction(ISD::SREM, VT, Expand);
780     setOperationAction(ISD::UREM, VT, Expand);
781     setOperationAction(ISD::LOAD, VT, Expand);
782     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
783     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
784     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
785     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
786     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
787     setOperationAction(ISD::FABS, VT, Expand);
788     setOperationAction(ISD::FSIN, VT, Expand);
789     setOperationAction(ISD::FSINCOS, VT, Expand);
790     setOperationAction(ISD::FCOS, VT, Expand);
791     setOperationAction(ISD::FSINCOS, VT, Expand);
792     setOperationAction(ISD::FREM, VT, Expand);
793     setOperationAction(ISD::FMA,  VT, Expand);
794     setOperationAction(ISD::FPOWI, VT, Expand);
795     setOperationAction(ISD::FSQRT, VT, Expand);
796     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
797     setOperationAction(ISD::FFLOOR, VT, Expand);
798     setOperationAction(ISD::FCEIL, VT, Expand);
799     setOperationAction(ISD::FTRUNC, VT, Expand);
800     setOperationAction(ISD::FRINT, VT, Expand);
801     setOperationAction(ISD::FNEARBYINT, VT, Expand);
802     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
803     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
804     setOperationAction(ISD::SDIVREM, VT, Expand);
805     setOperationAction(ISD::UDIVREM, VT, Expand);
806     setOperationAction(ISD::FPOW, VT, Expand);
807     setOperationAction(ISD::CTPOP, VT, Expand);
808     setOperationAction(ISD::CTTZ, VT, Expand);
809     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
810     setOperationAction(ISD::CTLZ, VT, Expand);
811     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
812     setOperationAction(ISD::SHL, VT, Expand);
813     setOperationAction(ISD::SRA, VT, Expand);
814     setOperationAction(ISD::SRL, VT, Expand);
815     setOperationAction(ISD::ROTL, VT, Expand);
816     setOperationAction(ISD::ROTR, VT, Expand);
817     setOperationAction(ISD::BSWAP, VT, Expand);
818     setOperationAction(ISD::SETCC, VT, Expand);
819     setOperationAction(ISD::FLOG, VT, Expand);
820     setOperationAction(ISD::FLOG2, VT, Expand);
821     setOperationAction(ISD::FLOG10, VT, Expand);
822     setOperationAction(ISD::FEXP, VT, Expand);
823     setOperationAction(ISD::FEXP2, VT, Expand);
824     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
825     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
826     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
827     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
828     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
829     setOperationAction(ISD::TRUNCATE, VT, Expand);
830     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
831     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
832     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
833     setOperationAction(ISD::VSELECT, VT, Expand);
834     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
835              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
836       setTruncStoreAction(VT,
837                           (MVT::SimpleValueType)InnerVT, Expand);
838     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
839     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
840     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
841   }
842
843   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
844   // with -msoft-float, disable use of MMX as well.
845   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
846     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
847     // No operations on x86mmx supported, everything uses intrinsics.
848   }
849
850   // MMX-sized vectors (other than x86mmx) are expected to be expanded
851   // into smaller operations.
852   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
853   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
854   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
855   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
856   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
857   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
858   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
859   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
860   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
861   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
862   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
863   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
864   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
865   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
866   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
867   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
868   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
869   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
870   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
871   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
872   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
873   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
874   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
875   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
876   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
877   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
878   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
879   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
880   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
881
882   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
883     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
884
885     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
886     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
887     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
888     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
889     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
890     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
891     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
892     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
893     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
894     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
895     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
896     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
897   }
898
899   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
900     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
901
902     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
903     // registers cannot be used even for integer operations.
904     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
905     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
906     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
907     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
908
909     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
910     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
911     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
912     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
913     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
914     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
915     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
916     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
917     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
918     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
919     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
920     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
921     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
922     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
923     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
924     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
925     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
926     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
927
928     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
929     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
930     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
931     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
932
933     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
934     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
935     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
938
939     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
940     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
941       MVT VT = (MVT::SimpleValueType)i;
942       // Do not attempt to custom lower non-power-of-2 vectors
943       if (!isPowerOf2_32(VT.getVectorNumElements()))
944         continue;
945       // Do not attempt to custom lower non-128-bit vectors
946       if (!VT.is128BitVector())
947         continue;
948       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
949       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
950       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
951     }
952
953     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
954     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
955     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
956     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
957     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
958     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
959
960     if (Subtarget->is64Bit()) {
961       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
962       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
963     }
964
965     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
966     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
967       MVT VT = (MVT::SimpleValueType)i;
968
969       // Do not attempt to promote non-128-bit vectors
970       if (!VT.is128BitVector())
971         continue;
972
973       setOperationAction(ISD::AND,    VT, Promote);
974       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
975       setOperationAction(ISD::OR,     VT, Promote);
976       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
977       setOperationAction(ISD::XOR,    VT, Promote);
978       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
979       setOperationAction(ISD::LOAD,   VT, Promote);
980       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
981       setOperationAction(ISD::SELECT, VT, Promote);
982       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
983     }
984
985     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
986
987     // Custom lower v2i64 and v2f64 selects.
988     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
989     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
990     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
991     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
992
993     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
994     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
995
996     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
997     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
998     // As there is no 64-bit GPR available, we need build a special custom
999     // sequence to convert from v2i32 to v2f32.
1000     if (!Subtarget->is64Bit())
1001       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1002
1003     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1004     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1005
1006     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1007   }
1008
1009   if (Subtarget->hasSSE41()) {
1010     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1011     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1012     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1013     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1014     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1015     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1016     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1017     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1018     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1019     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1020
1021     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1022     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1023     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1024     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1025     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1026     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1027     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1028     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1029     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1030     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1031
1032     // FIXME: Do we need to handle scalar-to-vector here?
1033     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1034
1035     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1036     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1037     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1038     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1039     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1040
1041     // i8 and i16 vectors are custom , because the source register and source
1042     // source memory operand types are not the same width.  f32 vectors are
1043     // custom since the immediate controlling the insert encodes additional
1044     // information.
1045     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1046     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1047     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1048     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1049
1050     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1051     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1052     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1053     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1054
1055     // FIXME: these should be Legal but thats only for the case where
1056     // the index is constant.  For now custom expand to deal with that.
1057     if (Subtarget->is64Bit()) {
1058       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1059       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1060     }
1061   }
1062
1063   if (Subtarget->hasSSE2()) {
1064     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1065     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1066
1067     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1068     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1069
1070     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1071     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1072
1073     // In the customized shift lowering, the legal cases in AVX2 will be
1074     // recognized.
1075     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1076     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1077
1078     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1079     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1080
1081     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1082
1083     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1084     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1085   }
1086
1087   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1088     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1089     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1090     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1091     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1092     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1093     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1094
1095     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1096     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1097     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1098
1099     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1100     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1101     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1102     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1103     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1104     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1105     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1106     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1107     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1108     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1109     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1110     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1111
1112     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1113     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1114     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1115     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1116     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1117     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1118     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1119     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1120     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1121     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1122     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1123     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1124
1125     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1126     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1127
1128     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1129
1130     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1131     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1132     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1133     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1134
1135     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1136     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1137     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1138
1139     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1140
1141     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1142     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1143
1144     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1145     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1146
1147     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1148     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1149
1150     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1151
1152     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1153     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1154     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1155     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1156
1157     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1158     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1159     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1160
1161     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1162     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1163     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1164     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1165
1166     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1167     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1168     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1169     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1170     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1171     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1172
1173     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1174       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1175       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1176       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1177       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1178       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1179       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1180     }
1181
1182     if (Subtarget->hasInt256()) {
1183       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1184       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1185       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1186       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1187
1188       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1189       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1190       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1191       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1192
1193       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1194       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1195       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1196       // Don't lower v32i8 because there is no 128-bit byte mul
1197
1198       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1199
1200       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1201     } else {
1202       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1203       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1204       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1205       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1206
1207       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1208       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1209       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1210       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1211
1212       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1213       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1214       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1215       // Don't lower v32i8 because there is no 128-bit byte mul
1216     }
1217
1218     // In the customized shift lowering, the legal cases in AVX2 will be
1219     // recognized.
1220     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1221     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1222
1223     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1224     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1225
1226     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1227
1228     // Custom lower several nodes for 256-bit types.
1229     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1230              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1231       MVT VT = (MVT::SimpleValueType)i;
1232
1233       // Extract subvector is special because the value type
1234       // (result) is 128-bit but the source is 256-bit wide.
1235       if (VT.is128BitVector())
1236         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1237
1238       // Do not attempt to custom lower other non-256-bit vectors
1239       if (!VT.is256BitVector())
1240         continue;
1241
1242       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1243       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1244       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1245       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1246       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1247       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1248       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1249     }
1250
1251     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1252     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1253       MVT VT = (MVT::SimpleValueType)i;
1254
1255       // Do not attempt to promote non-256-bit vectors
1256       if (!VT.is256BitVector())
1257         continue;
1258
1259       setOperationAction(ISD::AND,    VT, Promote);
1260       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1261       setOperationAction(ISD::OR,     VT, Promote);
1262       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1263       setOperationAction(ISD::XOR,    VT, Promote);
1264       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1265       setOperationAction(ISD::LOAD,   VT, Promote);
1266       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1267       setOperationAction(ISD::SELECT, VT, Promote);
1268       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1269     }
1270   }
1271
1272   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1273   // of this type with custom code.
1274   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1275            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1276     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1277                        Custom);
1278   }
1279
1280   // We want to custom lower some of our intrinsics.
1281   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1282   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1283
1284   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1285   // handle type legalization for these operations here.
1286   //
1287   // FIXME: We really should do custom legalization for addition and
1288   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1289   // than generic legalization for 64-bit multiplication-with-overflow, though.
1290   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1291     // Add/Sub/Mul with overflow operations are custom lowered.
1292     MVT VT = IntVTs[i];
1293     setOperationAction(ISD::SADDO, VT, Custom);
1294     setOperationAction(ISD::UADDO, VT, Custom);
1295     setOperationAction(ISD::SSUBO, VT, Custom);
1296     setOperationAction(ISD::USUBO, VT, Custom);
1297     setOperationAction(ISD::SMULO, VT, Custom);
1298     setOperationAction(ISD::UMULO, VT, Custom);
1299   }
1300
1301   // There are no 8-bit 3-address imul/mul instructions
1302   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1303   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1304
1305   if (!Subtarget->is64Bit()) {
1306     // These libcalls are not available in 32-bit.
1307     setLibcallName(RTLIB::SHL_I128, 0);
1308     setLibcallName(RTLIB::SRL_I128, 0);
1309     setLibcallName(RTLIB::SRA_I128, 0);
1310   }
1311
1312   // Combine sin / cos into one node or libcall if possible.
1313   if (Subtarget->hasSinCos()) {
1314     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1315     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1316     if (Subtarget->isTargetDarwin()) {
1317       // For MacOSX, we don't want to the normal expansion of a libcall to
1318       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1319       // traffic.
1320       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1321       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1322     }
1323   }
1324
1325   // We have target-specific dag combine patterns for the following nodes:
1326   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1327   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1328   setTargetDAGCombine(ISD::VSELECT);
1329   setTargetDAGCombine(ISD::SELECT);
1330   setTargetDAGCombine(ISD::SHL);
1331   setTargetDAGCombine(ISD::SRA);
1332   setTargetDAGCombine(ISD::SRL);
1333   setTargetDAGCombine(ISD::OR);
1334   setTargetDAGCombine(ISD::AND);
1335   setTargetDAGCombine(ISD::ADD);
1336   setTargetDAGCombine(ISD::FADD);
1337   setTargetDAGCombine(ISD::FSUB);
1338   setTargetDAGCombine(ISD::FMA);
1339   setTargetDAGCombine(ISD::SUB);
1340   setTargetDAGCombine(ISD::LOAD);
1341   setTargetDAGCombine(ISD::STORE);
1342   setTargetDAGCombine(ISD::ZERO_EXTEND);
1343   setTargetDAGCombine(ISD::ANY_EXTEND);
1344   setTargetDAGCombine(ISD::SIGN_EXTEND);
1345   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1346   setTargetDAGCombine(ISD::TRUNCATE);
1347   setTargetDAGCombine(ISD::SINT_TO_FP);
1348   setTargetDAGCombine(ISD::SETCC);
1349   if (Subtarget->is64Bit())
1350     setTargetDAGCombine(ISD::MUL);
1351   setTargetDAGCombine(ISD::XOR);
1352
1353   computeRegisterProperties();
1354
1355   // On Darwin, -Os means optimize for size without hurting performance,
1356   // do not reduce the limit.
1357   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1358   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1359   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1360   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1361   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1362   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1363   setPrefLoopAlignment(4); // 2^4 bytes.
1364
1365   // Predictable cmov don't hurt on atom because it's in-order.
1366   PredictableSelectIsExpensive = !Subtarget->isAtom();
1367
1368   setPrefFunctionAlignment(4); // 2^4 bytes.
1369 }
1370
1371 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1372   if (!VT.isVector()) return MVT::i8;
1373   return VT.changeVectorElementTypeToInteger();
1374 }
1375
1376 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1377 /// the desired ByVal argument alignment.
1378 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1379   if (MaxAlign == 16)
1380     return;
1381   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1382     if (VTy->getBitWidth() == 128)
1383       MaxAlign = 16;
1384   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1385     unsigned EltAlign = 0;
1386     getMaxByValAlign(ATy->getElementType(), EltAlign);
1387     if (EltAlign > MaxAlign)
1388       MaxAlign = EltAlign;
1389   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1390     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1391       unsigned EltAlign = 0;
1392       getMaxByValAlign(STy->getElementType(i), EltAlign);
1393       if (EltAlign > MaxAlign)
1394         MaxAlign = EltAlign;
1395       if (MaxAlign == 16)
1396         break;
1397     }
1398   }
1399 }
1400
1401 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1402 /// function arguments in the caller parameter area. For X86, aggregates
1403 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1404 /// are at 4-byte boundaries.
1405 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1406   if (Subtarget->is64Bit()) {
1407     // Max of 8 and alignment of type.
1408     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1409     if (TyAlign > 8)
1410       return TyAlign;
1411     return 8;
1412   }
1413
1414   unsigned Align = 4;
1415   if (Subtarget->hasSSE1())
1416     getMaxByValAlign(Ty, Align);
1417   return Align;
1418 }
1419
1420 /// getOptimalMemOpType - Returns the target specific optimal type for load
1421 /// and store operations as a result of memset, memcpy, and memmove
1422 /// lowering. If DstAlign is zero that means it's safe to destination
1423 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1424 /// means there isn't a need to check it against alignment requirement,
1425 /// probably because the source does not need to be loaded. If 'IsMemset' is
1426 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1427 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1428 /// source is constant so it does not need to be loaded.
1429 /// It returns EVT::Other if the type should be determined using generic
1430 /// target-independent logic.
1431 EVT
1432 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1433                                        unsigned DstAlign, unsigned SrcAlign,
1434                                        bool IsMemset, bool ZeroMemset,
1435                                        bool MemcpyStrSrc,
1436                                        MachineFunction &MF) const {
1437   const Function *F = MF.getFunction();
1438   if ((!IsMemset || ZeroMemset) &&
1439       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1440                                        Attribute::NoImplicitFloat)) {
1441     if (Size >= 16 &&
1442         (Subtarget->isUnalignedMemAccessFast() ||
1443          ((DstAlign == 0 || DstAlign >= 16) &&
1444           (SrcAlign == 0 || SrcAlign >= 16)))) {
1445       if (Size >= 32) {
1446         if (Subtarget->hasInt256())
1447           return MVT::v8i32;
1448         if (Subtarget->hasFp256())
1449           return MVT::v8f32;
1450       }
1451       if (Subtarget->hasSSE2())
1452         return MVT::v4i32;
1453       if (Subtarget->hasSSE1())
1454         return MVT::v4f32;
1455     } else if (!MemcpyStrSrc && Size >= 8 &&
1456                !Subtarget->is64Bit() &&
1457                Subtarget->hasSSE2()) {
1458       // Do not use f64 to lower memcpy if source is string constant. It's
1459       // better to use i32 to avoid the loads.
1460       return MVT::f64;
1461     }
1462   }
1463   if (Subtarget->is64Bit() && Size >= 8)
1464     return MVT::i64;
1465   return MVT::i32;
1466 }
1467
1468 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1469   if (VT == MVT::f32)
1470     return X86ScalarSSEf32;
1471   else if (VT == MVT::f64)
1472     return X86ScalarSSEf64;
1473   return true;
1474 }
1475
1476 bool
1477 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1478   if (Fast)
1479     *Fast = Subtarget->isUnalignedMemAccessFast();
1480   return true;
1481 }
1482
1483 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1484 /// current function.  The returned value is a member of the
1485 /// MachineJumpTableInfo::JTEntryKind enum.
1486 unsigned X86TargetLowering::getJumpTableEncoding() const {
1487   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1488   // symbol.
1489   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1490       Subtarget->isPICStyleGOT())
1491     return MachineJumpTableInfo::EK_Custom32;
1492
1493   // Otherwise, use the normal jump table encoding heuristics.
1494   return TargetLowering::getJumpTableEncoding();
1495 }
1496
1497 const MCExpr *
1498 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1499                                              const MachineBasicBlock *MBB,
1500                                              unsigned uid,MCContext &Ctx) const{
1501   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1502          Subtarget->isPICStyleGOT());
1503   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1504   // entries.
1505   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1506                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1507 }
1508
1509 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1510 /// jumptable.
1511 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1512                                                     SelectionDAG &DAG) const {
1513   if (!Subtarget->is64Bit())
1514     // This doesn't have DebugLoc associated with it, but is not really the
1515     // same as a Register.
1516     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1517   return Table;
1518 }
1519
1520 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1521 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1522 /// MCExpr.
1523 const MCExpr *X86TargetLowering::
1524 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1525                              MCContext &Ctx) const {
1526   // X86-64 uses RIP relative addressing based on the jump table label.
1527   if (Subtarget->isPICStyleRIPRel())
1528     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1529
1530   // Otherwise, the reference is relative to the PIC base.
1531   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1532 }
1533
1534 // FIXME: Why this routine is here? Move to RegInfo!
1535 std::pair<const TargetRegisterClass*, uint8_t>
1536 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1537   const TargetRegisterClass *RRC = 0;
1538   uint8_t Cost = 1;
1539   switch (VT.SimpleTy) {
1540   default:
1541     return TargetLowering::findRepresentativeClass(VT);
1542   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1543     RRC = Subtarget->is64Bit() ?
1544       (const TargetRegisterClass*)&X86::GR64RegClass :
1545       (const TargetRegisterClass*)&X86::GR32RegClass;
1546     break;
1547   case MVT::x86mmx:
1548     RRC = &X86::VR64RegClass;
1549     break;
1550   case MVT::f32: case MVT::f64:
1551   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1552   case MVT::v4f32: case MVT::v2f64:
1553   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1554   case MVT::v4f64:
1555     RRC = &X86::VR128RegClass;
1556     break;
1557   }
1558   return std::make_pair(RRC, Cost);
1559 }
1560
1561 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1562                                                unsigned &Offset) const {
1563   if (!Subtarget->isTargetLinux())
1564     return false;
1565
1566   if (Subtarget->is64Bit()) {
1567     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1568     Offset = 0x28;
1569     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1570       AddressSpace = 256;
1571     else
1572       AddressSpace = 257;
1573   } else {
1574     // %gs:0x14 on i386
1575     Offset = 0x14;
1576     AddressSpace = 256;
1577   }
1578   return true;
1579 }
1580
1581 //===----------------------------------------------------------------------===//
1582 //               Return Value Calling Convention Implementation
1583 //===----------------------------------------------------------------------===//
1584
1585 #include "X86GenCallingConv.inc"
1586
1587 bool
1588 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1589                                   MachineFunction &MF, bool isVarArg,
1590                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1591                         LLVMContext &Context) const {
1592   SmallVector<CCValAssign, 16> RVLocs;
1593   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1594                  RVLocs, Context);
1595   return CCInfo.CheckReturn(Outs, RetCC_X86);
1596 }
1597
1598 SDValue
1599 X86TargetLowering::LowerReturn(SDValue Chain,
1600                                CallingConv::ID CallConv, bool isVarArg,
1601                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1602                                const SmallVectorImpl<SDValue> &OutVals,
1603                                DebugLoc dl, SelectionDAG &DAG) const {
1604   MachineFunction &MF = DAG.getMachineFunction();
1605   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1606
1607   SmallVector<CCValAssign, 16> RVLocs;
1608   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1609                  RVLocs, *DAG.getContext());
1610   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1611
1612   SDValue Flag;
1613   SmallVector<SDValue, 6> RetOps;
1614   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1615   // Operand #1 = Bytes To Pop
1616   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1617                    MVT::i16));
1618
1619   // Copy the result values into the output registers.
1620   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1621     CCValAssign &VA = RVLocs[i];
1622     assert(VA.isRegLoc() && "Can only return in registers!");
1623     SDValue ValToCopy = OutVals[i];
1624     EVT ValVT = ValToCopy.getValueType();
1625
1626     // Promote values to the appropriate types
1627     if (VA.getLocInfo() == CCValAssign::SExt)
1628       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1629     else if (VA.getLocInfo() == CCValAssign::ZExt)
1630       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1631     else if (VA.getLocInfo() == CCValAssign::AExt)
1632       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1633     else if (VA.getLocInfo() == CCValAssign::BCvt)
1634       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1635
1636     // If this is x86-64, and we disabled SSE, we can't return FP values,
1637     // or SSE or MMX vectors.
1638     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1639          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1640           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1641       report_fatal_error("SSE register return with SSE disabled");
1642     }
1643     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1644     // llvm-gcc has never done it right and no one has noticed, so this
1645     // should be OK for now.
1646     if (ValVT == MVT::f64 &&
1647         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1648       report_fatal_error("SSE2 register return with SSE2 disabled");
1649
1650     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1651     // the RET instruction and handled by the FP Stackifier.
1652     if (VA.getLocReg() == X86::ST0 ||
1653         VA.getLocReg() == X86::ST1) {
1654       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1655       // change the value to the FP stack register class.
1656       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1657         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1658       RetOps.push_back(ValToCopy);
1659       // Don't emit a copytoreg.
1660       continue;
1661     }
1662
1663     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1664     // which is returned in RAX / RDX.
1665     if (Subtarget->is64Bit()) {
1666       if (ValVT == MVT::x86mmx) {
1667         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1668           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1669           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1670                                   ValToCopy);
1671           // If we don't have SSE2 available, convert to v4f32 so the generated
1672           // register is legal.
1673           if (!Subtarget->hasSSE2())
1674             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1675         }
1676       }
1677     }
1678
1679     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1680     Flag = Chain.getValue(1);
1681     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1682   }
1683
1684   // The x86-64 ABIs require that for returning structs by value we copy
1685   // the sret argument into %rax/%eax (depending on ABI) for the return.
1686   // Win32 requires us to put the sret argument to %eax as well.
1687   // We saved the argument into a virtual register in the entry block,
1688   // so now we copy the value out and into %rax/%eax.
1689   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1690       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1691     MachineFunction &MF = DAG.getMachineFunction();
1692     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1693     unsigned Reg = FuncInfo->getSRetReturnReg();
1694     assert(Reg &&
1695            "SRetReturnReg should have been set in LowerFormalArguments().");
1696     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1697
1698     unsigned RetValReg
1699         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1700           X86::RAX : X86::EAX;
1701     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1702     Flag = Chain.getValue(1);
1703
1704     // RAX/EAX now acts like a return value.
1705     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1706   }
1707
1708   RetOps[0] = Chain;  // Update chain.
1709
1710   // Add the flag if we have it.
1711   if (Flag.getNode())
1712     RetOps.push_back(Flag);
1713
1714   return DAG.getNode(X86ISD::RET_FLAG, dl,
1715                      MVT::Other, &RetOps[0], RetOps.size());
1716 }
1717
1718 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1719   if (N->getNumValues() != 1)
1720     return false;
1721   if (!N->hasNUsesOfValue(1, 0))
1722     return false;
1723
1724   SDValue TCChain = Chain;
1725   SDNode *Copy = *N->use_begin();
1726   if (Copy->getOpcode() == ISD::CopyToReg) {
1727     // If the copy has a glue operand, we conservatively assume it isn't safe to
1728     // perform a tail call.
1729     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1730       return false;
1731     TCChain = Copy->getOperand(0);
1732   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1733     return false;
1734
1735   bool HasRet = false;
1736   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1737        UI != UE; ++UI) {
1738     if (UI->getOpcode() != X86ISD::RET_FLAG)
1739       return false;
1740     HasRet = true;
1741   }
1742
1743   if (!HasRet)
1744     return false;
1745
1746   Chain = TCChain;
1747   return true;
1748 }
1749
1750 MVT
1751 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1752                                             ISD::NodeType ExtendKind) const {
1753   MVT ReturnMVT;
1754   // TODO: Is this also valid on 32-bit?
1755   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1756     ReturnMVT = MVT::i8;
1757   else
1758     ReturnMVT = MVT::i32;
1759
1760   MVT MinVT = getRegisterType(ReturnMVT);
1761   return VT.bitsLT(MinVT) ? MinVT : VT;
1762 }
1763
1764 /// LowerCallResult - Lower the result values of a call into the
1765 /// appropriate copies out of appropriate physical registers.
1766 ///
1767 SDValue
1768 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1769                                    CallingConv::ID CallConv, bool isVarArg,
1770                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1771                                    DebugLoc dl, SelectionDAG &DAG,
1772                                    SmallVectorImpl<SDValue> &InVals) const {
1773
1774   // Assign locations to each value returned by this call.
1775   SmallVector<CCValAssign, 16> RVLocs;
1776   bool Is64Bit = Subtarget->is64Bit();
1777   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1778                  getTargetMachine(), RVLocs, *DAG.getContext());
1779   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1780
1781   // Copy all of the result registers out of their specified physreg.
1782   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1783     CCValAssign &VA = RVLocs[i];
1784     EVT CopyVT = VA.getValVT();
1785
1786     // If this is x86-64, and we disabled SSE, we can't return FP values
1787     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1788         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1789       report_fatal_error("SSE register return with SSE disabled");
1790     }
1791
1792     SDValue Val;
1793
1794     // If this is a call to a function that returns an fp value on the floating
1795     // point stack, we must guarantee the value is popped from the stack, so
1796     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1797     // if the return value is not used. We use the FpPOP_RETVAL instruction
1798     // instead.
1799     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1800       // If we prefer to use the value in xmm registers, copy it out as f80 and
1801       // use a truncate to move it from fp stack reg to xmm reg.
1802       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1803       SDValue Ops[] = { Chain, InFlag };
1804       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1805                                          MVT::Other, MVT::Glue, Ops), 1);
1806       Val = Chain.getValue(0);
1807
1808       // Round the f80 to the right size, which also moves it to the appropriate
1809       // xmm register.
1810       if (CopyVT != VA.getValVT())
1811         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1812                           // This truncation won't change the value.
1813                           DAG.getIntPtrConstant(1));
1814     } else {
1815       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1816                                  CopyVT, InFlag).getValue(1);
1817       Val = Chain.getValue(0);
1818     }
1819     InFlag = Chain.getValue(2);
1820     InVals.push_back(Val);
1821   }
1822
1823   return Chain;
1824 }
1825
1826 //===----------------------------------------------------------------------===//
1827 //                C & StdCall & Fast Calling Convention implementation
1828 //===----------------------------------------------------------------------===//
1829 //  StdCall calling convention seems to be standard for many Windows' API
1830 //  routines and around. It differs from C calling convention just a little:
1831 //  callee should clean up the stack, not caller. Symbols should be also
1832 //  decorated in some fancy way :) It doesn't support any vector arguments.
1833 //  For info on fast calling convention see Fast Calling Convention (tail call)
1834 //  implementation LowerX86_32FastCCCallTo.
1835
1836 /// CallIsStructReturn - Determines whether a call uses struct return
1837 /// semantics.
1838 enum StructReturnType {
1839   NotStructReturn,
1840   RegStructReturn,
1841   StackStructReturn
1842 };
1843 static StructReturnType
1844 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1845   if (Outs.empty())
1846     return NotStructReturn;
1847
1848   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1849   if (!Flags.isSRet())
1850     return NotStructReturn;
1851   if (Flags.isInReg())
1852     return RegStructReturn;
1853   return StackStructReturn;
1854 }
1855
1856 /// ArgsAreStructReturn - Determines whether a function uses struct
1857 /// return semantics.
1858 static StructReturnType
1859 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1860   if (Ins.empty())
1861     return NotStructReturn;
1862
1863   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1864   if (!Flags.isSRet())
1865     return NotStructReturn;
1866   if (Flags.isInReg())
1867     return RegStructReturn;
1868   return StackStructReturn;
1869 }
1870
1871 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1872 /// by "Src" to address "Dst" with size and alignment information specified by
1873 /// the specific parameter attribute. The copy will be passed as a byval
1874 /// function parameter.
1875 static SDValue
1876 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1877                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1878                           DebugLoc dl) {
1879   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1880
1881   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1882                        /*isVolatile*/false, /*AlwaysInline=*/true,
1883                        MachinePointerInfo(), MachinePointerInfo());
1884 }
1885
1886 /// IsTailCallConvention - Return true if the calling convention is one that
1887 /// supports tail call optimization.
1888 static bool IsTailCallConvention(CallingConv::ID CC) {
1889   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1890           CC == CallingConv::HiPE);
1891 }
1892
1893 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1894   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1895     return false;
1896
1897   CallSite CS(CI);
1898   CallingConv::ID CalleeCC = CS.getCallingConv();
1899   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1900     return false;
1901
1902   return true;
1903 }
1904
1905 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1906 /// a tailcall target by changing its ABI.
1907 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1908                                    bool GuaranteedTailCallOpt) {
1909   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1910 }
1911
1912 SDValue
1913 X86TargetLowering::LowerMemArgument(SDValue Chain,
1914                                     CallingConv::ID CallConv,
1915                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1916                                     DebugLoc dl, SelectionDAG &DAG,
1917                                     const CCValAssign &VA,
1918                                     MachineFrameInfo *MFI,
1919                                     unsigned i) const {
1920   // Create the nodes corresponding to a load from this parameter slot.
1921   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1922   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1923                               getTargetMachine().Options.GuaranteedTailCallOpt);
1924   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1925   EVT ValVT;
1926
1927   // If value is passed by pointer we have address passed instead of the value
1928   // itself.
1929   if (VA.getLocInfo() == CCValAssign::Indirect)
1930     ValVT = VA.getLocVT();
1931   else
1932     ValVT = VA.getValVT();
1933
1934   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1935   // changed with more analysis.
1936   // In case of tail call optimization mark all arguments mutable. Since they
1937   // could be overwritten by lowering of arguments in case of a tail call.
1938   if (Flags.isByVal()) {
1939     unsigned Bytes = Flags.getByValSize();
1940     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1941     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1942     return DAG.getFrameIndex(FI, getPointerTy());
1943   } else {
1944     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1945                                     VA.getLocMemOffset(), isImmutable);
1946     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1947     return DAG.getLoad(ValVT, dl, Chain, FIN,
1948                        MachinePointerInfo::getFixedStack(FI),
1949                        false, false, false, 0);
1950   }
1951 }
1952
1953 SDValue
1954 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1955                                         CallingConv::ID CallConv,
1956                                         bool isVarArg,
1957                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1958                                         DebugLoc dl,
1959                                         SelectionDAG &DAG,
1960                                         SmallVectorImpl<SDValue> &InVals)
1961                                           const {
1962   MachineFunction &MF = DAG.getMachineFunction();
1963   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1964
1965   const Function* Fn = MF.getFunction();
1966   if (Fn->hasExternalLinkage() &&
1967       Subtarget->isTargetCygMing() &&
1968       Fn->getName() == "main")
1969     FuncInfo->setForceFramePointer(true);
1970
1971   MachineFrameInfo *MFI = MF.getFrameInfo();
1972   bool Is64Bit = Subtarget->is64Bit();
1973   bool IsWindows = Subtarget->isTargetWindows();
1974   bool IsWin64 = Subtarget->isTargetWin64();
1975
1976   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1977          "Var args not supported with calling convention fastcc, ghc or hipe");
1978
1979   // Assign locations to all of the incoming arguments.
1980   SmallVector<CCValAssign, 16> ArgLocs;
1981   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1982                  ArgLocs, *DAG.getContext());
1983
1984   // Allocate shadow area for Win64
1985   if (IsWin64) {
1986     CCInfo.AllocateStack(32, 8);
1987   }
1988
1989   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1990
1991   unsigned LastVal = ~0U;
1992   SDValue ArgValue;
1993   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1994     CCValAssign &VA = ArgLocs[i];
1995     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1996     // places.
1997     assert(VA.getValNo() != LastVal &&
1998            "Don't support value assigned to multiple locs yet");
1999     (void)LastVal;
2000     LastVal = VA.getValNo();
2001
2002     if (VA.isRegLoc()) {
2003       EVT RegVT = VA.getLocVT();
2004       const TargetRegisterClass *RC;
2005       if (RegVT == MVT::i32)
2006         RC = &X86::GR32RegClass;
2007       else if (Is64Bit && RegVT == MVT::i64)
2008         RC = &X86::GR64RegClass;
2009       else if (RegVT == MVT::f32)
2010         RC = &X86::FR32RegClass;
2011       else if (RegVT == MVT::f64)
2012         RC = &X86::FR64RegClass;
2013       else if (RegVT.is256BitVector())
2014         RC = &X86::VR256RegClass;
2015       else if (RegVT.is128BitVector())
2016         RC = &X86::VR128RegClass;
2017       else if (RegVT == MVT::x86mmx)
2018         RC = &X86::VR64RegClass;
2019       else
2020         llvm_unreachable("Unknown argument type!");
2021
2022       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2023       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2024
2025       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2026       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2027       // right size.
2028       if (VA.getLocInfo() == CCValAssign::SExt)
2029         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2030                                DAG.getValueType(VA.getValVT()));
2031       else if (VA.getLocInfo() == CCValAssign::ZExt)
2032         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2033                                DAG.getValueType(VA.getValVT()));
2034       else if (VA.getLocInfo() == CCValAssign::BCvt)
2035         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2036
2037       if (VA.isExtInLoc()) {
2038         // Handle MMX values passed in XMM regs.
2039         if (RegVT.isVector())
2040           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2041         else
2042           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2043       }
2044     } else {
2045       assert(VA.isMemLoc());
2046       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2047     }
2048
2049     // If value is passed via pointer - do a load.
2050     if (VA.getLocInfo() == CCValAssign::Indirect)
2051       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2052                              MachinePointerInfo(), false, false, false, 0);
2053
2054     InVals.push_back(ArgValue);
2055   }
2056
2057   // The x86-64 ABIs require that for returning structs by value we copy
2058   // the sret argument into %rax/%eax (depending on ABI) for the return.
2059   // Win32 requires us to put the sret argument to %eax as well.
2060   // Save the argument into a virtual register so that we can access it
2061   // from the return points.
2062   if (MF.getFunction()->hasStructRetAttr() &&
2063       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2064     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2065     unsigned Reg = FuncInfo->getSRetReturnReg();
2066     if (!Reg) {
2067       MVT PtrTy = getPointerTy();
2068       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2069       FuncInfo->setSRetReturnReg(Reg);
2070     }
2071     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2072     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2073   }
2074
2075   unsigned StackSize = CCInfo.getNextStackOffset();
2076   // Align stack specially for tail calls.
2077   if (FuncIsMadeTailCallSafe(CallConv,
2078                              MF.getTarget().Options.GuaranteedTailCallOpt))
2079     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2080
2081   // If the function takes variable number of arguments, make a frame index for
2082   // the start of the first vararg value... for expansion of llvm.va_start.
2083   if (isVarArg) {
2084     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2085                     CallConv != CallingConv::X86_ThisCall)) {
2086       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2087     }
2088     if (Is64Bit) {
2089       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2090
2091       // FIXME: We should really autogenerate these arrays
2092       static const uint16_t GPR64ArgRegsWin64[] = {
2093         X86::RCX, X86::RDX, X86::R8,  X86::R9
2094       };
2095       static const uint16_t GPR64ArgRegs64Bit[] = {
2096         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2097       };
2098       static const uint16_t XMMArgRegs64Bit[] = {
2099         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2100         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2101       };
2102       const uint16_t *GPR64ArgRegs;
2103       unsigned NumXMMRegs = 0;
2104
2105       if (IsWin64) {
2106         // The XMM registers which might contain var arg parameters are shadowed
2107         // in their paired GPR.  So we only need to save the GPR to their home
2108         // slots.
2109         TotalNumIntRegs = 4;
2110         GPR64ArgRegs = GPR64ArgRegsWin64;
2111       } else {
2112         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2113         GPR64ArgRegs = GPR64ArgRegs64Bit;
2114
2115         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2116                                                 TotalNumXMMRegs);
2117       }
2118       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2119                                                        TotalNumIntRegs);
2120
2121       bool NoImplicitFloatOps = Fn->getAttributes().
2122         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2123       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2124              "SSE register cannot be used when SSE is disabled!");
2125       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2126                NoImplicitFloatOps) &&
2127              "SSE register cannot be used when SSE is disabled!");
2128       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2129           !Subtarget->hasSSE1())
2130         // Kernel mode asks for SSE to be disabled, so don't push them
2131         // on the stack.
2132         TotalNumXMMRegs = 0;
2133
2134       if (IsWin64) {
2135         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2136         // Get to the caller-allocated home save location.  Add 8 to account
2137         // for the return address.
2138         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2139         FuncInfo->setRegSaveFrameIndex(
2140           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2141         // Fixup to set vararg frame on shadow area (4 x i64).
2142         if (NumIntRegs < 4)
2143           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2144       } else {
2145         // For X86-64, if there are vararg parameters that are passed via
2146         // registers, then we must store them to their spots on the stack so
2147         // they may be loaded by deferencing the result of va_next.
2148         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2149         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2150         FuncInfo->setRegSaveFrameIndex(
2151           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2152                                false));
2153       }
2154
2155       // Store the integer parameter registers.
2156       SmallVector<SDValue, 8> MemOps;
2157       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2158                                         getPointerTy());
2159       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2160       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2161         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2162                                   DAG.getIntPtrConstant(Offset));
2163         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2164                                      &X86::GR64RegClass);
2165         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2166         SDValue Store =
2167           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2168                        MachinePointerInfo::getFixedStack(
2169                          FuncInfo->getRegSaveFrameIndex(), Offset),
2170                        false, false, 0);
2171         MemOps.push_back(Store);
2172         Offset += 8;
2173       }
2174
2175       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2176         // Now store the XMM (fp + vector) parameter registers.
2177         SmallVector<SDValue, 11> SaveXMMOps;
2178         SaveXMMOps.push_back(Chain);
2179
2180         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2181         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2182         SaveXMMOps.push_back(ALVal);
2183
2184         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2185                                FuncInfo->getRegSaveFrameIndex()));
2186         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2187                                FuncInfo->getVarArgsFPOffset()));
2188
2189         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2190           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2191                                        &X86::VR128RegClass);
2192           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2193           SaveXMMOps.push_back(Val);
2194         }
2195         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2196                                      MVT::Other,
2197                                      &SaveXMMOps[0], SaveXMMOps.size()));
2198       }
2199
2200       if (!MemOps.empty())
2201         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2202                             &MemOps[0], MemOps.size());
2203     }
2204   }
2205
2206   // Some CCs need callee pop.
2207   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2208                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2209     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2210   } else {
2211     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2212     // If this is an sret function, the return should pop the hidden pointer.
2213     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2214         argsAreStructReturn(Ins) == StackStructReturn)
2215       FuncInfo->setBytesToPopOnReturn(4);
2216   }
2217
2218   if (!Is64Bit) {
2219     // RegSaveFrameIndex is X86-64 only.
2220     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2221     if (CallConv == CallingConv::X86_FastCall ||
2222         CallConv == CallingConv::X86_ThisCall)
2223       // fastcc functions can't have varargs.
2224       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2225   }
2226
2227   FuncInfo->setArgumentStackSize(StackSize);
2228
2229   return Chain;
2230 }
2231
2232 SDValue
2233 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2234                                     SDValue StackPtr, SDValue Arg,
2235                                     DebugLoc dl, SelectionDAG &DAG,
2236                                     const CCValAssign &VA,
2237                                     ISD::ArgFlagsTy Flags) const {
2238   unsigned LocMemOffset = VA.getLocMemOffset();
2239   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2240   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2241   if (Flags.isByVal())
2242     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2243
2244   return DAG.getStore(Chain, dl, Arg, PtrOff,
2245                       MachinePointerInfo::getStack(LocMemOffset),
2246                       false, false, 0);
2247 }
2248
2249 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2250 /// optimization is performed and it is required.
2251 SDValue
2252 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2253                                            SDValue &OutRetAddr, SDValue Chain,
2254                                            bool IsTailCall, bool Is64Bit,
2255                                            int FPDiff, DebugLoc dl) const {
2256   // Adjust the Return address stack slot.
2257   EVT VT = getPointerTy();
2258   OutRetAddr = getReturnAddressFrameIndex(DAG);
2259
2260   // Load the "old" Return address.
2261   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2262                            false, false, false, 0);
2263   return SDValue(OutRetAddr.getNode(), 1);
2264 }
2265
2266 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2267 /// optimization is performed and it is required (FPDiff!=0).
2268 static SDValue
2269 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2270                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2271                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2272   // Store the return address to the appropriate stack slot.
2273   if (!FPDiff) return Chain;
2274   // Calculate the new stack slot for the return address.
2275   int NewReturnAddrFI =
2276     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2277   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2278   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2279                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2280                        false, false, 0);
2281   return Chain;
2282 }
2283
2284 SDValue
2285 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2286                              SmallVectorImpl<SDValue> &InVals) const {
2287   SelectionDAG &DAG                     = CLI.DAG;
2288   DebugLoc &dl                          = CLI.DL;
2289   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2290   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2291   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2292   SDValue Chain                         = CLI.Chain;
2293   SDValue Callee                        = CLI.Callee;
2294   CallingConv::ID CallConv              = CLI.CallConv;
2295   bool &isTailCall                      = CLI.IsTailCall;
2296   bool isVarArg                         = CLI.IsVarArg;
2297
2298   MachineFunction &MF = DAG.getMachineFunction();
2299   bool Is64Bit        = Subtarget->is64Bit();
2300   bool IsWin64        = Subtarget->isTargetWin64();
2301   bool IsWindows      = Subtarget->isTargetWindows();
2302   StructReturnType SR = callIsStructReturn(Outs);
2303   bool IsSibcall      = false;
2304
2305   if (MF.getTarget().Options.DisableTailCalls)
2306     isTailCall = false;
2307
2308   if (isTailCall) {
2309     // Check if it's really possible to do a tail call.
2310     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2311                     isVarArg, SR != NotStructReturn,
2312                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2313                     Outs, OutVals, Ins, DAG);
2314
2315     // Sibcalls are automatically detected tailcalls which do not require
2316     // ABI changes.
2317     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2318       IsSibcall = true;
2319
2320     if (isTailCall)
2321       ++NumTailCalls;
2322   }
2323
2324   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2325          "Var args not supported with calling convention fastcc, ghc or hipe");
2326
2327   // Analyze operands of the call, assigning locations to each operand.
2328   SmallVector<CCValAssign, 16> ArgLocs;
2329   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2330                  ArgLocs, *DAG.getContext());
2331
2332   // Allocate shadow area for Win64
2333   if (IsWin64) {
2334     CCInfo.AllocateStack(32, 8);
2335   }
2336
2337   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2338
2339   // Get a count of how many bytes are to be pushed on the stack.
2340   unsigned NumBytes = CCInfo.getNextStackOffset();
2341   if (IsSibcall)
2342     // This is a sibcall. The memory operands are available in caller's
2343     // own caller's stack.
2344     NumBytes = 0;
2345   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2346            IsTailCallConvention(CallConv))
2347     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2348
2349   int FPDiff = 0;
2350   if (isTailCall && !IsSibcall) {
2351     // Lower arguments at fp - stackoffset + fpdiff.
2352     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2353     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2354
2355     FPDiff = NumBytesCallerPushed - NumBytes;
2356
2357     // Set the delta of movement of the returnaddr stackslot.
2358     // But only set if delta is greater than previous delta.
2359     if (FPDiff < X86Info->getTCReturnAddrDelta())
2360       X86Info->setTCReturnAddrDelta(FPDiff);
2361   }
2362
2363   if (!IsSibcall)
2364     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2365
2366   SDValue RetAddrFrIdx;
2367   // Load return address for tail calls.
2368   if (isTailCall && FPDiff)
2369     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2370                                     Is64Bit, FPDiff, dl);
2371
2372   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2373   SmallVector<SDValue, 8> MemOpChains;
2374   SDValue StackPtr;
2375
2376   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2377   // of tail call optimization arguments are handle later.
2378   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2379     CCValAssign &VA = ArgLocs[i];
2380     EVT RegVT = VA.getLocVT();
2381     SDValue Arg = OutVals[i];
2382     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2383     bool isByVal = Flags.isByVal();
2384
2385     // Promote the value if needed.
2386     switch (VA.getLocInfo()) {
2387     default: llvm_unreachable("Unknown loc info!");
2388     case CCValAssign::Full: break;
2389     case CCValAssign::SExt:
2390       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2391       break;
2392     case CCValAssign::ZExt:
2393       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2394       break;
2395     case CCValAssign::AExt:
2396       if (RegVT.is128BitVector()) {
2397         // Special case: passing MMX values in XMM registers.
2398         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2399         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2400         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2401       } else
2402         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2403       break;
2404     case CCValAssign::BCvt:
2405       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2406       break;
2407     case CCValAssign::Indirect: {
2408       // Store the argument.
2409       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2410       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2411       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2412                            MachinePointerInfo::getFixedStack(FI),
2413                            false, false, 0);
2414       Arg = SpillSlot;
2415       break;
2416     }
2417     }
2418
2419     if (VA.isRegLoc()) {
2420       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2421       if (isVarArg && IsWin64) {
2422         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2423         // shadow reg if callee is a varargs function.
2424         unsigned ShadowReg = 0;
2425         switch (VA.getLocReg()) {
2426         case X86::XMM0: ShadowReg = X86::RCX; break;
2427         case X86::XMM1: ShadowReg = X86::RDX; break;
2428         case X86::XMM2: ShadowReg = X86::R8; break;
2429         case X86::XMM3: ShadowReg = X86::R9; break;
2430         }
2431         if (ShadowReg)
2432           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2433       }
2434     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2435       assert(VA.isMemLoc());
2436       if (StackPtr.getNode() == 0)
2437         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2438                                       getPointerTy());
2439       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2440                                              dl, DAG, VA, Flags));
2441     }
2442   }
2443
2444   if (!MemOpChains.empty())
2445     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2446                         &MemOpChains[0], MemOpChains.size());
2447
2448   if (Subtarget->isPICStyleGOT()) {
2449     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2450     // GOT pointer.
2451     if (!isTailCall) {
2452       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2453                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2454     } else {
2455       // If we are tail calling and generating PIC/GOT style code load the
2456       // address of the callee into ECX. The value in ecx is used as target of
2457       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2458       // for tail calls on PIC/GOT architectures. Normally we would just put the
2459       // address of GOT into ebx and then call target@PLT. But for tail calls
2460       // ebx would be restored (since ebx is callee saved) before jumping to the
2461       // target@PLT.
2462
2463       // Note: The actual moving to ECX is done further down.
2464       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2465       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2466           !G->getGlobal()->hasProtectedVisibility())
2467         Callee = LowerGlobalAddress(Callee, DAG);
2468       else if (isa<ExternalSymbolSDNode>(Callee))
2469         Callee = LowerExternalSymbol(Callee, DAG);
2470     }
2471   }
2472
2473   if (Is64Bit && isVarArg && !IsWin64) {
2474     // From AMD64 ABI document:
2475     // For calls that may call functions that use varargs or stdargs
2476     // (prototype-less calls or calls to functions containing ellipsis (...) in
2477     // the declaration) %al is used as hidden argument to specify the number
2478     // of SSE registers used. The contents of %al do not need to match exactly
2479     // the number of registers, but must be an ubound on the number of SSE
2480     // registers used and is in the range 0 - 8 inclusive.
2481
2482     // Count the number of XMM registers allocated.
2483     static const uint16_t XMMArgRegs[] = {
2484       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2485       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2486     };
2487     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2488     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2489            && "SSE registers cannot be used when SSE is disabled");
2490
2491     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2492                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2493   }
2494
2495   // For tail calls lower the arguments to the 'real' stack slot.
2496   if (isTailCall) {
2497     // Force all the incoming stack arguments to be loaded from the stack
2498     // before any new outgoing arguments are stored to the stack, because the
2499     // outgoing stack slots may alias the incoming argument stack slots, and
2500     // the alias isn't otherwise explicit. This is slightly more conservative
2501     // than necessary, because it means that each store effectively depends
2502     // on every argument instead of just those arguments it would clobber.
2503     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2504
2505     SmallVector<SDValue, 8> MemOpChains2;
2506     SDValue FIN;
2507     int FI = 0;
2508     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2509       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2510         CCValAssign &VA = ArgLocs[i];
2511         if (VA.isRegLoc())
2512           continue;
2513         assert(VA.isMemLoc());
2514         SDValue Arg = OutVals[i];
2515         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2516         // Create frame index.
2517         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2518         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2519         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2520         FIN = DAG.getFrameIndex(FI, getPointerTy());
2521
2522         if (Flags.isByVal()) {
2523           // Copy relative to framepointer.
2524           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2525           if (StackPtr.getNode() == 0)
2526             StackPtr = DAG.getCopyFromReg(Chain, dl,
2527                                           RegInfo->getStackRegister(),
2528                                           getPointerTy());
2529           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2530
2531           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2532                                                            ArgChain,
2533                                                            Flags, DAG, dl));
2534         } else {
2535           // Store relative to framepointer.
2536           MemOpChains2.push_back(
2537             DAG.getStore(ArgChain, dl, Arg, FIN,
2538                          MachinePointerInfo::getFixedStack(FI),
2539                          false, false, 0));
2540         }
2541       }
2542     }
2543
2544     if (!MemOpChains2.empty())
2545       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2546                           &MemOpChains2[0], MemOpChains2.size());
2547
2548     // Store the return address to the appropriate stack slot.
2549     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2550                                      getPointerTy(), RegInfo->getSlotSize(),
2551                                      FPDiff, dl);
2552   }
2553
2554   // Build a sequence of copy-to-reg nodes chained together with token chain
2555   // and flag operands which copy the outgoing args into registers.
2556   SDValue InFlag;
2557   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2558     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2559                              RegsToPass[i].second, InFlag);
2560     InFlag = Chain.getValue(1);
2561   }
2562
2563   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2564     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2565     // In the 64-bit large code model, we have to make all calls
2566     // through a register, since the call instruction's 32-bit
2567     // pc-relative offset may not be large enough to hold the whole
2568     // address.
2569   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2570     // If the callee is a GlobalAddress node (quite common, every direct call
2571     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2572     // it.
2573
2574     // We should use extra load for direct calls to dllimported functions in
2575     // non-JIT mode.
2576     const GlobalValue *GV = G->getGlobal();
2577     if (!GV->hasDLLImportLinkage()) {
2578       unsigned char OpFlags = 0;
2579       bool ExtraLoad = false;
2580       unsigned WrapperKind = ISD::DELETED_NODE;
2581
2582       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2583       // external symbols most go through the PLT in PIC mode.  If the symbol
2584       // has hidden or protected visibility, or if it is static or local, then
2585       // we don't need to use the PLT - we can directly call it.
2586       if (Subtarget->isTargetELF() &&
2587           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2588           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2589         OpFlags = X86II::MO_PLT;
2590       } else if (Subtarget->isPICStyleStubAny() &&
2591                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2592                  (!Subtarget->getTargetTriple().isMacOSX() ||
2593                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2594         // PC-relative references to external symbols should go through $stub,
2595         // unless we're building with the leopard linker or later, which
2596         // automatically synthesizes these stubs.
2597         OpFlags = X86II::MO_DARWIN_STUB;
2598       } else if (Subtarget->isPICStyleRIPRel() &&
2599                  isa<Function>(GV) &&
2600                  cast<Function>(GV)->getAttributes().
2601                    hasAttribute(AttributeSet::FunctionIndex,
2602                                 Attribute::NonLazyBind)) {
2603         // If the function is marked as non-lazy, generate an indirect call
2604         // which loads from the GOT directly. This avoids runtime overhead
2605         // at the cost of eager binding (and one extra byte of encoding).
2606         OpFlags = X86II::MO_GOTPCREL;
2607         WrapperKind = X86ISD::WrapperRIP;
2608         ExtraLoad = true;
2609       }
2610
2611       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2612                                           G->getOffset(), OpFlags);
2613
2614       // Add a wrapper if needed.
2615       if (WrapperKind != ISD::DELETED_NODE)
2616         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2617       // Add extra indirection if needed.
2618       if (ExtraLoad)
2619         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2620                              MachinePointerInfo::getGOT(),
2621                              false, false, false, 0);
2622     }
2623   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2624     unsigned char OpFlags = 0;
2625
2626     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2627     // external symbols should go through the PLT.
2628     if (Subtarget->isTargetELF() &&
2629         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2630       OpFlags = X86II::MO_PLT;
2631     } else if (Subtarget->isPICStyleStubAny() &&
2632                (!Subtarget->getTargetTriple().isMacOSX() ||
2633                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2634       // PC-relative references to external symbols should go through $stub,
2635       // unless we're building with the leopard linker or later, which
2636       // automatically synthesizes these stubs.
2637       OpFlags = X86II::MO_DARWIN_STUB;
2638     }
2639
2640     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2641                                          OpFlags);
2642   }
2643
2644   // Returns a chain & a flag for retval copy to use.
2645   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2646   SmallVector<SDValue, 8> Ops;
2647
2648   if (!IsSibcall && isTailCall) {
2649     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2650                            DAG.getIntPtrConstant(0, true), InFlag);
2651     InFlag = Chain.getValue(1);
2652   }
2653
2654   Ops.push_back(Chain);
2655   Ops.push_back(Callee);
2656
2657   if (isTailCall)
2658     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2659
2660   // Add argument registers to the end of the list so that they are known live
2661   // into the call.
2662   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2663     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2664                                   RegsToPass[i].second.getValueType()));
2665
2666   // Add a register mask operand representing the call-preserved registers.
2667   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2668   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2669   assert(Mask && "Missing call preserved mask for calling convention");
2670   Ops.push_back(DAG.getRegisterMask(Mask));
2671
2672   if (InFlag.getNode())
2673     Ops.push_back(InFlag);
2674
2675   if (isTailCall) {
2676     // We used to do:
2677     //// If this is the first return lowered for this function, add the regs
2678     //// to the liveout set for the function.
2679     // This isn't right, although it's probably harmless on x86; liveouts
2680     // should be computed from returns not tail calls.  Consider a void
2681     // function making a tail call to a function returning int.
2682     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2683   }
2684
2685   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2686   InFlag = Chain.getValue(1);
2687
2688   // Create the CALLSEQ_END node.
2689   unsigned NumBytesForCalleeToPush;
2690   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2691                        getTargetMachine().Options.GuaranteedTailCallOpt))
2692     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2693   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2694            SR == StackStructReturn)
2695     // If this is a call to a struct-return function, the callee
2696     // pops the hidden struct pointer, so we have to push it back.
2697     // This is common for Darwin/X86, Linux & Mingw32 targets.
2698     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2699     NumBytesForCalleeToPush = 4;
2700   else
2701     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2702
2703   // Returns a flag for retval copy to use.
2704   if (!IsSibcall) {
2705     Chain = DAG.getCALLSEQ_END(Chain,
2706                                DAG.getIntPtrConstant(NumBytes, true),
2707                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2708                                                      true),
2709                                InFlag);
2710     InFlag = Chain.getValue(1);
2711   }
2712
2713   // Handle result values, copying them out of physregs into vregs that we
2714   // return.
2715   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2716                          Ins, dl, DAG, InVals);
2717 }
2718
2719 //===----------------------------------------------------------------------===//
2720 //                Fast Calling Convention (tail call) implementation
2721 //===----------------------------------------------------------------------===//
2722
2723 //  Like std call, callee cleans arguments, convention except that ECX is
2724 //  reserved for storing the tail called function address. Only 2 registers are
2725 //  free for argument passing (inreg). Tail call optimization is performed
2726 //  provided:
2727 //                * tailcallopt is enabled
2728 //                * caller/callee are fastcc
2729 //  On X86_64 architecture with GOT-style position independent code only local
2730 //  (within module) calls are supported at the moment.
2731 //  To keep the stack aligned according to platform abi the function
2732 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2733 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2734 //  If a tail called function callee has more arguments than the caller the
2735 //  caller needs to make sure that there is room to move the RETADDR to. This is
2736 //  achieved by reserving an area the size of the argument delta right after the
2737 //  original REtADDR, but before the saved framepointer or the spilled registers
2738 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2739 //  stack layout:
2740 //    arg1
2741 //    arg2
2742 //    RETADDR
2743 //    [ new RETADDR
2744 //      move area ]
2745 //    (possible EBP)
2746 //    ESI
2747 //    EDI
2748 //    local1 ..
2749
2750 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2751 /// for a 16 byte align requirement.
2752 unsigned
2753 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2754                                                SelectionDAG& DAG) const {
2755   MachineFunction &MF = DAG.getMachineFunction();
2756   const TargetMachine &TM = MF.getTarget();
2757   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2758   unsigned StackAlignment = TFI.getStackAlignment();
2759   uint64_t AlignMask = StackAlignment - 1;
2760   int64_t Offset = StackSize;
2761   unsigned SlotSize = RegInfo->getSlotSize();
2762   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2763     // Number smaller than 12 so just add the difference.
2764     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2765   } else {
2766     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2767     Offset = ((~AlignMask) & Offset) + StackAlignment +
2768       (StackAlignment-SlotSize);
2769   }
2770   return Offset;
2771 }
2772
2773 /// MatchingStackOffset - Return true if the given stack call argument is
2774 /// already available in the same position (relatively) of the caller's
2775 /// incoming argument stack.
2776 static
2777 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2778                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2779                          const X86InstrInfo *TII) {
2780   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2781   int FI = INT_MAX;
2782   if (Arg.getOpcode() == ISD::CopyFromReg) {
2783     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2784     if (!TargetRegisterInfo::isVirtualRegister(VR))
2785       return false;
2786     MachineInstr *Def = MRI->getVRegDef(VR);
2787     if (!Def)
2788       return false;
2789     if (!Flags.isByVal()) {
2790       if (!TII->isLoadFromStackSlot(Def, FI))
2791         return false;
2792     } else {
2793       unsigned Opcode = Def->getOpcode();
2794       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2795           Def->getOperand(1).isFI()) {
2796         FI = Def->getOperand(1).getIndex();
2797         Bytes = Flags.getByValSize();
2798       } else
2799         return false;
2800     }
2801   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2802     if (Flags.isByVal())
2803       // ByVal argument is passed in as a pointer but it's now being
2804       // dereferenced. e.g.
2805       // define @foo(%struct.X* %A) {
2806       //   tail call @bar(%struct.X* byval %A)
2807       // }
2808       return false;
2809     SDValue Ptr = Ld->getBasePtr();
2810     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2811     if (!FINode)
2812       return false;
2813     FI = FINode->getIndex();
2814   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2815     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2816     FI = FINode->getIndex();
2817     Bytes = Flags.getByValSize();
2818   } else
2819     return false;
2820
2821   assert(FI != INT_MAX);
2822   if (!MFI->isFixedObjectIndex(FI))
2823     return false;
2824   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2825 }
2826
2827 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2828 /// for tail call optimization. Targets which want to do tail call
2829 /// optimization should implement this function.
2830 bool
2831 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2832                                                      CallingConv::ID CalleeCC,
2833                                                      bool isVarArg,
2834                                                      bool isCalleeStructRet,
2835                                                      bool isCallerStructRet,
2836                                                      Type *RetTy,
2837                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2838                                     const SmallVectorImpl<SDValue> &OutVals,
2839                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2840                                                      SelectionDAG &DAG) const {
2841   if (!IsTailCallConvention(CalleeCC) &&
2842       CalleeCC != CallingConv::C)
2843     return false;
2844
2845   // If -tailcallopt is specified, make fastcc functions tail-callable.
2846   const MachineFunction &MF = DAG.getMachineFunction();
2847   const Function *CallerF = DAG.getMachineFunction().getFunction();
2848
2849   // If the function return type is x86_fp80 and the callee return type is not,
2850   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2851   // perform a tailcall optimization here.
2852   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2853     return false;
2854
2855   CallingConv::ID CallerCC = CallerF->getCallingConv();
2856   bool CCMatch = CallerCC == CalleeCC;
2857
2858   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2859     if (IsTailCallConvention(CalleeCC) && CCMatch)
2860       return true;
2861     return false;
2862   }
2863
2864   // Look for obvious safe cases to perform tail call optimization that do not
2865   // require ABI changes. This is what gcc calls sibcall.
2866
2867   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2868   // emit a special epilogue.
2869   if (RegInfo->needsStackRealignment(MF))
2870     return false;
2871
2872   // Also avoid sibcall optimization if either caller or callee uses struct
2873   // return semantics.
2874   if (isCalleeStructRet || isCallerStructRet)
2875     return false;
2876
2877   // An stdcall caller is expected to clean up its arguments; the callee
2878   // isn't going to do that.
2879   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2880     return false;
2881
2882   // Do not sibcall optimize vararg calls unless all arguments are passed via
2883   // registers.
2884   if (isVarArg && !Outs.empty()) {
2885
2886     // Optimizing for varargs on Win64 is unlikely to be safe without
2887     // additional testing.
2888     if (Subtarget->isTargetWin64())
2889       return false;
2890
2891     SmallVector<CCValAssign, 16> ArgLocs;
2892     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2893                    getTargetMachine(), ArgLocs, *DAG.getContext());
2894
2895     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2896     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2897       if (!ArgLocs[i].isRegLoc())
2898         return false;
2899   }
2900
2901   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2902   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2903   // this into a sibcall.
2904   bool Unused = false;
2905   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2906     if (!Ins[i].Used) {
2907       Unused = true;
2908       break;
2909     }
2910   }
2911   if (Unused) {
2912     SmallVector<CCValAssign, 16> RVLocs;
2913     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2914                    getTargetMachine(), RVLocs, *DAG.getContext());
2915     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2916     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2917       CCValAssign &VA = RVLocs[i];
2918       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2919         return false;
2920     }
2921   }
2922
2923   // If the calling conventions do not match, then we'd better make sure the
2924   // results are returned in the same way as what the caller expects.
2925   if (!CCMatch) {
2926     SmallVector<CCValAssign, 16> RVLocs1;
2927     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2928                     getTargetMachine(), RVLocs1, *DAG.getContext());
2929     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2930
2931     SmallVector<CCValAssign, 16> RVLocs2;
2932     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2933                     getTargetMachine(), RVLocs2, *DAG.getContext());
2934     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2935
2936     if (RVLocs1.size() != RVLocs2.size())
2937       return false;
2938     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2939       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2940         return false;
2941       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2942         return false;
2943       if (RVLocs1[i].isRegLoc()) {
2944         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2945           return false;
2946       } else {
2947         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2948           return false;
2949       }
2950     }
2951   }
2952
2953   // If the callee takes no arguments then go on to check the results of the
2954   // call.
2955   if (!Outs.empty()) {
2956     // Check if stack adjustment is needed. For now, do not do this if any
2957     // argument is passed on the stack.
2958     SmallVector<CCValAssign, 16> ArgLocs;
2959     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2960                    getTargetMachine(), ArgLocs, *DAG.getContext());
2961
2962     // Allocate shadow area for Win64
2963     if (Subtarget->isTargetWin64()) {
2964       CCInfo.AllocateStack(32, 8);
2965     }
2966
2967     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2968     if (CCInfo.getNextStackOffset()) {
2969       MachineFunction &MF = DAG.getMachineFunction();
2970       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2971         return false;
2972
2973       // Check if the arguments are already laid out in the right way as
2974       // the caller's fixed stack objects.
2975       MachineFrameInfo *MFI = MF.getFrameInfo();
2976       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2977       const X86InstrInfo *TII =
2978         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2979       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2980         CCValAssign &VA = ArgLocs[i];
2981         SDValue Arg = OutVals[i];
2982         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2983         if (VA.getLocInfo() == CCValAssign::Indirect)
2984           return false;
2985         if (!VA.isRegLoc()) {
2986           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2987                                    MFI, MRI, TII))
2988             return false;
2989         }
2990       }
2991     }
2992
2993     // If the tailcall address may be in a register, then make sure it's
2994     // possible to register allocate for it. In 32-bit, the call address can
2995     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2996     // callee-saved registers are restored. These happen to be the same
2997     // registers used to pass 'inreg' arguments so watch out for those.
2998     if (!Subtarget->is64Bit() &&
2999         ((!isa<GlobalAddressSDNode>(Callee) &&
3000           !isa<ExternalSymbolSDNode>(Callee)) ||
3001          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3002       unsigned NumInRegs = 0;
3003       // In PIC we need an extra register to formulate the address computation
3004       // for the callee.
3005       unsigned MaxInRegs =
3006           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3007
3008       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3009         CCValAssign &VA = ArgLocs[i];
3010         if (!VA.isRegLoc())
3011           continue;
3012         unsigned Reg = VA.getLocReg();
3013         switch (Reg) {
3014         default: break;
3015         case X86::EAX: case X86::EDX: case X86::ECX:
3016           if (++NumInRegs == MaxInRegs)
3017             return false;
3018           break;
3019         }
3020       }
3021     }
3022   }
3023
3024   return true;
3025 }
3026
3027 FastISel *
3028 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3029                                   const TargetLibraryInfo *libInfo) const {
3030   return X86::createFastISel(funcInfo, libInfo);
3031 }
3032
3033 //===----------------------------------------------------------------------===//
3034 //                           Other Lowering Hooks
3035 //===----------------------------------------------------------------------===//
3036
3037 static bool MayFoldLoad(SDValue Op) {
3038   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3039 }
3040
3041 static bool MayFoldIntoStore(SDValue Op) {
3042   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3043 }
3044
3045 static bool isTargetShuffle(unsigned Opcode) {
3046   switch(Opcode) {
3047   default: return false;
3048   case X86ISD::PSHUFD:
3049   case X86ISD::PSHUFHW:
3050   case X86ISD::PSHUFLW:
3051   case X86ISD::SHUFP:
3052   case X86ISD::PALIGNR:
3053   case X86ISD::MOVLHPS:
3054   case X86ISD::MOVLHPD:
3055   case X86ISD::MOVHLPS:
3056   case X86ISD::MOVLPS:
3057   case X86ISD::MOVLPD:
3058   case X86ISD::MOVSHDUP:
3059   case X86ISD::MOVSLDUP:
3060   case X86ISD::MOVDDUP:
3061   case X86ISD::MOVSS:
3062   case X86ISD::MOVSD:
3063   case X86ISD::UNPCKL:
3064   case X86ISD::UNPCKH:
3065   case X86ISD::VPERMILP:
3066   case X86ISD::VPERM2X128:
3067   case X86ISD::VPERMI:
3068     return true;
3069   }
3070 }
3071
3072 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3073                                     SDValue V1, SelectionDAG &DAG) {
3074   switch(Opc) {
3075   default: llvm_unreachable("Unknown x86 shuffle node");
3076   case X86ISD::MOVSHDUP:
3077   case X86ISD::MOVSLDUP:
3078   case X86ISD::MOVDDUP:
3079     return DAG.getNode(Opc, dl, VT, V1);
3080   }
3081 }
3082
3083 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3084                                     SDValue V1, unsigned TargetMask,
3085                                     SelectionDAG &DAG) {
3086   switch(Opc) {
3087   default: llvm_unreachable("Unknown x86 shuffle node");
3088   case X86ISD::PSHUFD:
3089   case X86ISD::PSHUFHW:
3090   case X86ISD::PSHUFLW:
3091   case X86ISD::VPERMILP:
3092   case X86ISD::VPERMI:
3093     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3094   }
3095 }
3096
3097 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3098                                     SDValue V1, SDValue V2, unsigned TargetMask,
3099                                     SelectionDAG &DAG) {
3100   switch(Opc) {
3101   default: llvm_unreachable("Unknown x86 shuffle node");
3102   case X86ISD::PALIGNR:
3103   case X86ISD::SHUFP:
3104   case X86ISD::VPERM2X128:
3105     return DAG.getNode(Opc, dl, VT, V1, V2,
3106                        DAG.getConstant(TargetMask, MVT::i8));
3107   }
3108 }
3109
3110 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3111                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3112   switch(Opc) {
3113   default: llvm_unreachable("Unknown x86 shuffle node");
3114   case X86ISD::MOVLHPS:
3115   case X86ISD::MOVLHPD:
3116   case X86ISD::MOVHLPS:
3117   case X86ISD::MOVLPS:
3118   case X86ISD::MOVLPD:
3119   case X86ISD::MOVSS:
3120   case X86ISD::MOVSD:
3121   case X86ISD::UNPCKL:
3122   case X86ISD::UNPCKH:
3123     return DAG.getNode(Opc, dl, VT, V1, V2);
3124   }
3125 }
3126
3127 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3128   MachineFunction &MF = DAG.getMachineFunction();
3129   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3130   int ReturnAddrIndex = FuncInfo->getRAIndex();
3131
3132   if (ReturnAddrIndex == 0) {
3133     // Set up a frame object for the return address.
3134     unsigned SlotSize = RegInfo->getSlotSize();
3135     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3136                                                            false);
3137     FuncInfo->setRAIndex(ReturnAddrIndex);
3138   }
3139
3140   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3141 }
3142
3143 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3144                                        bool hasSymbolicDisplacement) {
3145   // Offset should fit into 32 bit immediate field.
3146   if (!isInt<32>(Offset))
3147     return false;
3148
3149   // If we don't have a symbolic displacement - we don't have any extra
3150   // restrictions.
3151   if (!hasSymbolicDisplacement)
3152     return true;
3153
3154   // FIXME: Some tweaks might be needed for medium code model.
3155   if (M != CodeModel::Small && M != CodeModel::Kernel)
3156     return false;
3157
3158   // For small code model we assume that latest object is 16MB before end of 31
3159   // bits boundary. We may also accept pretty large negative constants knowing
3160   // that all objects are in the positive half of address space.
3161   if (M == CodeModel::Small && Offset < 16*1024*1024)
3162     return true;
3163
3164   // For kernel code model we know that all object resist in the negative half
3165   // of 32bits address space. We may not accept negative offsets, since they may
3166   // be just off and we may accept pretty large positive ones.
3167   if (M == CodeModel::Kernel && Offset > 0)
3168     return true;
3169
3170   return false;
3171 }
3172
3173 /// isCalleePop - Determines whether the callee is required to pop its
3174 /// own arguments. Callee pop is necessary to support tail calls.
3175 bool X86::isCalleePop(CallingConv::ID CallingConv,
3176                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3177   if (IsVarArg)
3178     return false;
3179
3180   switch (CallingConv) {
3181   default:
3182     return false;
3183   case CallingConv::X86_StdCall:
3184     return !is64Bit;
3185   case CallingConv::X86_FastCall:
3186     return !is64Bit;
3187   case CallingConv::X86_ThisCall:
3188     return !is64Bit;
3189   case CallingConv::Fast:
3190     return TailCallOpt;
3191   case CallingConv::GHC:
3192     return TailCallOpt;
3193   case CallingConv::HiPE:
3194     return TailCallOpt;
3195   }
3196 }
3197
3198 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3199 /// specific condition code, returning the condition code and the LHS/RHS of the
3200 /// comparison to make.
3201 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3202                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3203   if (!isFP) {
3204     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3205       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3206         // X > -1   -> X == 0, jump !sign.
3207         RHS = DAG.getConstant(0, RHS.getValueType());
3208         return X86::COND_NS;
3209       }
3210       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3211         // X < 0   -> X == 0, jump on sign.
3212         return X86::COND_S;
3213       }
3214       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3215         // X < 1   -> X <= 0
3216         RHS = DAG.getConstant(0, RHS.getValueType());
3217         return X86::COND_LE;
3218       }
3219     }
3220
3221     switch (SetCCOpcode) {
3222     default: llvm_unreachable("Invalid integer condition!");
3223     case ISD::SETEQ:  return X86::COND_E;
3224     case ISD::SETGT:  return X86::COND_G;
3225     case ISD::SETGE:  return X86::COND_GE;
3226     case ISD::SETLT:  return X86::COND_L;
3227     case ISD::SETLE:  return X86::COND_LE;
3228     case ISD::SETNE:  return X86::COND_NE;
3229     case ISD::SETULT: return X86::COND_B;
3230     case ISD::SETUGT: return X86::COND_A;
3231     case ISD::SETULE: return X86::COND_BE;
3232     case ISD::SETUGE: return X86::COND_AE;
3233     }
3234   }
3235
3236   // First determine if it is required or is profitable to flip the operands.
3237
3238   // If LHS is a foldable load, but RHS is not, flip the condition.
3239   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3240       !ISD::isNON_EXTLoad(RHS.getNode())) {
3241     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3242     std::swap(LHS, RHS);
3243   }
3244
3245   switch (SetCCOpcode) {
3246   default: break;
3247   case ISD::SETOLT:
3248   case ISD::SETOLE:
3249   case ISD::SETUGT:
3250   case ISD::SETUGE:
3251     std::swap(LHS, RHS);
3252     break;
3253   }
3254
3255   // On a floating point condition, the flags are set as follows:
3256   // ZF  PF  CF   op
3257   //  0 | 0 | 0 | X > Y
3258   //  0 | 0 | 1 | X < Y
3259   //  1 | 0 | 0 | X == Y
3260   //  1 | 1 | 1 | unordered
3261   switch (SetCCOpcode) {
3262   default: llvm_unreachable("Condcode should be pre-legalized away");
3263   case ISD::SETUEQ:
3264   case ISD::SETEQ:   return X86::COND_E;
3265   case ISD::SETOLT:              // flipped
3266   case ISD::SETOGT:
3267   case ISD::SETGT:   return X86::COND_A;
3268   case ISD::SETOLE:              // flipped
3269   case ISD::SETOGE:
3270   case ISD::SETGE:   return X86::COND_AE;
3271   case ISD::SETUGT:              // flipped
3272   case ISD::SETULT:
3273   case ISD::SETLT:   return X86::COND_B;
3274   case ISD::SETUGE:              // flipped
3275   case ISD::SETULE:
3276   case ISD::SETLE:   return X86::COND_BE;
3277   case ISD::SETONE:
3278   case ISD::SETNE:   return X86::COND_NE;
3279   case ISD::SETUO:   return X86::COND_P;
3280   case ISD::SETO:    return X86::COND_NP;
3281   case ISD::SETOEQ:
3282   case ISD::SETUNE:  return X86::COND_INVALID;
3283   }
3284 }
3285
3286 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3287 /// code. Current x86 isa includes the following FP cmov instructions:
3288 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3289 static bool hasFPCMov(unsigned X86CC) {
3290   switch (X86CC) {
3291   default:
3292     return false;
3293   case X86::COND_B:
3294   case X86::COND_BE:
3295   case X86::COND_E:
3296   case X86::COND_P:
3297   case X86::COND_A:
3298   case X86::COND_AE:
3299   case X86::COND_NE:
3300   case X86::COND_NP:
3301     return true;
3302   }
3303 }
3304
3305 /// isFPImmLegal - Returns true if the target can instruction select the
3306 /// specified FP immediate natively. If false, the legalizer will
3307 /// materialize the FP immediate as a load from a constant pool.
3308 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3309   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3310     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3311       return true;
3312   }
3313   return false;
3314 }
3315
3316 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3317 /// the specified range (L, H].
3318 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3319   return (Val < 0) || (Val >= Low && Val < Hi);
3320 }
3321
3322 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3323 /// specified value.
3324 static bool isUndefOrEqual(int Val, int CmpVal) {
3325   return (Val < 0 || Val == CmpVal);
3326 }
3327
3328 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3329 /// from position Pos and ending in Pos+Size, falls within the specified
3330 /// sequential range (L, L+Pos]. or is undef.
3331 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3332                                        unsigned Pos, unsigned Size, int Low) {
3333   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3334     if (!isUndefOrEqual(Mask[i], Low))
3335       return false;
3336   return true;
3337 }
3338
3339 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3340 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3341 /// the second operand.
3342 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3343   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3344     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3345   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3346     return (Mask[0] < 2 && Mask[1] < 2);
3347   return false;
3348 }
3349
3350 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3351 /// is suitable for input to PSHUFHW.
3352 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3353   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3354     return false;
3355
3356   // Lower quadword copied in order or undef.
3357   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3358     return false;
3359
3360   // Upper quadword shuffled.
3361   for (unsigned i = 4; i != 8; ++i)
3362     if (!isUndefOrInRange(Mask[i], 4, 8))
3363       return false;
3364
3365   if (VT == MVT::v16i16) {
3366     // Lower quadword copied in order or undef.
3367     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3368       return false;
3369
3370     // Upper quadword shuffled.
3371     for (unsigned i = 12; i != 16; ++i)
3372       if (!isUndefOrInRange(Mask[i], 12, 16))
3373         return false;
3374   }
3375
3376   return true;
3377 }
3378
3379 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3380 /// is suitable for input to PSHUFLW.
3381 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3382   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3383     return false;
3384
3385   // Upper quadword copied in order.
3386   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3387     return false;
3388
3389   // Lower quadword shuffled.
3390   for (unsigned i = 0; i != 4; ++i)
3391     if (!isUndefOrInRange(Mask[i], 0, 4))
3392       return false;
3393
3394   if (VT == MVT::v16i16) {
3395     // Upper quadword copied in order.
3396     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3397       return false;
3398
3399     // Lower quadword shuffled.
3400     for (unsigned i = 8; i != 12; ++i)
3401       if (!isUndefOrInRange(Mask[i], 8, 12))
3402         return false;
3403   }
3404
3405   return true;
3406 }
3407
3408 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3409 /// is suitable for input to PALIGNR.
3410 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3411                           const X86Subtarget *Subtarget) {
3412   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3413       (VT.is256BitVector() && !Subtarget->hasInt256()))
3414     return false;
3415
3416   unsigned NumElts = VT.getVectorNumElements();
3417   unsigned NumLanes = VT.getSizeInBits()/128;
3418   unsigned NumLaneElts = NumElts/NumLanes;
3419
3420   // Do not handle 64-bit element shuffles with palignr.
3421   if (NumLaneElts == 2)
3422     return false;
3423
3424   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3425     unsigned i;
3426     for (i = 0; i != NumLaneElts; ++i) {
3427       if (Mask[i+l] >= 0)
3428         break;
3429     }
3430
3431     // Lane is all undef, go to next lane
3432     if (i == NumLaneElts)
3433       continue;
3434
3435     int Start = Mask[i+l];
3436
3437     // Make sure its in this lane in one of the sources
3438     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3439         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3440       return false;
3441
3442     // If not lane 0, then we must match lane 0
3443     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3444       return false;
3445
3446     // Correct second source to be contiguous with first source
3447     if (Start >= (int)NumElts)
3448       Start -= NumElts - NumLaneElts;
3449
3450     // Make sure we're shifting in the right direction.
3451     if (Start <= (int)(i+l))
3452       return false;
3453
3454     Start -= i;
3455
3456     // Check the rest of the elements to see if they are consecutive.
3457     for (++i; i != NumLaneElts; ++i) {
3458       int Idx = Mask[i+l];
3459
3460       // Make sure its in this lane
3461       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3462           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3463         return false;
3464
3465       // If not lane 0, then we must match lane 0
3466       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3467         return false;
3468
3469       if (Idx >= (int)NumElts)
3470         Idx -= NumElts - NumLaneElts;
3471
3472       if (!isUndefOrEqual(Idx, Start+i))
3473         return false;
3474
3475     }
3476   }
3477
3478   return true;
3479 }
3480
3481 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3482 /// the two vector operands have swapped position.
3483 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3484                                      unsigned NumElems) {
3485   for (unsigned i = 0; i != NumElems; ++i) {
3486     int idx = Mask[i];
3487     if (idx < 0)
3488       continue;
3489     else if (idx < (int)NumElems)
3490       Mask[i] = idx + NumElems;
3491     else
3492       Mask[i] = idx - NumElems;
3493   }
3494 }
3495
3496 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3497 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3498 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3499 /// reverse of what x86 shuffles want.
3500 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3501                         bool Commuted = false) {
3502   if (!HasFp256 && VT.is256BitVector())
3503     return false;
3504
3505   unsigned NumElems = VT.getVectorNumElements();
3506   unsigned NumLanes = VT.getSizeInBits()/128;
3507   unsigned NumLaneElems = NumElems/NumLanes;
3508
3509   if (NumLaneElems != 2 && NumLaneElems != 4)
3510     return false;
3511
3512   // VSHUFPSY divides the resulting vector into 4 chunks.
3513   // The sources are also splitted into 4 chunks, and each destination
3514   // chunk must come from a different source chunk.
3515   //
3516   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3517   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3518   //
3519   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3520   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3521   //
3522   // VSHUFPDY divides the resulting vector into 4 chunks.
3523   // The sources are also splitted into 4 chunks, and each destination
3524   // chunk must come from a different source chunk.
3525   //
3526   //  SRC1 =>      X3       X2       X1       X0
3527   //  SRC2 =>      Y3       Y2       Y1       Y0
3528   //
3529   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3530   //
3531   unsigned HalfLaneElems = NumLaneElems/2;
3532   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3533     for (unsigned i = 0; i != NumLaneElems; ++i) {
3534       int Idx = Mask[i+l];
3535       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3536       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3537         return false;
3538       // For VSHUFPSY, the mask of the second half must be the same as the
3539       // first but with the appropriate offsets. This works in the same way as
3540       // VPERMILPS works with masks.
3541       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3542         continue;
3543       if (!isUndefOrEqual(Idx, Mask[i]+l))
3544         return false;
3545     }
3546   }
3547
3548   return true;
3549 }
3550
3551 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3552 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3553 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3554   if (!VT.is128BitVector())
3555     return false;
3556
3557   unsigned NumElems = VT.getVectorNumElements();
3558
3559   if (NumElems != 4)
3560     return false;
3561
3562   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3563   return isUndefOrEqual(Mask[0], 6) &&
3564          isUndefOrEqual(Mask[1], 7) &&
3565          isUndefOrEqual(Mask[2], 2) &&
3566          isUndefOrEqual(Mask[3], 3);
3567 }
3568
3569 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3570 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3571 /// <2, 3, 2, 3>
3572 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3573   if (!VT.is128BitVector())
3574     return false;
3575
3576   unsigned NumElems = VT.getVectorNumElements();
3577
3578   if (NumElems != 4)
3579     return false;
3580
3581   return isUndefOrEqual(Mask[0], 2) &&
3582          isUndefOrEqual(Mask[1], 3) &&
3583          isUndefOrEqual(Mask[2], 2) &&
3584          isUndefOrEqual(Mask[3], 3);
3585 }
3586
3587 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3588 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3589 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3590   if (!VT.is128BitVector())
3591     return false;
3592
3593   unsigned NumElems = VT.getVectorNumElements();
3594
3595   if (NumElems != 2 && NumElems != 4)
3596     return false;
3597
3598   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3599     if (!isUndefOrEqual(Mask[i], i + NumElems))
3600       return false;
3601
3602   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3603     if (!isUndefOrEqual(Mask[i], i))
3604       return false;
3605
3606   return true;
3607 }
3608
3609 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3610 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3611 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3612   if (!VT.is128BitVector())
3613     return false;
3614
3615   unsigned NumElems = VT.getVectorNumElements();
3616
3617   if (NumElems != 2 && NumElems != 4)
3618     return false;
3619
3620   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3621     if (!isUndefOrEqual(Mask[i], i))
3622       return false;
3623
3624   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3625     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3626       return false;
3627
3628   return true;
3629 }
3630
3631 //
3632 // Some special combinations that can be optimized.
3633 //
3634 static
3635 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3636                                SelectionDAG &DAG) {
3637   MVT VT = SVOp->getValueType(0).getSimpleVT();
3638   DebugLoc dl = SVOp->getDebugLoc();
3639
3640   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3641     return SDValue();
3642
3643   ArrayRef<int> Mask = SVOp->getMask();
3644
3645   // These are the special masks that may be optimized.
3646   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3647   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3648   bool MatchEvenMask = true;
3649   bool MatchOddMask  = true;
3650   for (int i=0; i<8; ++i) {
3651     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3652       MatchEvenMask = false;
3653     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3654       MatchOddMask = false;
3655   }
3656
3657   if (!MatchEvenMask && !MatchOddMask)
3658     return SDValue();
3659
3660   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3661
3662   SDValue Op0 = SVOp->getOperand(0);
3663   SDValue Op1 = SVOp->getOperand(1);
3664
3665   if (MatchEvenMask) {
3666     // Shift the second operand right to 32 bits.
3667     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3668     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3669   } else {
3670     // Shift the first operand left to 32 bits.
3671     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3672     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3673   }
3674   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3675   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3676 }
3677
3678 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3679 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3680 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3681                          bool HasInt256, bool V2IsSplat = false) {
3682   unsigned NumElts = VT.getVectorNumElements();
3683
3684   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3685          "Unsupported vector type for unpckh");
3686
3687   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3688       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3689     return false;
3690
3691   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3692   // independently on 128-bit lanes.
3693   unsigned NumLanes = VT.getSizeInBits()/128;
3694   unsigned NumLaneElts = NumElts/NumLanes;
3695
3696   for (unsigned l = 0; l != NumLanes; ++l) {
3697     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3698          i != (l+1)*NumLaneElts;
3699          i += 2, ++j) {
3700       int BitI  = Mask[i];
3701       int BitI1 = Mask[i+1];
3702       if (!isUndefOrEqual(BitI, j))
3703         return false;
3704       if (V2IsSplat) {
3705         if (!isUndefOrEqual(BitI1, NumElts))
3706           return false;
3707       } else {
3708         if (!isUndefOrEqual(BitI1, j + NumElts))
3709           return false;
3710       }
3711     }
3712   }
3713
3714   return true;
3715 }
3716
3717 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3718 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3719 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3720                          bool HasInt256, bool V2IsSplat = false) {
3721   unsigned NumElts = VT.getVectorNumElements();
3722
3723   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3724          "Unsupported vector type for unpckh");
3725
3726   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3727       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3728     return false;
3729
3730   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3731   // independently on 128-bit lanes.
3732   unsigned NumLanes = VT.getSizeInBits()/128;
3733   unsigned NumLaneElts = NumElts/NumLanes;
3734
3735   for (unsigned l = 0; l != NumLanes; ++l) {
3736     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3737          i != (l+1)*NumLaneElts; i += 2, ++j) {
3738       int BitI  = Mask[i];
3739       int BitI1 = Mask[i+1];
3740       if (!isUndefOrEqual(BitI, j))
3741         return false;
3742       if (V2IsSplat) {
3743         if (isUndefOrEqual(BitI1, NumElts))
3744           return false;
3745       } else {
3746         if (!isUndefOrEqual(BitI1, j+NumElts))
3747           return false;
3748       }
3749     }
3750   }
3751   return true;
3752 }
3753
3754 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3755 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3756 /// <0, 0, 1, 1>
3757 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3758   unsigned NumElts = VT.getVectorNumElements();
3759   bool Is256BitVec = VT.is256BitVector();
3760
3761   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3762          "Unsupported vector type for unpckh");
3763
3764   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3765       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3766     return false;
3767
3768   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3769   // FIXME: Need a better way to get rid of this, there's no latency difference
3770   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3771   // the former later. We should also remove the "_undef" special mask.
3772   if (NumElts == 4 && Is256BitVec)
3773     return false;
3774
3775   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3776   // independently on 128-bit lanes.
3777   unsigned NumLanes = VT.getSizeInBits()/128;
3778   unsigned NumLaneElts = NumElts/NumLanes;
3779
3780   for (unsigned l = 0; l != NumLanes; ++l) {
3781     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3782          i != (l+1)*NumLaneElts;
3783          i += 2, ++j) {
3784       int BitI  = Mask[i];
3785       int BitI1 = Mask[i+1];
3786
3787       if (!isUndefOrEqual(BitI, j))
3788         return false;
3789       if (!isUndefOrEqual(BitI1, j))
3790         return false;
3791     }
3792   }
3793
3794   return true;
3795 }
3796
3797 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3798 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3799 /// <2, 2, 3, 3>
3800 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3801   unsigned NumElts = VT.getVectorNumElements();
3802
3803   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3804          "Unsupported vector type for unpckh");
3805
3806   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3807       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3808     return false;
3809
3810   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3811   // independently on 128-bit lanes.
3812   unsigned NumLanes = VT.getSizeInBits()/128;
3813   unsigned NumLaneElts = NumElts/NumLanes;
3814
3815   for (unsigned l = 0; l != NumLanes; ++l) {
3816     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3817          i != (l+1)*NumLaneElts; i += 2, ++j) {
3818       int BitI  = Mask[i];
3819       int BitI1 = Mask[i+1];
3820       if (!isUndefOrEqual(BitI, j))
3821         return false;
3822       if (!isUndefOrEqual(BitI1, j))
3823         return false;
3824     }
3825   }
3826   return true;
3827 }
3828
3829 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3830 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3831 /// MOVSD, and MOVD, i.e. setting the lowest element.
3832 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3833   if (VT.getVectorElementType().getSizeInBits() < 32)
3834     return false;
3835   if (!VT.is128BitVector())
3836     return false;
3837
3838   unsigned NumElts = VT.getVectorNumElements();
3839
3840   if (!isUndefOrEqual(Mask[0], NumElts))
3841     return false;
3842
3843   for (unsigned i = 1; i != NumElts; ++i)
3844     if (!isUndefOrEqual(Mask[i], i))
3845       return false;
3846
3847   return true;
3848 }
3849
3850 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3851 /// as permutations between 128-bit chunks or halves. As an example: this
3852 /// shuffle bellow:
3853 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3854 /// The first half comes from the second half of V1 and the second half from the
3855 /// the second half of V2.
3856 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3857   if (!HasFp256 || !VT.is256BitVector())
3858     return false;
3859
3860   // The shuffle result is divided into half A and half B. In total the two
3861   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3862   // B must come from C, D, E or F.
3863   unsigned HalfSize = VT.getVectorNumElements()/2;
3864   bool MatchA = false, MatchB = false;
3865
3866   // Check if A comes from one of C, D, E, F.
3867   for (unsigned Half = 0; Half != 4; ++Half) {
3868     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3869       MatchA = true;
3870       break;
3871     }
3872   }
3873
3874   // Check if B comes from one of C, D, E, F.
3875   for (unsigned Half = 0; Half != 4; ++Half) {
3876     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3877       MatchB = true;
3878       break;
3879     }
3880   }
3881
3882   return MatchA && MatchB;
3883 }
3884
3885 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3886 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3887 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3888   MVT VT = SVOp->getValueType(0).getSimpleVT();
3889
3890   unsigned HalfSize = VT.getVectorNumElements()/2;
3891
3892   unsigned FstHalf = 0, SndHalf = 0;
3893   for (unsigned i = 0; i < HalfSize; ++i) {
3894     if (SVOp->getMaskElt(i) > 0) {
3895       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3896       break;
3897     }
3898   }
3899   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3900     if (SVOp->getMaskElt(i) > 0) {
3901       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3902       break;
3903     }
3904   }
3905
3906   return (FstHalf | (SndHalf << 4));
3907 }
3908
3909 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3910 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3911 /// Note that VPERMIL mask matching is different depending whether theunderlying
3912 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3913 /// to the same elements of the low, but to the higher half of the source.
3914 /// In VPERMILPD the two lanes could be shuffled independently of each other
3915 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3916 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3917   if (!HasFp256)
3918     return false;
3919
3920   unsigned NumElts = VT.getVectorNumElements();
3921   // Only match 256-bit with 32/64-bit types
3922   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3923     return false;
3924
3925   unsigned NumLanes = VT.getSizeInBits()/128;
3926   unsigned LaneSize = NumElts/NumLanes;
3927   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3928     for (unsigned i = 0; i != LaneSize; ++i) {
3929       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3930         return false;
3931       if (NumElts != 8 || l == 0)
3932         continue;
3933       // VPERMILPS handling
3934       if (Mask[i] < 0)
3935         continue;
3936       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3937         return false;
3938     }
3939   }
3940
3941   return true;
3942 }
3943
3944 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3945 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3946 /// element of vector 2 and the other elements to come from vector 1 in order.
3947 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3948                                bool V2IsSplat = false, bool V2IsUndef = false) {
3949   if (!VT.is128BitVector())
3950     return false;
3951
3952   unsigned NumOps = VT.getVectorNumElements();
3953   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3954     return false;
3955
3956   if (!isUndefOrEqual(Mask[0], 0))
3957     return false;
3958
3959   for (unsigned i = 1; i != NumOps; ++i)
3960     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3961           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3962           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3963       return false;
3964
3965   return true;
3966 }
3967
3968 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3969 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3970 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3971 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3972                            const X86Subtarget *Subtarget) {
3973   if (!Subtarget->hasSSE3())
3974     return false;
3975
3976   unsigned NumElems = VT.getVectorNumElements();
3977
3978   if ((VT.is128BitVector() && NumElems != 4) ||
3979       (VT.is256BitVector() && NumElems != 8))
3980     return false;
3981
3982   // "i+1" is the value the indexed mask element must have
3983   for (unsigned i = 0; i != NumElems; i += 2)
3984     if (!isUndefOrEqual(Mask[i], i+1) ||
3985         !isUndefOrEqual(Mask[i+1], i+1))
3986       return false;
3987
3988   return true;
3989 }
3990
3991 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3992 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3993 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3994 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3995                            const X86Subtarget *Subtarget) {
3996   if (!Subtarget->hasSSE3())
3997     return false;
3998
3999   unsigned NumElems = VT.getVectorNumElements();
4000
4001   if ((VT.is128BitVector() && NumElems != 4) ||
4002       (VT.is256BitVector() && NumElems != 8))
4003     return false;
4004
4005   // "i" is the value the indexed mask element must have
4006   for (unsigned i = 0; i != NumElems; i += 2)
4007     if (!isUndefOrEqual(Mask[i], i) ||
4008         !isUndefOrEqual(Mask[i+1], i))
4009       return false;
4010
4011   return true;
4012 }
4013
4014 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4015 /// specifies a shuffle of elements that is suitable for input to 256-bit
4016 /// version of MOVDDUP.
4017 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4018   if (!HasFp256 || !VT.is256BitVector())
4019     return false;
4020
4021   unsigned NumElts = VT.getVectorNumElements();
4022   if (NumElts != 4)
4023     return false;
4024
4025   for (unsigned i = 0; i != NumElts/2; ++i)
4026     if (!isUndefOrEqual(Mask[i], 0))
4027       return false;
4028   for (unsigned i = NumElts/2; i != NumElts; ++i)
4029     if (!isUndefOrEqual(Mask[i], NumElts/2))
4030       return false;
4031   return true;
4032 }
4033
4034 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4035 /// specifies a shuffle of elements that is suitable for input to 128-bit
4036 /// version of MOVDDUP.
4037 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4038   if (!VT.is128BitVector())
4039     return false;
4040
4041   unsigned e = VT.getVectorNumElements() / 2;
4042   for (unsigned i = 0; i != e; ++i)
4043     if (!isUndefOrEqual(Mask[i], i))
4044       return false;
4045   for (unsigned i = 0; i != e; ++i)
4046     if (!isUndefOrEqual(Mask[e+i], i))
4047       return false;
4048   return true;
4049 }
4050
4051 /// isVEXTRACTF128Index - Return true if the specified
4052 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4053 /// suitable for input to VEXTRACTF128.
4054 bool X86::isVEXTRACTF128Index(SDNode *N) {
4055   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4056     return false;
4057
4058   // The index should be aligned on a 128-bit boundary.
4059   uint64_t Index =
4060     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4061
4062   MVT VT = N->getValueType(0).getSimpleVT();
4063   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4064   bool Result = (Index * ElSize) % 128 == 0;
4065
4066   return Result;
4067 }
4068
4069 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4070 /// operand specifies a subvector insert that is suitable for input to
4071 /// VINSERTF128.
4072 bool X86::isVINSERTF128Index(SDNode *N) {
4073   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4074     return false;
4075
4076   // The index should be aligned on a 128-bit boundary.
4077   uint64_t Index =
4078     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4079
4080   MVT VT = N->getValueType(0).getSimpleVT();
4081   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4082   bool Result = (Index * ElSize) % 128 == 0;
4083
4084   return Result;
4085 }
4086
4087 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4088 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4089 /// Handles 128-bit and 256-bit.
4090 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4091   MVT VT = N->getValueType(0).getSimpleVT();
4092
4093   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4094          "Unsupported vector type for PSHUF/SHUFP");
4095
4096   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4097   // independently on 128-bit lanes.
4098   unsigned NumElts = VT.getVectorNumElements();
4099   unsigned NumLanes = VT.getSizeInBits()/128;
4100   unsigned NumLaneElts = NumElts/NumLanes;
4101
4102   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4103          "Only supports 2 or 4 elements per lane");
4104
4105   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4106   unsigned Mask = 0;
4107   for (unsigned i = 0; i != NumElts; ++i) {
4108     int Elt = N->getMaskElt(i);
4109     if (Elt < 0) continue;
4110     Elt &= NumLaneElts - 1;
4111     unsigned ShAmt = (i << Shift) % 8;
4112     Mask |= Elt << ShAmt;
4113   }
4114
4115   return Mask;
4116 }
4117
4118 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4119 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4120 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4121   MVT VT = N->getValueType(0).getSimpleVT();
4122
4123   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4124          "Unsupported vector type for PSHUFHW");
4125
4126   unsigned NumElts = VT.getVectorNumElements();
4127
4128   unsigned Mask = 0;
4129   for (unsigned l = 0; l != NumElts; l += 8) {
4130     // 8 nodes per lane, but we only care about the last 4.
4131     for (unsigned i = 0; i < 4; ++i) {
4132       int Elt = N->getMaskElt(l+i+4);
4133       if (Elt < 0) continue;
4134       Elt &= 0x3; // only 2-bits.
4135       Mask |= Elt << (i * 2);
4136     }
4137   }
4138
4139   return Mask;
4140 }
4141
4142 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4143 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4144 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4145   MVT VT = N->getValueType(0).getSimpleVT();
4146
4147   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4148          "Unsupported vector type for PSHUFHW");
4149
4150   unsigned NumElts = VT.getVectorNumElements();
4151
4152   unsigned Mask = 0;
4153   for (unsigned l = 0; l != NumElts; l += 8) {
4154     // 8 nodes per lane, but we only care about the first 4.
4155     for (unsigned i = 0; i < 4; ++i) {
4156       int Elt = N->getMaskElt(l+i);
4157       if (Elt < 0) continue;
4158       Elt &= 0x3; // only 2-bits
4159       Mask |= Elt << (i * 2);
4160     }
4161   }
4162
4163   return Mask;
4164 }
4165
4166 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4167 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4168 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4169   MVT VT = SVOp->getValueType(0).getSimpleVT();
4170   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4171
4172   unsigned NumElts = VT.getVectorNumElements();
4173   unsigned NumLanes = VT.getSizeInBits()/128;
4174   unsigned NumLaneElts = NumElts/NumLanes;
4175
4176   int Val = 0;
4177   unsigned i;
4178   for (i = 0; i != NumElts; ++i) {
4179     Val = SVOp->getMaskElt(i);
4180     if (Val >= 0)
4181       break;
4182   }
4183   if (Val >= (int)NumElts)
4184     Val -= NumElts - NumLaneElts;
4185
4186   assert(Val - i > 0 && "PALIGNR imm should be positive");
4187   return (Val - i) * EltSize;
4188 }
4189
4190 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4191 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4192 /// instructions.
4193 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4194   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4195     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4196
4197   uint64_t Index =
4198     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4199
4200   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4201   MVT ElVT = VecVT.getVectorElementType();
4202
4203   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4204   return Index / NumElemsPerChunk;
4205 }
4206
4207 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4208 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4209 /// instructions.
4210 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4211   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4212     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4213
4214   uint64_t Index =
4215     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4216
4217   MVT VecVT = N->getValueType(0).getSimpleVT();
4218   MVT ElVT = VecVT.getVectorElementType();
4219
4220   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4221   return Index / NumElemsPerChunk;
4222 }
4223
4224 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4225 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4226 /// Handles 256-bit.
4227 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4228   MVT VT = N->getValueType(0).getSimpleVT();
4229
4230   unsigned NumElts = VT.getVectorNumElements();
4231
4232   assert((VT.is256BitVector() && NumElts == 4) &&
4233          "Unsupported vector type for VPERMQ/VPERMPD");
4234
4235   unsigned Mask = 0;
4236   for (unsigned i = 0; i != NumElts; ++i) {
4237     int Elt = N->getMaskElt(i);
4238     if (Elt < 0)
4239       continue;
4240     Mask |= Elt << (i*2);
4241   }
4242
4243   return Mask;
4244 }
4245 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4246 /// constant +0.0.
4247 bool X86::isZeroNode(SDValue Elt) {
4248   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4249     return CN->isNullValue();
4250   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4251     return CFP->getValueAPF().isPosZero();
4252   return false;
4253 }
4254
4255 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4256 /// their permute mask.
4257 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4258                                     SelectionDAG &DAG) {
4259   MVT VT = SVOp->getValueType(0).getSimpleVT();
4260   unsigned NumElems = VT.getVectorNumElements();
4261   SmallVector<int, 8> MaskVec;
4262
4263   for (unsigned i = 0; i != NumElems; ++i) {
4264     int Idx = SVOp->getMaskElt(i);
4265     if (Idx >= 0) {
4266       if (Idx < (int)NumElems)
4267         Idx += NumElems;
4268       else
4269         Idx -= NumElems;
4270     }
4271     MaskVec.push_back(Idx);
4272   }
4273   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4274                               SVOp->getOperand(0), &MaskVec[0]);
4275 }
4276
4277 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4278 /// match movhlps. The lower half elements should come from upper half of
4279 /// V1 (and in order), and the upper half elements should come from the upper
4280 /// half of V2 (and in order).
4281 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4282   if (!VT.is128BitVector())
4283     return false;
4284   if (VT.getVectorNumElements() != 4)
4285     return false;
4286   for (unsigned i = 0, e = 2; i != e; ++i)
4287     if (!isUndefOrEqual(Mask[i], i+2))
4288       return false;
4289   for (unsigned i = 2; i != 4; ++i)
4290     if (!isUndefOrEqual(Mask[i], i+4))
4291       return false;
4292   return true;
4293 }
4294
4295 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4296 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4297 /// required.
4298 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4299   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4300     return false;
4301   N = N->getOperand(0).getNode();
4302   if (!ISD::isNON_EXTLoad(N))
4303     return false;
4304   if (LD)
4305     *LD = cast<LoadSDNode>(N);
4306   return true;
4307 }
4308
4309 // Test whether the given value is a vector value which will be legalized
4310 // into a load.
4311 static bool WillBeConstantPoolLoad(SDNode *N) {
4312   if (N->getOpcode() != ISD::BUILD_VECTOR)
4313     return false;
4314
4315   // Check for any non-constant elements.
4316   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4317     switch (N->getOperand(i).getNode()->getOpcode()) {
4318     case ISD::UNDEF:
4319     case ISD::ConstantFP:
4320     case ISD::Constant:
4321       break;
4322     default:
4323       return false;
4324     }
4325
4326   // Vectors of all-zeros and all-ones are materialized with special
4327   // instructions rather than being loaded.
4328   return !ISD::isBuildVectorAllZeros(N) &&
4329          !ISD::isBuildVectorAllOnes(N);
4330 }
4331
4332 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4333 /// match movlp{s|d}. The lower half elements should come from lower half of
4334 /// V1 (and in order), and the upper half elements should come from the upper
4335 /// half of V2 (and in order). And since V1 will become the source of the
4336 /// MOVLP, it must be either a vector load or a scalar load to vector.
4337 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4338                                ArrayRef<int> Mask, EVT VT) {
4339   if (!VT.is128BitVector())
4340     return false;
4341
4342   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4343     return false;
4344   // Is V2 is a vector load, don't do this transformation. We will try to use
4345   // load folding shufps op.
4346   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4347     return false;
4348
4349   unsigned NumElems = VT.getVectorNumElements();
4350
4351   if (NumElems != 2 && NumElems != 4)
4352     return false;
4353   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4354     if (!isUndefOrEqual(Mask[i], i))
4355       return false;
4356   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4357     if (!isUndefOrEqual(Mask[i], i+NumElems))
4358       return false;
4359   return true;
4360 }
4361
4362 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4363 /// all the same.
4364 static bool isSplatVector(SDNode *N) {
4365   if (N->getOpcode() != ISD::BUILD_VECTOR)
4366     return false;
4367
4368   SDValue SplatValue = N->getOperand(0);
4369   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4370     if (N->getOperand(i) != SplatValue)
4371       return false;
4372   return true;
4373 }
4374
4375 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4376 /// to an zero vector.
4377 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4378 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4379   SDValue V1 = N->getOperand(0);
4380   SDValue V2 = N->getOperand(1);
4381   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4382   for (unsigned i = 0; i != NumElems; ++i) {
4383     int Idx = N->getMaskElt(i);
4384     if (Idx >= (int)NumElems) {
4385       unsigned Opc = V2.getOpcode();
4386       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4387         continue;
4388       if (Opc != ISD::BUILD_VECTOR ||
4389           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4390         return false;
4391     } else if (Idx >= 0) {
4392       unsigned Opc = V1.getOpcode();
4393       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4394         continue;
4395       if (Opc != ISD::BUILD_VECTOR ||
4396           !X86::isZeroNode(V1.getOperand(Idx)))
4397         return false;
4398     }
4399   }
4400   return true;
4401 }
4402
4403 /// getZeroVector - Returns a vector of specified type with all zero elements.
4404 ///
4405 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4406                              SelectionDAG &DAG, DebugLoc dl) {
4407   assert(VT.isVector() && "Expected a vector type");
4408
4409   // Always build SSE zero vectors as <4 x i32> bitcasted
4410   // to their dest type. This ensures they get CSE'd.
4411   SDValue Vec;
4412   if (VT.is128BitVector()) {  // SSE
4413     if (Subtarget->hasSSE2()) {  // SSE2
4414       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4415       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4416     } else { // SSE1
4417       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4418       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4419     }
4420   } else if (VT.is256BitVector()) { // AVX
4421     if (Subtarget->hasInt256()) { // AVX2
4422       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4423       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4424       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4425                         array_lengthof(Ops));
4426     } else {
4427       // 256-bit logic and arithmetic instructions in AVX are all
4428       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4429       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4430       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4431       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4432                         array_lengthof(Ops));
4433     }
4434   } else
4435     llvm_unreachable("Unexpected vector type");
4436
4437   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4438 }
4439
4440 /// getOnesVector - Returns a vector of specified type with all bits set.
4441 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4442 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4443 /// Then bitcast to their original type, ensuring they get CSE'd.
4444 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4445                              DebugLoc dl) {
4446   assert(VT.isVector() && "Expected a vector type");
4447
4448   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4449   SDValue Vec;
4450   if (VT.is256BitVector()) {
4451     if (HasInt256) { // AVX2
4452       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4453       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4454                         array_lengthof(Ops));
4455     } else { // AVX
4456       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4457       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4458     }
4459   } else if (VT.is128BitVector()) {
4460     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4461   } else
4462     llvm_unreachable("Unexpected vector type");
4463
4464   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4465 }
4466
4467 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4468 /// that point to V2 points to its first element.
4469 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4470   for (unsigned i = 0; i != NumElems; ++i) {
4471     if (Mask[i] > (int)NumElems) {
4472       Mask[i] = NumElems;
4473     }
4474   }
4475 }
4476
4477 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4478 /// operation of specified width.
4479 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4480                        SDValue V2) {
4481   unsigned NumElems = VT.getVectorNumElements();
4482   SmallVector<int, 8> Mask;
4483   Mask.push_back(NumElems);
4484   for (unsigned i = 1; i != NumElems; ++i)
4485     Mask.push_back(i);
4486   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4487 }
4488
4489 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4490 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4491                           SDValue V2) {
4492   unsigned NumElems = VT.getVectorNumElements();
4493   SmallVector<int, 8> Mask;
4494   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4495     Mask.push_back(i);
4496     Mask.push_back(i + NumElems);
4497   }
4498   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4499 }
4500
4501 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4502 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4503                           SDValue V2) {
4504   unsigned NumElems = VT.getVectorNumElements();
4505   SmallVector<int, 8> Mask;
4506   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4507     Mask.push_back(i + Half);
4508     Mask.push_back(i + NumElems + Half);
4509   }
4510   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4511 }
4512
4513 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4514 // a generic shuffle instruction because the target has no such instructions.
4515 // Generate shuffles which repeat i16 and i8 several times until they can be
4516 // represented by v4f32 and then be manipulated by target suported shuffles.
4517 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4518   EVT VT = V.getValueType();
4519   int NumElems = VT.getVectorNumElements();
4520   DebugLoc dl = V.getDebugLoc();
4521
4522   while (NumElems > 4) {
4523     if (EltNo < NumElems/2) {
4524       V = getUnpackl(DAG, dl, VT, V, V);
4525     } else {
4526       V = getUnpackh(DAG, dl, VT, V, V);
4527       EltNo -= NumElems/2;
4528     }
4529     NumElems >>= 1;
4530   }
4531   return V;
4532 }
4533
4534 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4535 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4536   EVT VT = V.getValueType();
4537   DebugLoc dl = V.getDebugLoc();
4538
4539   if (VT.is128BitVector()) {
4540     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4541     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4542     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4543                              &SplatMask[0]);
4544   } else if (VT.is256BitVector()) {
4545     // To use VPERMILPS to splat scalars, the second half of indicies must
4546     // refer to the higher part, which is a duplication of the lower one,
4547     // because VPERMILPS can only handle in-lane permutations.
4548     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4549                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4550
4551     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4552     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4553                              &SplatMask[0]);
4554   } else
4555     llvm_unreachable("Vector size not supported");
4556
4557   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4558 }
4559
4560 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4561 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4562   EVT SrcVT = SV->getValueType(0);
4563   SDValue V1 = SV->getOperand(0);
4564   DebugLoc dl = SV->getDebugLoc();
4565
4566   int EltNo = SV->getSplatIndex();
4567   int NumElems = SrcVT.getVectorNumElements();
4568   bool Is256BitVec = SrcVT.is256BitVector();
4569
4570   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4571          "Unknown how to promote splat for type");
4572
4573   // Extract the 128-bit part containing the splat element and update
4574   // the splat element index when it refers to the higher register.
4575   if (Is256BitVec) {
4576     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4577     if (EltNo >= NumElems/2)
4578       EltNo -= NumElems/2;
4579   }
4580
4581   // All i16 and i8 vector types can't be used directly by a generic shuffle
4582   // instruction because the target has no such instruction. Generate shuffles
4583   // which repeat i16 and i8 several times until they fit in i32, and then can
4584   // be manipulated by target suported shuffles.
4585   EVT EltVT = SrcVT.getVectorElementType();
4586   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4587     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4588
4589   // Recreate the 256-bit vector and place the same 128-bit vector
4590   // into the low and high part. This is necessary because we want
4591   // to use VPERM* to shuffle the vectors
4592   if (Is256BitVec) {
4593     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4594   }
4595
4596   return getLegalSplat(DAG, V1, EltNo);
4597 }
4598
4599 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4600 /// vector of zero or undef vector.  This produces a shuffle where the low
4601 /// element of V2 is swizzled into the zero/undef vector, landing at element
4602 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4603 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4604                                            bool IsZero,
4605                                            const X86Subtarget *Subtarget,
4606                                            SelectionDAG &DAG) {
4607   EVT VT = V2.getValueType();
4608   SDValue V1 = IsZero
4609     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4610   unsigned NumElems = VT.getVectorNumElements();
4611   SmallVector<int, 16> MaskVec;
4612   for (unsigned i = 0; i != NumElems; ++i)
4613     // If this is the insertion idx, put the low elt of V2 here.
4614     MaskVec.push_back(i == Idx ? NumElems : i);
4615   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4616 }
4617
4618 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4619 /// target specific opcode. Returns true if the Mask could be calculated.
4620 /// Sets IsUnary to true if only uses one source.
4621 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4622                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4623   unsigned NumElems = VT.getVectorNumElements();
4624   SDValue ImmN;
4625
4626   IsUnary = false;
4627   switch(N->getOpcode()) {
4628   case X86ISD::SHUFP:
4629     ImmN = N->getOperand(N->getNumOperands()-1);
4630     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4631     break;
4632   case X86ISD::UNPCKH:
4633     DecodeUNPCKHMask(VT, Mask);
4634     break;
4635   case X86ISD::UNPCKL:
4636     DecodeUNPCKLMask(VT, Mask);
4637     break;
4638   case X86ISD::MOVHLPS:
4639     DecodeMOVHLPSMask(NumElems, Mask);
4640     break;
4641   case X86ISD::MOVLHPS:
4642     DecodeMOVLHPSMask(NumElems, Mask);
4643     break;
4644   case X86ISD::PALIGNR:
4645     ImmN = N->getOperand(N->getNumOperands()-1);
4646     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4647     break;
4648   case X86ISD::PSHUFD:
4649   case X86ISD::VPERMILP:
4650     ImmN = N->getOperand(N->getNumOperands()-1);
4651     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4652     IsUnary = true;
4653     break;
4654   case X86ISD::PSHUFHW:
4655     ImmN = N->getOperand(N->getNumOperands()-1);
4656     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4657     IsUnary = true;
4658     break;
4659   case X86ISD::PSHUFLW:
4660     ImmN = N->getOperand(N->getNumOperands()-1);
4661     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4662     IsUnary = true;
4663     break;
4664   case X86ISD::VPERMI:
4665     ImmN = N->getOperand(N->getNumOperands()-1);
4666     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4667     IsUnary = true;
4668     break;
4669   case X86ISD::MOVSS:
4670   case X86ISD::MOVSD: {
4671     // The index 0 always comes from the first element of the second source,
4672     // this is why MOVSS and MOVSD are used in the first place. The other
4673     // elements come from the other positions of the first source vector
4674     Mask.push_back(NumElems);
4675     for (unsigned i = 1; i != NumElems; ++i) {
4676       Mask.push_back(i);
4677     }
4678     break;
4679   }
4680   case X86ISD::VPERM2X128:
4681     ImmN = N->getOperand(N->getNumOperands()-1);
4682     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4683     if (Mask.empty()) return false;
4684     break;
4685   case X86ISD::MOVDDUP:
4686   case X86ISD::MOVLHPD:
4687   case X86ISD::MOVLPD:
4688   case X86ISD::MOVLPS:
4689   case X86ISD::MOVSHDUP:
4690   case X86ISD::MOVSLDUP:
4691     // Not yet implemented
4692     return false;
4693   default: llvm_unreachable("unknown target shuffle node");
4694   }
4695
4696   return true;
4697 }
4698
4699 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4700 /// element of the result of the vector shuffle.
4701 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4702                                    unsigned Depth) {
4703   if (Depth == 6)
4704     return SDValue();  // Limit search depth.
4705
4706   SDValue V = SDValue(N, 0);
4707   EVT VT = V.getValueType();
4708   unsigned Opcode = V.getOpcode();
4709
4710   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4711   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4712     int Elt = SV->getMaskElt(Index);
4713
4714     if (Elt < 0)
4715       return DAG.getUNDEF(VT.getVectorElementType());
4716
4717     unsigned NumElems = VT.getVectorNumElements();
4718     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4719                                          : SV->getOperand(1);
4720     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4721   }
4722
4723   // Recurse into target specific vector shuffles to find scalars.
4724   if (isTargetShuffle(Opcode)) {
4725     MVT ShufVT = V.getValueType().getSimpleVT();
4726     unsigned NumElems = ShufVT.getVectorNumElements();
4727     SmallVector<int, 16> ShuffleMask;
4728     bool IsUnary;
4729
4730     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4731       return SDValue();
4732
4733     int Elt = ShuffleMask[Index];
4734     if (Elt < 0)
4735       return DAG.getUNDEF(ShufVT.getVectorElementType());
4736
4737     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4738                                          : N->getOperand(1);
4739     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4740                                Depth+1);
4741   }
4742
4743   // Actual nodes that may contain scalar elements
4744   if (Opcode == ISD::BITCAST) {
4745     V = V.getOperand(0);
4746     EVT SrcVT = V.getValueType();
4747     unsigned NumElems = VT.getVectorNumElements();
4748
4749     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4750       return SDValue();
4751   }
4752
4753   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4754     return (Index == 0) ? V.getOperand(0)
4755                         : DAG.getUNDEF(VT.getVectorElementType());
4756
4757   if (V.getOpcode() == ISD::BUILD_VECTOR)
4758     return V.getOperand(Index);
4759
4760   return SDValue();
4761 }
4762
4763 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4764 /// shuffle operation which come from a consecutively from a zero. The
4765 /// search can start in two different directions, from left or right.
4766 static
4767 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4768                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4769   unsigned i;
4770   for (i = 0; i != NumElems; ++i) {
4771     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4772     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4773     if (!(Elt.getNode() &&
4774          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4775       break;
4776   }
4777
4778   return i;
4779 }
4780
4781 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4782 /// correspond consecutively to elements from one of the vector operands,
4783 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4784 static
4785 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4786                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4787                               unsigned NumElems, unsigned &OpNum) {
4788   bool SeenV1 = false;
4789   bool SeenV2 = false;
4790
4791   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4792     int Idx = SVOp->getMaskElt(i);
4793     // Ignore undef indicies
4794     if (Idx < 0)
4795       continue;
4796
4797     if (Idx < (int)NumElems)
4798       SeenV1 = true;
4799     else
4800       SeenV2 = true;
4801
4802     // Only accept consecutive elements from the same vector
4803     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4804       return false;
4805   }
4806
4807   OpNum = SeenV1 ? 0 : 1;
4808   return true;
4809 }
4810
4811 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4812 /// logical left shift of a vector.
4813 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4814                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4815   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4816   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4817               false /* check zeros from right */, DAG);
4818   unsigned OpSrc;
4819
4820   if (!NumZeros)
4821     return false;
4822
4823   // Considering the elements in the mask that are not consecutive zeros,
4824   // check if they consecutively come from only one of the source vectors.
4825   //
4826   //               V1 = {X, A, B, C}     0
4827   //                         \  \  \    /
4828   //   vector_shuffle V1, V2 <1, 2, 3, X>
4829   //
4830   if (!isShuffleMaskConsecutive(SVOp,
4831             0,                   // Mask Start Index
4832             NumElems-NumZeros,   // Mask End Index(exclusive)
4833             NumZeros,            // Where to start looking in the src vector
4834             NumElems,            // Number of elements in vector
4835             OpSrc))              // Which source operand ?
4836     return false;
4837
4838   isLeft = false;
4839   ShAmt = NumZeros;
4840   ShVal = SVOp->getOperand(OpSrc);
4841   return true;
4842 }
4843
4844 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4845 /// logical left shift of a vector.
4846 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4847                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4848   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4849   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4850               true /* check zeros from left */, DAG);
4851   unsigned OpSrc;
4852
4853   if (!NumZeros)
4854     return false;
4855
4856   // Considering the elements in the mask that are not consecutive zeros,
4857   // check if they consecutively come from only one of the source vectors.
4858   //
4859   //                           0    { A, B, X, X } = V2
4860   //                          / \    /  /
4861   //   vector_shuffle V1, V2 <X, X, 4, 5>
4862   //
4863   if (!isShuffleMaskConsecutive(SVOp,
4864             NumZeros,     // Mask Start Index
4865             NumElems,     // Mask End Index(exclusive)
4866             0,            // Where to start looking in the src vector
4867             NumElems,     // Number of elements in vector
4868             OpSrc))       // Which source operand ?
4869     return false;
4870
4871   isLeft = true;
4872   ShAmt = NumZeros;
4873   ShVal = SVOp->getOperand(OpSrc);
4874   return true;
4875 }
4876
4877 /// isVectorShift - Returns true if the shuffle can be implemented as a
4878 /// logical left or right shift of a vector.
4879 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4880                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4881   // Although the logic below support any bitwidth size, there are no
4882   // shift instructions which handle more than 128-bit vectors.
4883   if (!SVOp->getValueType(0).is128BitVector())
4884     return false;
4885
4886   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4887       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4888     return true;
4889
4890   return false;
4891 }
4892
4893 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4894 ///
4895 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4896                                        unsigned NumNonZero, unsigned NumZero,
4897                                        SelectionDAG &DAG,
4898                                        const X86Subtarget* Subtarget,
4899                                        const TargetLowering &TLI) {
4900   if (NumNonZero > 8)
4901     return SDValue();
4902
4903   DebugLoc dl = Op.getDebugLoc();
4904   SDValue V(0, 0);
4905   bool First = true;
4906   for (unsigned i = 0; i < 16; ++i) {
4907     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4908     if (ThisIsNonZero && First) {
4909       if (NumZero)
4910         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4911       else
4912         V = DAG.getUNDEF(MVT::v8i16);
4913       First = false;
4914     }
4915
4916     if ((i & 1) != 0) {
4917       SDValue ThisElt(0, 0), LastElt(0, 0);
4918       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4919       if (LastIsNonZero) {
4920         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4921                               MVT::i16, Op.getOperand(i-1));
4922       }
4923       if (ThisIsNonZero) {
4924         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4925         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4926                               ThisElt, DAG.getConstant(8, MVT::i8));
4927         if (LastIsNonZero)
4928           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4929       } else
4930         ThisElt = LastElt;
4931
4932       if (ThisElt.getNode())
4933         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4934                         DAG.getIntPtrConstant(i/2));
4935     }
4936   }
4937
4938   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4939 }
4940
4941 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4942 ///
4943 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4944                                      unsigned NumNonZero, unsigned NumZero,
4945                                      SelectionDAG &DAG,
4946                                      const X86Subtarget* Subtarget,
4947                                      const TargetLowering &TLI) {
4948   if (NumNonZero > 4)
4949     return SDValue();
4950
4951   DebugLoc dl = Op.getDebugLoc();
4952   SDValue V(0, 0);
4953   bool First = true;
4954   for (unsigned i = 0; i < 8; ++i) {
4955     bool isNonZero = (NonZeros & (1 << i)) != 0;
4956     if (isNonZero) {
4957       if (First) {
4958         if (NumZero)
4959           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4960         else
4961           V = DAG.getUNDEF(MVT::v8i16);
4962         First = false;
4963       }
4964       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4965                       MVT::v8i16, V, Op.getOperand(i),
4966                       DAG.getIntPtrConstant(i));
4967     }
4968   }
4969
4970   return V;
4971 }
4972
4973 /// getVShift - Return a vector logical shift node.
4974 ///
4975 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4976                          unsigned NumBits, SelectionDAG &DAG,
4977                          const TargetLowering &TLI, DebugLoc dl) {
4978   assert(VT.is128BitVector() && "Unknown type for VShift");
4979   EVT ShVT = MVT::v2i64;
4980   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4981   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4982   return DAG.getNode(ISD::BITCAST, dl, VT,
4983                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4984                              DAG.getConstant(NumBits,
4985                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4986 }
4987
4988 SDValue
4989 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4990                                           SelectionDAG &DAG) const {
4991
4992   // Check if the scalar load can be widened into a vector load. And if
4993   // the address is "base + cst" see if the cst can be "absorbed" into
4994   // the shuffle mask.
4995   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4996     SDValue Ptr = LD->getBasePtr();
4997     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4998       return SDValue();
4999     EVT PVT = LD->getValueType(0);
5000     if (PVT != MVT::i32 && PVT != MVT::f32)
5001       return SDValue();
5002
5003     int FI = -1;
5004     int64_t Offset = 0;
5005     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5006       FI = FINode->getIndex();
5007       Offset = 0;
5008     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5009                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5010       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5011       Offset = Ptr.getConstantOperandVal(1);
5012       Ptr = Ptr.getOperand(0);
5013     } else {
5014       return SDValue();
5015     }
5016
5017     // FIXME: 256-bit vector instructions don't require a strict alignment,
5018     // improve this code to support it better.
5019     unsigned RequiredAlign = VT.getSizeInBits()/8;
5020     SDValue Chain = LD->getChain();
5021     // Make sure the stack object alignment is at least 16 or 32.
5022     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5023     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5024       if (MFI->isFixedObjectIndex(FI)) {
5025         // Can't change the alignment. FIXME: It's possible to compute
5026         // the exact stack offset and reference FI + adjust offset instead.
5027         // If someone *really* cares about this. That's the way to implement it.
5028         return SDValue();
5029       } else {
5030         MFI->setObjectAlignment(FI, RequiredAlign);
5031       }
5032     }
5033
5034     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5035     // Ptr + (Offset & ~15).
5036     if (Offset < 0)
5037       return SDValue();
5038     if ((Offset % RequiredAlign) & 3)
5039       return SDValue();
5040     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5041     if (StartOffset)
5042       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5043                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5044
5045     int EltNo = (Offset - StartOffset) >> 2;
5046     unsigned NumElems = VT.getVectorNumElements();
5047
5048     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5049     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5050                              LD->getPointerInfo().getWithOffset(StartOffset),
5051                              false, false, false, 0);
5052
5053     SmallVector<int, 8> Mask;
5054     for (unsigned i = 0; i != NumElems; ++i)
5055       Mask.push_back(EltNo);
5056
5057     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5058   }
5059
5060   return SDValue();
5061 }
5062
5063 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5064 /// vector of type 'VT', see if the elements can be replaced by a single large
5065 /// load which has the same value as a build_vector whose operands are 'elts'.
5066 ///
5067 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5068 ///
5069 /// FIXME: we'd also like to handle the case where the last elements are zero
5070 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5071 /// There's even a handy isZeroNode for that purpose.
5072 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5073                                         DebugLoc &DL, SelectionDAG &DAG) {
5074   EVT EltVT = VT.getVectorElementType();
5075   unsigned NumElems = Elts.size();
5076
5077   LoadSDNode *LDBase = NULL;
5078   unsigned LastLoadedElt = -1U;
5079
5080   // For each element in the initializer, see if we've found a load or an undef.
5081   // If we don't find an initial load element, or later load elements are
5082   // non-consecutive, bail out.
5083   for (unsigned i = 0; i < NumElems; ++i) {
5084     SDValue Elt = Elts[i];
5085
5086     if (!Elt.getNode() ||
5087         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5088       return SDValue();
5089     if (!LDBase) {
5090       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5091         return SDValue();
5092       LDBase = cast<LoadSDNode>(Elt.getNode());
5093       LastLoadedElt = i;
5094       continue;
5095     }
5096     if (Elt.getOpcode() == ISD::UNDEF)
5097       continue;
5098
5099     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5100     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5101       return SDValue();
5102     LastLoadedElt = i;
5103   }
5104
5105   // If we have found an entire vector of loads and undefs, then return a large
5106   // load of the entire vector width starting at the base pointer.  If we found
5107   // consecutive loads for the low half, generate a vzext_load node.
5108   if (LastLoadedElt == NumElems - 1) {
5109     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5110       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5111                          LDBase->getPointerInfo(),
5112                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5113                          LDBase->isInvariant(), 0);
5114     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5115                        LDBase->getPointerInfo(),
5116                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5117                        LDBase->isInvariant(), LDBase->getAlignment());
5118   }
5119   if (NumElems == 4 && LastLoadedElt == 1 &&
5120       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5121     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5122     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5123     SDValue ResNode =
5124         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5125                                 array_lengthof(Ops), MVT::i64,
5126                                 LDBase->getPointerInfo(),
5127                                 LDBase->getAlignment(),
5128                                 false/*isVolatile*/, true/*ReadMem*/,
5129                                 false/*WriteMem*/);
5130
5131     // Make sure the newly-created LOAD is in the same position as LDBase in
5132     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5133     // update uses of LDBase's output chain to use the TokenFactor.
5134     if (LDBase->hasAnyUseOfValue(1)) {
5135       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5136                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5137       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5138       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5139                              SDValue(ResNode.getNode(), 1));
5140     }
5141
5142     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5143   }
5144   return SDValue();
5145 }
5146
5147 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5148 /// to generate a splat value for the following cases:
5149 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5150 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5151 /// a scalar load, or a constant.
5152 /// The VBROADCAST node is returned when a pattern is found,
5153 /// or SDValue() otherwise.
5154 SDValue
5155 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5156   if (!Subtarget->hasFp256())
5157     return SDValue();
5158
5159   MVT VT = Op.getValueType().getSimpleVT();
5160   DebugLoc dl = Op.getDebugLoc();
5161
5162   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5163          "Unsupported vector type for broadcast.");
5164
5165   SDValue Ld;
5166   bool ConstSplatVal;
5167
5168   switch (Op.getOpcode()) {
5169     default:
5170       // Unknown pattern found.
5171       return SDValue();
5172
5173     case ISD::BUILD_VECTOR: {
5174       // The BUILD_VECTOR node must be a splat.
5175       if (!isSplatVector(Op.getNode()))
5176         return SDValue();
5177
5178       Ld = Op.getOperand(0);
5179       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5180                      Ld.getOpcode() == ISD::ConstantFP);
5181
5182       // The suspected load node has several users. Make sure that all
5183       // of its users are from the BUILD_VECTOR node.
5184       // Constants may have multiple users.
5185       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5186         return SDValue();
5187       break;
5188     }
5189
5190     case ISD::VECTOR_SHUFFLE: {
5191       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5192
5193       // Shuffles must have a splat mask where the first element is
5194       // broadcasted.
5195       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5196         return SDValue();
5197
5198       SDValue Sc = Op.getOperand(0);
5199       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5200           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5201
5202         if (!Subtarget->hasInt256())
5203           return SDValue();
5204
5205         // Use the register form of the broadcast instruction available on AVX2.
5206         if (VT.is256BitVector())
5207           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5208         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5209       }
5210
5211       Ld = Sc.getOperand(0);
5212       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5213                        Ld.getOpcode() == ISD::ConstantFP);
5214
5215       // The scalar_to_vector node and the suspected
5216       // load node must have exactly one user.
5217       // Constants may have multiple users.
5218       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5219         return SDValue();
5220       break;
5221     }
5222   }
5223
5224   bool Is256 = VT.is256BitVector();
5225
5226   // Handle the broadcasting a single constant scalar from the constant pool
5227   // into a vector. On Sandybridge it is still better to load a constant vector
5228   // from the constant pool and not to broadcast it from a scalar.
5229   if (ConstSplatVal && Subtarget->hasInt256()) {
5230     EVT CVT = Ld.getValueType();
5231     assert(!CVT.isVector() && "Must not broadcast a vector type");
5232     unsigned ScalarSize = CVT.getSizeInBits();
5233
5234     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5235       const Constant *C = 0;
5236       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5237         C = CI->getConstantIntValue();
5238       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5239         C = CF->getConstantFPValue();
5240
5241       assert(C && "Invalid constant type");
5242
5243       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5244       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5245       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5246                        MachinePointerInfo::getConstantPool(),
5247                        false, false, false, Alignment);
5248
5249       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5250     }
5251   }
5252
5253   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5254   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5255
5256   // Handle AVX2 in-register broadcasts.
5257   if (!IsLoad && Subtarget->hasInt256() &&
5258       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5259     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5260
5261   // The scalar source must be a normal load.
5262   if (!IsLoad)
5263     return SDValue();
5264
5265   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5266     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5267
5268   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5269   // double since there is no vbroadcastsd xmm
5270   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5271     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5272       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5273   }
5274
5275   // Unsupported broadcast.
5276   return SDValue();
5277 }
5278
5279 SDValue
5280 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5281   EVT VT = Op.getValueType();
5282
5283   // Skip if insert_vec_elt is not supported.
5284   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5285     return SDValue();
5286
5287   DebugLoc DL = Op.getDebugLoc();
5288   unsigned NumElems = Op.getNumOperands();
5289
5290   SDValue VecIn1;
5291   SDValue VecIn2;
5292   SmallVector<unsigned, 4> InsertIndices;
5293   SmallVector<int, 8> Mask(NumElems, -1);
5294
5295   for (unsigned i = 0; i != NumElems; ++i) {
5296     unsigned Opc = Op.getOperand(i).getOpcode();
5297
5298     if (Opc == ISD::UNDEF)
5299       continue;
5300
5301     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5302       // Quit if more than 1 elements need inserting.
5303       if (InsertIndices.size() > 1)
5304         return SDValue();
5305
5306       InsertIndices.push_back(i);
5307       continue;
5308     }
5309
5310     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5311     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5312
5313     // Quit if extracted from vector of different type.
5314     if (ExtractedFromVec.getValueType() != VT)
5315       return SDValue();
5316
5317     // Quit if non-constant index.
5318     if (!isa<ConstantSDNode>(ExtIdx))
5319       return SDValue();
5320
5321     if (VecIn1.getNode() == 0)
5322       VecIn1 = ExtractedFromVec;
5323     else if (VecIn1 != ExtractedFromVec) {
5324       if (VecIn2.getNode() == 0)
5325         VecIn2 = ExtractedFromVec;
5326       else if (VecIn2 != ExtractedFromVec)
5327         // Quit if more than 2 vectors to shuffle
5328         return SDValue();
5329     }
5330
5331     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5332
5333     if (ExtractedFromVec == VecIn1)
5334       Mask[i] = Idx;
5335     else if (ExtractedFromVec == VecIn2)
5336       Mask[i] = Idx + NumElems;
5337   }
5338
5339   if (VecIn1.getNode() == 0)
5340     return SDValue();
5341
5342   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5343   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5344   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5345     unsigned Idx = InsertIndices[i];
5346     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5347                      DAG.getIntPtrConstant(Idx));
5348   }
5349
5350   return NV;
5351 }
5352
5353 SDValue
5354 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5355   DebugLoc dl = Op.getDebugLoc();
5356
5357   MVT VT = Op.getValueType().getSimpleVT();
5358   MVT ExtVT = VT.getVectorElementType();
5359   unsigned NumElems = Op.getNumOperands();
5360
5361   // Vectors containing all zeros can be matched by pxor and xorps later
5362   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5363     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5364     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5365     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5366       return Op;
5367
5368     return getZeroVector(VT, Subtarget, DAG, dl);
5369   }
5370
5371   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5372   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5373   // vpcmpeqd on 256-bit vectors.
5374   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5375     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5376       return Op;
5377
5378     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5379   }
5380
5381   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5382   if (Broadcast.getNode())
5383     return Broadcast;
5384
5385   unsigned EVTBits = ExtVT.getSizeInBits();
5386
5387   unsigned NumZero  = 0;
5388   unsigned NumNonZero = 0;
5389   unsigned NonZeros = 0;
5390   bool IsAllConstants = true;
5391   SmallSet<SDValue, 8> Values;
5392   for (unsigned i = 0; i < NumElems; ++i) {
5393     SDValue Elt = Op.getOperand(i);
5394     if (Elt.getOpcode() == ISD::UNDEF)
5395       continue;
5396     Values.insert(Elt);
5397     if (Elt.getOpcode() != ISD::Constant &&
5398         Elt.getOpcode() != ISD::ConstantFP)
5399       IsAllConstants = false;
5400     if (X86::isZeroNode(Elt))
5401       NumZero++;
5402     else {
5403       NonZeros |= (1 << i);
5404       NumNonZero++;
5405     }
5406   }
5407
5408   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5409   if (NumNonZero == 0)
5410     return DAG.getUNDEF(VT);
5411
5412   // Special case for single non-zero, non-undef, element.
5413   if (NumNonZero == 1) {
5414     unsigned Idx = CountTrailingZeros_32(NonZeros);
5415     SDValue Item = Op.getOperand(Idx);
5416
5417     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5418     // the value are obviously zero, truncate the value to i32 and do the
5419     // insertion that way.  Only do this if the value is non-constant or if the
5420     // value is a constant being inserted into element 0.  It is cheaper to do
5421     // a constant pool load than it is to do a movd + shuffle.
5422     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5423         (!IsAllConstants || Idx == 0)) {
5424       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5425         // Handle SSE only.
5426         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5427         EVT VecVT = MVT::v4i32;
5428         unsigned VecElts = 4;
5429
5430         // Truncate the value (which may itself be a constant) to i32, and
5431         // convert it to a vector with movd (S2V+shuffle to zero extend).
5432         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5433         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5434         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5435
5436         // Now we have our 32-bit value zero extended in the low element of
5437         // a vector.  If Idx != 0, swizzle it into place.
5438         if (Idx != 0) {
5439           SmallVector<int, 4> Mask;
5440           Mask.push_back(Idx);
5441           for (unsigned i = 1; i != VecElts; ++i)
5442             Mask.push_back(i);
5443           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5444                                       &Mask[0]);
5445         }
5446         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5447       }
5448     }
5449
5450     // If we have a constant or non-constant insertion into the low element of
5451     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5452     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5453     // depending on what the source datatype is.
5454     if (Idx == 0) {
5455       if (NumZero == 0)
5456         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5457
5458       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5459           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5460         if (VT.is256BitVector()) {
5461           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5462           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5463                              Item, DAG.getIntPtrConstant(0));
5464         }
5465         assert(VT.is128BitVector() && "Expected an SSE value type!");
5466         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5467         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5468         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5469       }
5470
5471       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5472         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5473         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5474         if (VT.is256BitVector()) {
5475           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5476           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5477         } else {
5478           assert(VT.is128BitVector() && "Expected an SSE value type!");
5479           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5480         }
5481         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5482       }
5483     }
5484
5485     // Is it a vector logical left shift?
5486     if (NumElems == 2 && Idx == 1 &&
5487         X86::isZeroNode(Op.getOperand(0)) &&
5488         !X86::isZeroNode(Op.getOperand(1))) {
5489       unsigned NumBits = VT.getSizeInBits();
5490       return getVShift(true, VT,
5491                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5492                                    VT, Op.getOperand(1)),
5493                        NumBits/2, DAG, *this, dl);
5494     }
5495
5496     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5497       return SDValue();
5498
5499     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5500     // is a non-constant being inserted into an element other than the low one,
5501     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5502     // movd/movss) to move this into the low element, then shuffle it into
5503     // place.
5504     if (EVTBits == 32) {
5505       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5506
5507       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5508       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5509       SmallVector<int, 8> MaskVec;
5510       for (unsigned i = 0; i != NumElems; ++i)
5511         MaskVec.push_back(i == Idx ? 0 : 1);
5512       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5513     }
5514   }
5515
5516   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5517   if (Values.size() == 1) {
5518     if (EVTBits == 32) {
5519       // Instead of a shuffle like this:
5520       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5521       // Check if it's possible to issue this instead.
5522       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5523       unsigned Idx = CountTrailingZeros_32(NonZeros);
5524       SDValue Item = Op.getOperand(Idx);
5525       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5526         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5527     }
5528     return SDValue();
5529   }
5530
5531   // A vector full of immediates; various special cases are already
5532   // handled, so this is best done with a single constant-pool load.
5533   if (IsAllConstants)
5534     return SDValue();
5535
5536   // For AVX-length vectors, build the individual 128-bit pieces and use
5537   // shuffles to put them in place.
5538   if (VT.is256BitVector()) {
5539     SmallVector<SDValue, 32> V;
5540     for (unsigned i = 0; i != NumElems; ++i)
5541       V.push_back(Op.getOperand(i));
5542
5543     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5544
5545     // Build both the lower and upper subvector.
5546     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5547     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5548                                 NumElems/2);
5549
5550     // Recreate the wider vector with the lower and upper part.
5551     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5552   }
5553
5554   // Let legalizer expand 2-wide build_vectors.
5555   if (EVTBits == 64) {
5556     if (NumNonZero == 1) {
5557       // One half is zero or undef.
5558       unsigned Idx = CountTrailingZeros_32(NonZeros);
5559       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5560                                  Op.getOperand(Idx));
5561       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5562     }
5563     return SDValue();
5564   }
5565
5566   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5567   if (EVTBits == 8 && NumElems == 16) {
5568     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5569                                         Subtarget, *this);
5570     if (V.getNode()) return V;
5571   }
5572
5573   if (EVTBits == 16 && NumElems == 8) {
5574     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5575                                       Subtarget, *this);
5576     if (V.getNode()) return V;
5577   }
5578
5579   // If element VT is == 32 bits, turn it into a number of shuffles.
5580   SmallVector<SDValue, 8> V(NumElems);
5581   if (NumElems == 4 && NumZero > 0) {
5582     for (unsigned i = 0; i < 4; ++i) {
5583       bool isZero = !(NonZeros & (1 << i));
5584       if (isZero)
5585         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5586       else
5587         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5588     }
5589
5590     for (unsigned i = 0; i < 2; ++i) {
5591       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5592         default: break;
5593         case 0:
5594           V[i] = V[i*2];  // Must be a zero vector.
5595           break;
5596         case 1:
5597           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5598           break;
5599         case 2:
5600           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5601           break;
5602         case 3:
5603           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5604           break;
5605       }
5606     }
5607
5608     bool Reverse1 = (NonZeros & 0x3) == 2;
5609     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5610     int MaskVec[] = {
5611       Reverse1 ? 1 : 0,
5612       Reverse1 ? 0 : 1,
5613       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5614       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5615     };
5616     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5617   }
5618
5619   if (Values.size() > 1 && VT.is128BitVector()) {
5620     // Check for a build vector of consecutive loads.
5621     for (unsigned i = 0; i < NumElems; ++i)
5622       V[i] = Op.getOperand(i);
5623
5624     // Check for elements which are consecutive loads.
5625     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5626     if (LD.getNode())
5627       return LD;
5628
5629     // Check for a build vector from mostly shuffle plus few inserting.
5630     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5631     if (Sh.getNode())
5632       return Sh;
5633
5634     // For SSE 4.1, use insertps to put the high elements into the low element.
5635     if (getSubtarget()->hasSSE41()) {
5636       SDValue Result;
5637       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5638         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5639       else
5640         Result = DAG.getUNDEF(VT);
5641
5642       for (unsigned i = 1; i < NumElems; ++i) {
5643         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5644         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5645                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5646       }
5647       return Result;
5648     }
5649
5650     // Otherwise, expand into a number of unpckl*, start by extending each of
5651     // our (non-undef) elements to the full vector width with the element in the
5652     // bottom slot of the vector (which generates no code for SSE).
5653     for (unsigned i = 0; i < NumElems; ++i) {
5654       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5655         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5656       else
5657         V[i] = DAG.getUNDEF(VT);
5658     }
5659
5660     // Next, we iteratively mix elements, e.g. for v4f32:
5661     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5662     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5663     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5664     unsigned EltStride = NumElems >> 1;
5665     while (EltStride != 0) {
5666       for (unsigned i = 0; i < EltStride; ++i) {
5667         // If V[i+EltStride] is undef and this is the first round of mixing,
5668         // then it is safe to just drop this shuffle: V[i] is already in the
5669         // right place, the one element (since it's the first round) being
5670         // inserted as undef can be dropped.  This isn't safe for successive
5671         // rounds because they will permute elements within both vectors.
5672         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5673             EltStride == NumElems/2)
5674           continue;
5675
5676         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5677       }
5678       EltStride >>= 1;
5679     }
5680     return V[0];
5681   }
5682   return SDValue();
5683 }
5684
5685 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5686 // to create 256-bit vectors from two other 128-bit ones.
5687 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5688   DebugLoc dl = Op.getDebugLoc();
5689   MVT ResVT = Op.getValueType().getSimpleVT();
5690
5691   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5692
5693   SDValue V1 = Op.getOperand(0);
5694   SDValue V2 = Op.getOperand(1);
5695   unsigned NumElems = ResVT.getVectorNumElements();
5696
5697   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5698 }
5699
5700 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5701   assert(Op.getNumOperands() == 2);
5702
5703   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5704   // from two other 128-bit ones.
5705   return LowerAVXCONCAT_VECTORS(Op, DAG);
5706 }
5707
5708 // Try to lower a shuffle node into a simple blend instruction.
5709 static SDValue
5710 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5711                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5712   SDValue V1 = SVOp->getOperand(0);
5713   SDValue V2 = SVOp->getOperand(1);
5714   DebugLoc dl = SVOp->getDebugLoc();
5715   MVT VT = SVOp->getValueType(0).getSimpleVT();
5716   MVT EltVT = VT.getVectorElementType();
5717   unsigned NumElems = VT.getVectorNumElements();
5718
5719   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5720     return SDValue();
5721   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5722     return SDValue();
5723
5724   // Check the mask for BLEND and build the value.
5725   unsigned MaskValue = 0;
5726   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5727   unsigned NumLanes = (NumElems-1)/8 + 1;
5728   unsigned NumElemsInLane = NumElems / NumLanes;
5729
5730   // Blend for v16i16 should be symetric for the both lanes.
5731   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5732
5733     int SndLaneEltIdx = (NumLanes == 2) ?
5734       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5735     int EltIdx = SVOp->getMaskElt(i);
5736
5737     if ((EltIdx < 0 || EltIdx == (int)i) &&
5738         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5739       continue;
5740
5741     if (((unsigned)EltIdx == (i + NumElems)) &&
5742         (SndLaneEltIdx < 0 ||
5743          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5744       MaskValue |= (1<<i);
5745     else
5746       return SDValue();
5747   }
5748
5749   // Convert i32 vectors to floating point if it is not AVX2.
5750   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5751   MVT BlendVT = VT;
5752   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5753     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5754                                NumElems);
5755     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5756     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5757   }
5758
5759   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5760                             DAG.getConstant(MaskValue, MVT::i32));
5761   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5762 }
5763
5764 // v8i16 shuffles - Prefer shuffles in the following order:
5765 // 1. [all]   pshuflw, pshufhw, optional move
5766 // 2. [ssse3] 1 x pshufb
5767 // 3. [ssse3] 2 x pshufb + 1 x por
5768 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5769 static SDValue
5770 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5771                          SelectionDAG &DAG) {
5772   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5773   SDValue V1 = SVOp->getOperand(0);
5774   SDValue V2 = SVOp->getOperand(1);
5775   DebugLoc dl = SVOp->getDebugLoc();
5776   SmallVector<int, 8> MaskVals;
5777
5778   // Determine if more than 1 of the words in each of the low and high quadwords
5779   // of the result come from the same quadword of one of the two inputs.  Undef
5780   // mask values count as coming from any quadword, for better codegen.
5781   unsigned LoQuad[] = { 0, 0, 0, 0 };
5782   unsigned HiQuad[] = { 0, 0, 0, 0 };
5783   std::bitset<4> InputQuads;
5784   for (unsigned i = 0; i < 8; ++i) {
5785     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5786     int EltIdx = SVOp->getMaskElt(i);
5787     MaskVals.push_back(EltIdx);
5788     if (EltIdx < 0) {
5789       ++Quad[0];
5790       ++Quad[1];
5791       ++Quad[2];
5792       ++Quad[3];
5793       continue;
5794     }
5795     ++Quad[EltIdx / 4];
5796     InputQuads.set(EltIdx / 4);
5797   }
5798
5799   int BestLoQuad = -1;
5800   unsigned MaxQuad = 1;
5801   for (unsigned i = 0; i < 4; ++i) {
5802     if (LoQuad[i] > MaxQuad) {
5803       BestLoQuad = i;
5804       MaxQuad = LoQuad[i];
5805     }
5806   }
5807
5808   int BestHiQuad = -1;
5809   MaxQuad = 1;
5810   for (unsigned i = 0; i < 4; ++i) {
5811     if (HiQuad[i] > MaxQuad) {
5812       BestHiQuad = i;
5813       MaxQuad = HiQuad[i];
5814     }
5815   }
5816
5817   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5818   // of the two input vectors, shuffle them into one input vector so only a
5819   // single pshufb instruction is necessary. If There are more than 2 input
5820   // quads, disable the next transformation since it does not help SSSE3.
5821   bool V1Used = InputQuads[0] || InputQuads[1];
5822   bool V2Used = InputQuads[2] || InputQuads[3];
5823   if (Subtarget->hasSSSE3()) {
5824     if (InputQuads.count() == 2 && V1Used && V2Used) {
5825       BestLoQuad = InputQuads[0] ? 0 : 1;
5826       BestHiQuad = InputQuads[2] ? 2 : 3;
5827     }
5828     if (InputQuads.count() > 2) {
5829       BestLoQuad = -1;
5830       BestHiQuad = -1;
5831     }
5832   }
5833
5834   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5835   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5836   // words from all 4 input quadwords.
5837   SDValue NewV;
5838   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5839     int MaskV[] = {
5840       BestLoQuad < 0 ? 0 : BestLoQuad,
5841       BestHiQuad < 0 ? 1 : BestHiQuad
5842     };
5843     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5844                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5845                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5846     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5847
5848     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5849     // source words for the shuffle, to aid later transformations.
5850     bool AllWordsInNewV = true;
5851     bool InOrder[2] = { true, true };
5852     for (unsigned i = 0; i != 8; ++i) {
5853       int idx = MaskVals[i];
5854       if (idx != (int)i)
5855         InOrder[i/4] = false;
5856       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5857         continue;
5858       AllWordsInNewV = false;
5859       break;
5860     }
5861
5862     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5863     if (AllWordsInNewV) {
5864       for (int i = 0; i != 8; ++i) {
5865         int idx = MaskVals[i];
5866         if (idx < 0)
5867           continue;
5868         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5869         if ((idx != i) && idx < 4)
5870           pshufhw = false;
5871         if ((idx != i) && idx > 3)
5872           pshuflw = false;
5873       }
5874       V1 = NewV;
5875       V2Used = false;
5876       BestLoQuad = 0;
5877       BestHiQuad = 1;
5878     }
5879
5880     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5881     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5882     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5883       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5884       unsigned TargetMask = 0;
5885       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5886                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5887       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5888       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5889                              getShufflePSHUFLWImmediate(SVOp);
5890       V1 = NewV.getOperand(0);
5891       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5892     }
5893   }
5894
5895   // Promote splats to a larger type which usually leads to more efficient code.
5896   // FIXME: Is this true if pshufb is available?
5897   if (SVOp->isSplat())
5898     return PromoteSplat(SVOp, DAG);
5899
5900   // If we have SSSE3, and all words of the result are from 1 input vector,
5901   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5902   // is present, fall back to case 4.
5903   if (Subtarget->hasSSSE3()) {
5904     SmallVector<SDValue,16> pshufbMask;
5905
5906     // If we have elements from both input vectors, set the high bit of the
5907     // shuffle mask element to zero out elements that come from V2 in the V1
5908     // mask, and elements that come from V1 in the V2 mask, so that the two
5909     // results can be OR'd together.
5910     bool TwoInputs = V1Used && V2Used;
5911     for (unsigned i = 0; i != 8; ++i) {
5912       int EltIdx = MaskVals[i] * 2;
5913       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5914       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5915       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5916       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5917     }
5918     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5919     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5920                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5921                                  MVT::v16i8, &pshufbMask[0], 16));
5922     if (!TwoInputs)
5923       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5924
5925     // Calculate the shuffle mask for the second input, shuffle it, and
5926     // OR it with the first shuffled input.
5927     pshufbMask.clear();
5928     for (unsigned i = 0; i != 8; ++i) {
5929       int EltIdx = MaskVals[i] * 2;
5930       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5931       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5932       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5933       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5934     }
5935     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5936     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5937                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5938                                  MVT::v16i8, &pshufbMask[0], 16));
5939     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5940     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5941   }
5942
5943   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5944   // and update MaskVals with new element order.
5945   std::bitset<8> InOrder;
5946   if (BestLoQuad >= 0) {
5947     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5948     for (int i = 0; i != 4; ++i) {
5949       int idx = MaskVals[i];
5950       if (idx < 0) {
5951         InOrder.set(i);
5952       } else if ((idx / 4) == BestLoQuad) {
5953         MaskV[i] = idx & 3;
5954         InOrder.set(i);
5955       }
5956     }
5957     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5958                                 &MaskV[0]);
5959
5960     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5961       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5962       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5963                                   NewV.getOperand(0),
5964                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5965     }
5966   }
5967
5968   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5969   // and update MaskVals with the new element order.
5970   if (BestHiQuad >= 0) {
5971     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5972     for (unsigned i = 4; i != 8; ++i) {
5973       int idx = MaskVals[i];
5974       if (idx < 0) {
5975         InOrder.set(i);
5976       } else if ((idx / 4) == BestHiQuad) {
5977         MaskV[i] = (idx & 3) + 4;
5978         InOrder.set(i);
5979       }
5980     }
5981     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5982                                 &MaskV[0]);
5983
5984     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5985       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5986       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5987                                   NewV.getOperand(0),
5988                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5989     }
5990   }
5991
5992   // In case BestHi & BestLo were both -1, which means each quadword has a word
5993   // from each of the four input quadwords, calculate the InOrder bitvector now
5994   // before falling through to the insert/extract cleanup.
5995   if (BestLoQuad == -1 && BestHiQuad == -1) {
5996     NewV = V1;
5997     for (int i = 0; i != 8; ++i)
5998       if (MaskVals[i] < 0 || MaskVals[i] == i)
5999         InOrder.set(i);
6000   }
6001
6002   // The other elements are put in the right place using pextrw and pinsrw.
6003   for (unsigned i = 0; i != 8; ++i) {
6004     if (InOrder[i])
6005       continue;
6006     int EltIdx = MaskVals[i];
6007     if (EltIdx < 0)
6008       continue;
6009     SDValue ExtOp = (EltIdx < 8) ?
6010       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6011                   DAG.getIntPtrConstant(EltIdx)) :
6012       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6013                   DAG.getIntPtrConstant(EltIdx - 8));
6014     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6015                        DAG.getIntPtrConstant(i));
6016   }
6017   return NewV;
6018 }
6019
6020 // v16i8 shuffles - Prefer shuffles in the following order:
6021 // 1. [ssse3] 1 x pshufb
6022 // 2. [ssse3] 2 x pshufb + 1 x por
6023 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6024 static
6025 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6026                                  SelectionDAG &DAG,
6027                                  const X86TargetLowering &TLI) {
6028   SDValue V1 = SVOp->getOperand(0);
6029   SDValue V2 = SVOp->getOperand(1);
6030   DebugLoc dl = SVOp->getDebugLoc();
6031   ArrayRef<int> MaskVals = SVOp->getMask();
6032
6033   // Promote splats to a larger type which usually leads to more efficient code.
6034   // FIXME: Is this true if pshufb is available?
6035   if (SVOp->isSplat())
6036     return PromoteSplat(SVOp, DAG);
6037
6038   // If we have SSSE3, case 1 is generated when all result bytes come from
6039   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6040   // present, fall back to case 3.
6041
6042   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6043   if (TLI.getSubtarget()->hasSSSE3()) {
6044     SmallVector<SDValue,16> pshufbMask;
6045
6046     // If all result elements are from one input vector, then only translate
6047     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6048     //
6049     // Otherwise, we have elements from both input vectors, and must zero out
6050     // elements that come from V2 in the first mask, and V1 in the second mask
6051     // so that we can OR them together.
6052     for (unsigned i = 0; i != 16; ++i) {
6053       int EltIdx = MaskVals[i];
6054       if (EltIdx < 0 || EltIdx >= 16)
6055         EltIdx = 0x80;
6056       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6057     }
6058     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6059                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6060                                  MVT::v16i8, &pshufbMask[0], 16));
6061
6062     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6063     // the 2nd operand if it's undefined or zero.
6064     if (V2.getOpcode() == ISD::UNDEF ||
6065         ISD::isBuildVectorAllZeros(V2.getNode()))
6066       return V1;
6067
6068     // Calculate the shuffle mask for the second input, shuffle it, and
6069     // OR it with the first shuffled input.
6070     pshufbMask.clear();
6071     for (unsigned i = 0; i != 16; ++i) {
6072       int EltIdx = MaskVals[i];
6073       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6074       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6075     }
6076     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6077                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6078                                  MVT::v16i8, &pshufbMask[0], 16));
6079     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6080   }
6081
6082   // No SSSE3 - Calculate in place words and then fix all out of place words
6083   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6084   // the 16 different words that comprise the two doublequadword input vectors.
6085   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6086   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6087   SDValue NewV = V1;
6088   for (int i = 0; i != 8; ++i) {
6089     int Elt0 = MaskVals[i*2];
6090     int Elt1 = MaskVals[i*2+1];
6091
6092     // This word of the result is all undef, skip it.
6093     if (Elt0 < 0 && Elt1 < 0)
6094       continue;
6095
6096     // This word of the result is already in the correct place, skip it.
6097     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6098       continue;
6099
6100     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6101     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6102     SDValue InsElt;
6103
6104     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6105     // using a single extract together, load it and store it.
6106     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6107       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6108                            DAG.getIntPtrConstant(Elt1 / 2));
6109       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6110                         DAG.getIntPtrConstant(i));
6111       continue;
6112     }
6113
6114     // If Elt1 is defined, extract it from the appropriate source.  If the
6115     // source byte is not also odd, shift the extracted word left 8 bits
6116     // otherwise clear the bottom 8 bits if we need to do an or.
6117     if (Elt1 >= 0) {
6118       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6119                            DAG.getIntPtrConstant(Elt1 / 2));
6120       if ((Elt1 & 1) == 0)
6121         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6122                              DAG.getConstant(8,
6123                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6124       else if (Elt0 >= 0)
6125         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6126                              DAG.getConstant(0xFF00, MVT::i16));
6127     }
6128     // If Elt0 is defined, extract it from the appropriate source.  If the
6129     // source byte is not also even, shift the extracted word right 8 bits. If
6130     // Elt1 was also defined, OR the extracted values together before
6131     // inserting them in the result.
6132     if (Elt0 >= 0) {
6133       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6134                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6135       if ((Elt0 & 1) != 0)
6136         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6137                               DAG.getConstant(8,
6138                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6139       else if (Elt1 >= 0)
6140         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6141                              DAG.getConstant(0x00FF, MVT::i16));
6142       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6143                          : InsElt0;
6144     }
6145     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6146                        DAG.getIntPtrConstant(i));
6147   }
6148   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6149 }
6150
6151 // v32i8 shuffles - Translate to VPSHUFB if possible.
6152 static
6153 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6154                                  const X86Subtarget *Subtarget,
6155                                  SelectionDAG &DAG) {
6156   MVT VT = SVOp->getValueType(0).getSimpleVT();
6157   SDValue V1 = SVOp->getOperand(0);
6158   SDValue V2 = SVOp->getOperand(1);
6159   DebugLoc dl = SVOp->getDebugLoc();
6160   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6161
6162   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6163   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6164   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6165
6166   // VPSHUFB may be generated if
6167   // (1) one of input vector is undefined or zeroinitializer.
6168   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6169   // And (2) the mask indexes don't cross the 128-bit lane.
6170   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6171       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6172     return SDValue();
6173
6174   if (V1IsAllZero && !V2IsAllZero) {
6175     CommuteVectorShuffleMask(MaskVals, 32);
6176     V1 = V2;
6177   }
6178   SmallVector<SDValue, 32> pshufbMask;
6179   for (unsigned i = 0; i != 32; i++) {
6180     int EltIdx = MaskVals[i];
6181     if (EltIdx < 0 || EltIdx >= 32)
6182       EltIdx = 0x80;
6183     else {
6184       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6185         // Cross lane is not allowed.
6186         return SDValue();
6187       EltIdx &= 0xf;
6188     }
6189     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6190   }
6191   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6192                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6193                                   MVT::v32i8, &pshufbMask[0], 32));
6194 }
6195
6196 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6197 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6198 /// done when every pair / quad of shuffle mask elements point to elements in
6199 /// the right sequence. e.g.
6200 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6201 static
6202 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6203                                  SelectionDAG &DAG) {
6204   MVT VT = SVOp->getValueType(0).getSimpleVT();
6205   DebugLoc dl = SVOp->getDebugLoc();
6206   unsigned NumElems = VT.getVectorNumElements();
6207   MVT NewVT;
6208   unsigned Scale;
6209   switch (VT.SimpleTy) {
6210   default: llvm_unreachable("Unexpected!");
6211   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6212   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6213   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6214   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6215   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6216   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6217   }
6218
6219   SmallVector<int, 8> MaskVec;
6220   for (unsigned i = 0; i != NumElems; i += Scale) {
6221     int StartIdx = -1;
6222     for (unsigned j = 0; j != Scale; ++j) {
6223       int EltIdx = SVOp->getMaskElt(i+j);
6224       if (EltIdx < 0)
6225         continue;
6226       if (StartIdx < 0)
6227         StartIdx = (EltIdx / Scale);
6228       if (EltIdx != (int)(StartIdx*Scale + j))
6229         return SDValue();
6230     }
6231     MaskVec.push_back(StartIdx);
6232   }
6233
6234   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6235   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6236   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6237 }
6238
6239 /// getVZextMovL - Return a zero-extending vector move low node.
6240 ///
6241 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6242                             SDValue SrcOp, SelectionDAG &DAG,
6243                             const X86Subtarget *Subtarget, DebugLoc dl) {
6244   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6245     LoadSDNode *LD = NULL;
6246     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6247       LD = dyn_cast<LoadSDNode>(SrcOp);
6248     if (!LD) {
6249       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6250       // instead.
6251       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6252       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6253           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6254           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6255           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6256         // PR2108
6257         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6258         return DAG.getNode(ISD::BITCAST, dl, VT,
6259                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6260                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6261                                                    OpVT,
6262                                                    SrcOp.getOperand(0)
6263                                                           .getOperand(0))));
6264       }
6265     }
6266   }
6267
6268   return DAG.getNode(ISD::BITCAST, dl, VT,
6269                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6270                                  DAG.getNode(ISD::BITCAST, dl,
6271                                              OpVT, SrcOp)));
6272 }
6273
6274 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6275 /// which could not be matched by any known target speficic shuffle
6276 static SDValue
6277 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6278
6279   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6280   if (NewOp.getNode())
6281     return NewOp;
6282
6283   MVT VT = SVOp->getValueType(0).getSimpleVT();
6284
6285   unsigned NumElems = VT.getVectorNumElements();
6286   unsigned NumLaneElems = NumElems / 2;
6287
6288   DebugLoc dl = SVOp->getDebugLoc();
6289   MVT EltVT = VT.getVectorElementType();
6290   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6291   SDValue Output[2];
6292
6293   SmallVector<int, 16> Mask;
6294   for (unsigned l = 0; l < 2; ++l) {
6295     // Build a shuffle mask for the output, discovering on the fly which
6296     // input vectors to use as shuffle operands (recorded in InputUsed).
6297     // If building a suitable shuffle vector proves too hard, then bail
6298     // out with UseBuildVector set.
6299     bool UseBuildVector = false;
6300     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6301     unsigned LaneStart = l * NumLaneElems;
6302     for (unsigned i = 0; i != NumLaneElems; ++i) {
6303       // The mask element.  This indexes into the input.
6304       int Idx = SVOp->getMaskElt(i+LaneStart);
6305       if (Idx < 0) {
6306         // the mask element does not index into any input vector.
6307         Mask.push_back(-1);
6308         continue;
6309       }
6310
6311       // The input vector this mask element indexes into.
6312       int Input = Idx / NumLaneElems;
6313
6314       // Turn the index into an offset from the start of the input vector.
6315       Idx -= Input * NumLaneElems;
6316
6317       // Find or create a shuffle vector operand to hold this input.
6318       unsigned OpNo;
6319       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6320         if (InputUsed[OpNo] == Input)
6321           // This input vector is already an operand.
6322           break;
6323         if (InputUsed[OpNo] < 0) {
6324           // Create a new operand for this input vector.
6325           InputUsed[OpNo] = Input;
6326           break;
6327         }
6328       }
6329
6330       if (OpNo >= array_lengthof(InputUsed)) {
6331         // More than two input vectors used!  Give up on trying to create a
6332         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6333         UseBuildVector = true;
6334         break;
6335       }
6336
6337       // Add the mask index for the new shuffle vector.
6338       Mask.push_back(Idx + OpNo * NumLaneElems);
6339     }
6340
6341     if (UseBuildVector) {
6342       SmallVector<SDValue, 16> SVOps;
6343       for (unsigned i = 0; i != NumLaneElems; ++i) {
6344         // The mask element.  This indexes into the input.
6345         int Idx = SVOp->getMaskElt(i+LaneStart);
6346         if (Idx < 0) {
6347           SVOps.push_back(DAG.getUNDEF(EltVT));
6348           continue;
6349         }
6350
6351         // The input vector this mask element indexes into.
6352         int Input = Idx / NumElems;
6353
6354         // Turn the index into an offset from the start of the input vector.
6355         Idx -= Input * NumElems;
6356
6357         // Extract the vector element by hand.
6358         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6359                                     SVOp->getOperand(Input),
6360                                     DAG.getIntPtrConstant(Idx)));
6361       }
6362
6363       // Construct the output using a BUILD_VECTOR.
6364       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6365                               SVOps.size());
6366     } else if (InputUsed[0] < 0) {
6367       // No input vectors were used! The result is undefined.
6368       Output[l] = DAG.getUNDEF(NVT);
6369     } else {
6370       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6371                                         (InputUsed[0] % 2) * NumLaneElems,
6372                                         DAG, dl);
6373       // If only one input was used, use an undefined vector for the other.
6374       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6375         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6376                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6377       // At least one input vector was used. Create a new shuffle vector.
6378       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6379     }
6380
6381     Mask.clear();
6382   }
6383
6384   // Concatenate the result back
6385   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6386 }
6387
6388 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6389 /// 4 elements, and match them with several different shuffle types.
6390 static SDValue
6391 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6392   SDValue V1 = SVOp->getOperand(0);
6393   SDValue V2 = SVOp->getOperand(1);
6394   DebugLoc dl = SVOp->getDebugLoc();
6395   MVT VT = SVOp->getValueType(0).getSimpleVT();
6396
6397   assert(VT.is128BitVector() && "Unsupported vector size");
6398
6399   std::pair<int, int> Locs[4];
6400   int Mask1[] = { -1, -1, -1, -1 };
6401   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6402
6403   unsigned NumHi = 0;
6404   unsigned NumLo = 0;
6405   for (unsigned i = 0; i != 4; ++i) {
6406     int Idx = PermMask[i];
6407     if (Idx < 0) {
6408       Locs[i] = std::make_pair(-1, -1);
6409     } else {
6410       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6411       if (Idx < 4) {
6412         Locs[i] = std::make_pair(0, NumLo);
6413         Mask1[NumLo] = Idx;
6414         NumLo++;
6415       } else {
6416         Locs[i] = std::make_pair(1, NumHi);
6417         if (2+NumHi < 4)
6418           Mask1[2+NumHi] = Idx;
6419         NumHi++;
6420       }
6421     }
6422   }
6423
6424   if (NumLo <= 2 && NumHi <= 2) {
6425     // If no more than two elements come from either vector. This can be
6426     // implemented with two shuffles. First shuffle gather the elements.
6427     // The second shuffle, which takes the first shuffle as both of its
6428     // vector operands, put the elements into the right order.
6429     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6430
6431     int Mask2[] = { -1, -1, -1, -1 };
6432
6433     for (unsigned i = 0; i != 4; ++i)
6434       if (Locs[i].first != -1) {
6435         unsigned Idx = (i < 2) ? 0 : 4;
6436         Idx += Locs[i].first * 2 + Locs[i].second;
6437         Mask2[i] = Idx;
6438       }
6439
6440     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6441   }
6442
6443   if (NumLo == 3 || NumHi == 3) {
6444     // Otherwise, we must have three elements from one vector, call it X, and
6445     // one element from the other, call it Y.  First, use a shufps to build an
6446     // intermediate vector with the one element from Y and the element from X
6447     // that will be in the same half in the final destination (the indexes don't
6448     // matter). Then, use a shufps to build the final vector, taking the half
6449     // containing the element from Y from the intermediate, and the other half
6450     // from X.
6451     if (NumHi == 3) {
6452       // Normalize it so the 3 elements come from V1.
6453       CommuteVectorShuffleMask(PermMask, 4);
6454       std::swap(V1, V2);
6455     }
6456
6457     // Find the element from V2.
6458     unsigned HiIndex;
6459     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6460       int Val = PermMask[HiIndex];
6461       if (Val < 0)
6462         continue;
6463       if (Val >= 4)
6464         break;
6465     }
6466
6467     Mask1[0] = PermMask[HiIndex];
6468     Mask1[1] = -1;
6469     Mask1[2] = PermMask[HiIndex^1];
6470     Mask1[3] = -1;
6471     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6472
6473     if (HiIndex >= 2) {
6474       Mask1[0] = PermMask[0];
6475       Mask1[1] = PermMask[1];
6476       Mask1[2] = HiIndex & 1 ? 6 : 4;
6477       Mask1[3] = HiIndex & 1 ? 4 : 6;
6478       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6479     }
6480
6481     Mask1[0] = HiIndex & 1 ? 2 : 0;
6482     Mask1[1] = HiIndex & 1 ? 0 : 2;
6483     Mask1[2] = PermMask[2];
6484     Mask1[3] = PermMask[3];
6485     if (Mask1[2] >= 0)
6486       Mask1[2] += 4;
6487     if (Mask1[3] >= 0)
6488       Mask1[3] += 4;
6489     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6490   }
6491
6492   // Break it into (shuffle shuffle_hi, shuffle_lo).
6493   int LoMask[] = { -1, -1, -1, -1 };
6494   int HiMask[] = { -1, -1, -1, -1 };
6495
6496   int *MaskPtr = LoMask;
6497   unsigned MaskIdx = 0;
6498   unsigned LoIdx = 0;
6499   unsigned HiIdx = 2;
6500   for (unsigned i = 0; i != 4; ++i) {
6501     if (i == 2) {
6502       MaskPtr = HiMask;
6503       MaskIdx = 1;
6504       LoIdx = 0;
6505       HiIdx = 2;
6506     }
6507     int Idx = PermMask[i];
6508     if (Idx < 0) {
6509       Locs[i] = std::make_pair(-1, -1);
6510     } else if (Idx < 4) {
6511       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6512       MaskPtr[LoIdx] = Idx;
6513       LoIdx++;
6514     } else {
6515       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6516       MaskPtr[HiIdx] = Idx;
6517       HiIdx++;
6518     }
6519   }
6520
6521   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6522   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6523   int MaskOps[] = { -1, -1, -1, -1 };
6524   for (unsigned i = 0; i != 4; ++i)
6525     if (Locs[i].first != -1)
6526       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6527   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6528 }
6529
6530 static bool MayFoldVectorLoad(SDValue V) {
6531   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6532     V = V.getOperand(0);
6533
6534   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6535     V = V.getOperand(0);
6536   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6537       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6538     // BUILD_VECTOR (load), undef
6539     V = V.getOperand(0);
6540
6541   return MayFoldLoad(V);
6542 }
6543
6544 static
6545 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6546   EVT VT = Op.getValueType();
6547
6548   // Canonizalize to v2f64.
6549   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6550   return DAG.getNode(ISD::BITCAST, dl, VT,
6551                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6552                                           V1, DAG));
6553 }
6554
6555 static
6556 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6557                         bool HasSSE2) {
6558   SDValue V1 = Op.getOperand(0);
6559   SDValue V2 = Op.getOperand(1);
6560   EVT VT = Op.getValueType();
6561
6562   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6563
6564   if (HasSSE2 && VT == MVT::v2f64)
6565     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6566
6567   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6568   return DAG.getNode(ISD::BITCAST, dl, VT,
6569                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6570                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6571                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6572 }
6573
6574 static
6575 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6576   SDValue V1 = Op.getOperand(0);
6577   SDValue V2 = Op.getOperand(1);
6578   EVT VT = Op.getValueType();
6579
6580   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6581          "unsupported shuffle type");
6582
6583   if (V2.getOpcode() == ISD::UNDEF)
6584     V2 = V1;
6585
6586   // v4i32 or v4f32
6587   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6588 }
6589
6590 static
6591 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6592   SDValue V1 = Op.getOperand(0);
6593   SDValue V2 = Op.getOperand(1);
6594   EVT VT = Op.getValueType();
6595   unsigned NumElems = VT.getVectorNumElements();
6596
6597   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6598   // operand of these instructions is only memory, so check if there's a
6599   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6600   // same masks.
6601   bool CanFoldLoad = false;
6602
6603   // Trivial case, when V2 comes from a load.
6604   if (MayFoldVectorLoad(V2))
6605     CanFoldLoad = true;
6606
6607   // When V1 is a load, it can be folded later into a store in isel, example:
6608   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6609   //    turns into:
6610   //  (MOVLPSmr addr:$src1, VR128:$src2)
6611   // So, recognize this potential and also use MOVLPS or MOVLPD
6612   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6613     CanFoldLoad = true;
6614
6615   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6616   if (CanFoldLoad) {
6617     if (HasSSE2 && NumElems == 2)
6618       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6619
6620     if (NumElems == 4)
6621       // If we don't care about the second element, proceed to use movss.
6622       if (SVOp->getMaskElt(1) != -1)
6623         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6624   }
6625
6626   // movl and movlp will both match v2i64, but v2i64 is never matched by
6627   // movl earlier because we make it strict to avoid messing with the movlp load
6628   // folding logic (see the code above getMOVLP call). Match it here then,
6629   // this is horrible, but will stay like this until we move all shuffle
6630   // matching to x86 specific nodes. Note that for the 1st condition all
6631   // types are matched with movsd.
6632   if (HasSSE2) {
6633     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6634     // as to remove this logic from here, as much as possible
6635     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6636       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6637     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6638   }
6639
6640   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6641
6642   // Invert the operand order and use SHUFPS to match it.
6643   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6644                               getShuffleSHUFImmediate(SVOp), DAG);
6645 }
6646
6647 // Reduce a vector shuffle to zext.
6648 SDValue
6649 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6650   // PMOVZX is only available from SSE41.
6651   if (!Subtarget->hasSSE41())
6652     return SDValue();
6653
6654   EVT VT = Op.getValueType();
6655
6656   // Only AVX2 support 256-bit vector integer extending.
6657   if (!Subtarget->hasInt256() && VT.is256BitVector())
6658     return SDValue();
6659
6660   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6661   DebugLoc DL = Op.getDebugLoc();
6662   SDValue V1 = Op.getOperand(0);
6663   SDValue V2 = Op.getOperand(1);
6664   unsigned NumElems = VT.getVectorNumElements();
6665
6666   // Extending is an unary operation and the element type of the source vector
6667   // won't be equal to or larger than i64.
6668   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6669       VT.getVectorElementType() == MVT::i64)
6670     return SDValue();
6671
6672   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6673   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6674   while ((1U << Shift) < NumElems) {
6675     if (SVOp->getMaskElt(1U << Shift) == 1)
6676       break;
6677     Shift += 1;
6678     // The maximal ratio is 8, i.e. from i8 to i64.
6679     if (Shift > 3)
6680       return SDValue();
6681   }
6682
6683   // Check the shuffle mask.
6684   unsigned Mask = (1U << Shift) - 1;
6685   for (unsigned i = 0; i != NumElems; ++i) {
6686     int EltIdx = SVOp->getMaskElt(i);
6687     if ((i & Mask) != 0 && EltIdx != -1)
6688       return SDValue();
6689     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6690       return SDValue();
6691   }
6692
6693   LLVMContext *Context = DAG.getContext();
6694   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6695   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6696   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6697
6698   if (!isTypeLegal(NVT))
6699     return SDValue();
6700
6701   // Simplify the operand as it's prepared to be fed into shuffle.
6702   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6703   if (V1.getOpcode() == ISD::BITCAST &&
6704       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6705       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6706       V1.getOperand(0)
6707         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6708     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6709     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6710     ConstantSDNode *CIdx =
6711       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6712     // If it's foldable, i.e. normal load with single use, we will let code
6713     // selection to fold it. Otherwise, we will short the conversion sequence.
6714     if (CIdx && CIdx->getZExtValue() == 0 &&
6715         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6716       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6717         // The "ext_vec_elt" node is wider than the result node.
6718         // In this case we should extract subvector from V.
6719         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6720         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6721         EVT FullVT = V.getValueType();
6722         EVT SubVecVT = EVT::getVectorVT(*Context, 
6723                                         FullVT.getVectorElementType(),
6724                                         FullVT.getVectorNumElements()/Ratio);
6725         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V, 
6726                         DAG.getIntPtrConstant(0));
6727       }
6728       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6729     }
6730   }
6731
6732   return DAG.getNode(ISD::BITCAST, DL, VT,
6733                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6734 }
6735
6736 SDValue
6737 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6738   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6739   MVT VT = Op.getValueType().getSimpleVT();
6740   DebugLoc dl = Op.getDebugLoc();
6741   SDValue V1 = Op.getOperand(0);
6742   SDValue V2 = Op.getOperand(1);
6743
6744   if (isZeroShuffle(SVOp))
6745     return getZeroVector(VT, Subtarget, DAG, dl);
6746
6747   // Handle splat operations
6748   if (SVOp->isSplat()) {
6749     // Use vbroadcast whenever the splat comes from a foldable load
6750     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6751     if (Broadcast.getNode())
6752       return Broadcast;
6753   }
6754
6755   // Check integer expanding shuffles.
6756   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6757   if (NewOp.getNode())
6758     return NewOp;
6759
6760   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6761   // do it!
6762   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6763       VT == MVT::v16i16 || VT == MVT::v32i8) {
6764     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6765     if (NewOp.getNode())
6766       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6767   } else if ((VT == MVT::v4i32 ||
6768              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6769     // FIXME: Figure out a cleaner way to do this.
6770     // Try to make use of movq to zero out the top part.
6771     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6772       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6773       if (NewOp.getNode()) {
6774         MVT NewVT = NewOp.getValueType().getSimpleVT();
6775         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6776                                NewVT, true, false))
6777           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6778                               DAG, Subtarget, dl);
6779       }
6780     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6781       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6782       if (NewOp.getNode()) {
6783         MVT NewVT = NewOp.getValueType().getSimpleVT();
6784         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6785           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6786                               DAG, Subtarget, dl);
6787       }
6788     }
6789   }
6790   return SDValue();
6791 }
6792
6793 SDValue
6794 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6795   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6796   SDValue V1 = Op.getOperand(0);
6797   SDValue V2 = Op.getOperand(1);
6798   MVT VT = Op.getValueType().getSimpleVT();
6799   DebugLoc dl = Op.getDebugLoc();
6800   unsigned NumElems = VT.getVectorNumElements();
6801   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6802   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6803   bool V1IsSplat = false;
6804   bool V2IsSplat = false;
6805   bool HasSSE2 = Subtarget->hasSSE2();
6806   bool HasFp256    = Subtarget->hasFp256();
6807   bool HasInt256   = Subtarget->hasInt256();
6808   MachineFunction &MF = DAG.getMachineFunction();
6809   bool OptForSize = MF.getFunction()->getAttributes().
6810     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6811
6812   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6813
6814   if (V1IsUndef && V2IsUndef)
6815     return DAG.getUNDEF(VT);
6816
6817   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6818
6819   // Vector shuffle lowering takes 3 steps:
6820   //
6821   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6822   //    narrowing and commutation of operands should be handled.
6823   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6824   //    shuffle nodes.
6825   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6826   //    so the shuffle can be broken into other shuffles and the legalizer can
6827   //    try the lowering again.
6828   //
6829   // The general idea is that no vector_shuffle operation should be left to
6830   // be matched during isel, all of them must be converted to a target specific
6831   // node here.
6832
6833   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6834   // narrowing and commutation of operands should be handled. The actual code
6835   // doesn't include all of those, work in progress...
6836   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6837   if (NewOp.getNode())
6838     return NewOp;
6839
6840   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6841
6842   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6843   // unpckh_undef). Only use pshufd if speed is more important than size.
6844   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6845     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6846   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6847     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6848
6849   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6850       V2IsUndef && MayFoldVectorLoad(V1))
6851     return getMOVDDup(Op, dl, V1, DAG);
6852
6853   if (isMOVHLPS_v_undef_Mask(M, VT))
6854     return getMOVHighToLow(Op, dl, DAG);
6855
6856   // Use to match splats
6857   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6858       (VT == MVT::v2f64 || VT == MVT::v2i64))
6859     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6860
6861   if (isPSHUFDMask(M, VT)) {
6862     // The actual implementation will match the mask in the if above and then
6863     // during isel it can match several different instructions, not only pshufd
6864     // as its name says, sad but true, emulate the behavior for now...
6865     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6866       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6867
6868     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6869
6870     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6871       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6872
6873     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6874       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6875                                   DAG);
6876
6877     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6878                                 TargetMask, DAG);
6879   }
6880
6881   // Check if this can be converted into a logical shift.
6882   bool isLeft = false;
6883   unsigned ShAmt = 0;
6884   SDValue ShVal;
6885   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6886   if (isShift && ShVal.hasOneUse()) {
6887     // If the shifted value has multiple uses, it may be cheaper to use
6888     // v_set0 + movlhps or movhlps, etc.
6889     MVT EltVT = VT.getVectorElementType();
6890     ShAmt *= EltVT.getSizeInBits();
6891     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6892   }
6893
6894   if (isMOVLMask(M, VT)) {
6895     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6896       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6897     if (!isMOVLPMask(M, VT)) {
6898       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6899         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6900
6901       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6902         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6903     }
6904   }
6905
6906   // FIXME: fold these into legal mask.
6907   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6908     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6909
6910   if (isMOVHLPSMask(M, VT))
6911     return getMOVHighToLow(Op, dl, DAG);
6912
6913   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6914     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6915
6916   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6917     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6918
6919   if (isMOVLPMask(M, VT))
6920     return getMOVLP(Op, dl, DAG, HasSSE2);
6921
6922   if (ShouldXformToMOVHLPS(M, VT) ||
6923       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6924     return CommuteVectorShuffle(SVOp, DAG);
6925
6926   if (isShift) {
6927     // No better options. Use a vshldq / vsrldq.
6928     MVT EltVT = VT.getVectorElementType();
6929     ShAmt *= EltVT.getSizeInBits();
6930     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6931   }
6932
6933   bool Commuted = false;
6934   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6935   // 1,1,1,1 -> v8i16 though.
6936   V1IsSplat = isSplatVector(V1.getNode());
6937   V2IsSplat = isSplatVector(V2.getNode());
6938
6939   // Canonicalize the splat or undef, if present, to be on the RHS.
6940   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6941     CommuteVectorShuffleMask(M, NumElems);
6942     std::swap(V1, V2);
6943     std::swap(V1IsSplat, V2IsSplat);
6944     Commuted = true;
6945   }
6946
6947   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6948     // Shuffling low element of v1 into undef, just return v1.
6949     if (V2IsUndef)
6950       return V1;
6951     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6952     // the instruction selector will not match, so get a canonical MOVL with
6953     // swapped operands to undo the commute.
6954     return getMOVL(DAG, dl, VT, V2, V1);
6955   }
6956
6957   if (isUNPCKLMask(M, VT, HasInt256))
6958     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6959
6960   if (isUNPCKHMask(M, VT, HasInt256))
6961     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6962
6963   if (V2IsSplat) {
6964     // Normalize mask so all entries that point to V2 points to its first
6965     // element then try to match unpck{h|l} again. If match, return a
6966     // new vector_shuffle with the corrected mask.p
6967     SmallVector<int, 8> NewMask(M.begin(), M.end());
6968     NormalizeMask(NewMask, NumElems);
6969     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6970       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6971     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6972       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6973   }
6974
6975   if (Commuted) {
6976     // Commute is back and try unpck* again.
6977     // FIXME: this seems wrong.
6978     CommuteVectorShuffleMask(M, NumElems);
6979     std::swap(V1, V2);
6980     std::swap(V1IsSplat, V2IsSplat);
6981     Commuted = false;
6982
6983     if (isUNPCKLMask(M, VT, HasInt256))
6984       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6985
6986     if (isUNPCKHMask(M, VT, HasInt256))
6987       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6988   }
6989
6990   // Normalize the node to match x86 shuffle ops if needed
6991   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6992     return CommuteVectorShuffle(SVOp, DAG);
6993
6994   // The checks below are all present in isShuffleMaskLegal, but they are
6995   // inlined here right now to enable us to directly emit target specific
6996   // nodes, and remove one by one until they don't return Op anymore.
6997
6998   if (isPALIGNRMask(M, VT, Subtarget))
6999     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7000                                 getShufflePALIGNRImmediate(SVOp),
7001                                 DAG);
7002
7003   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7004       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7005     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7006       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7007   }
7008
7009   if (isPSHUFHWMask(M, VT, HasInt256))
7010     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7011                                 getShufflePSHUFHWImmediate(SVOp),
7012                                 DAG);
7013
7014   if (isPSHUFLWMask(M, VT, HasInt256))
7015     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7016                                 getShufflePSHUFLWImmediate(SVOp),
7017                                 DAG);
7018
7019   if (isSHUFPMask(M, VT, HasFp256))
7020     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7021                                 getShuffleSHUFImmediate(SVOp), DAG);
7022
7023   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7024     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7025   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7026     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7027
7028   //===--------------------------------------------------------------------===//
7029   // Generate target specific nodes for 128 or 256-bit shuffles only
7030   // supported in the AVX instruction set.
7031   //
7032
7033   // Handle VMOVDDUPY permutations
7034   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7035     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7036
7037   // Handle VPERMILPS/D* permutations
7038   if (isVPERMILPMask(M, VT, HasFp256)) {
7039     if (HasInt256 && VT == MVT::v8i32)
7040       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7041                                   getShuffleSHUFImmediate(SVOp), DAG);
7042     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7043                                 getShuffleSHUFImmediate(SVOp), DAG);
7044   }
7045
7046   // Handle VPERM2F128/VPERM2I128 permutations
7047   if (isVPERM2X128Mask(M, VT, HasFp256))
7048     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7049                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7050
7051   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7052   if (BlendOp.getNode())
7053     return BlendOp;
7054
7055   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7056     SmallVector<SDValue, 8> permclMask;
7057     for (unsigned i = 0; i != 8; ++i) {
7058       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7059     }
7060     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7061                                &permclMask[0], 8);
7062     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7063     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7064                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7065   }
7066
7067   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7068     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7069                                 getShuffleCLImmediate(SVOp), DAG);
7070
7071   //===--------------------------------------------------------------------===//
7072   // Since no target specific shuffle was selected for this generic one,
7073   // lower it into other known shuffles. FIXME: this isn't true yet, but
7074   // this is the plan.
7075   //
7076
7077   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7078   if (VT == MVT::v8i16) {
7079     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7080     if (NewOp.getNode())
7081       return NewOp;
7082   }
7083
7084   if (VT == MVT::v16i8) {
7085     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7086     if (NewOp.getNode())
7087       return NewOp;
7088   }
7089
7090   if (VT == MVT::v32i8) {
7091     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7092     if (NewOp.getNode())
7093       return NewOp;
7094   }
7095
7096   // Handle all 128-bit wide vectors with 4 elements, and match them with
7097   // several different shuffle types.
7098   if (NumElems == 4 && VT.is128BitVector())
7099     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7100
7101   // Handle general 256-bit shuffles
7102   if (VT.is256BitVector())
7103     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7104
7105   return SDValue();
7106 }
7107
7108 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7109   MVT VT = Op.getValueType().getSimpleVT();
7110   DebugLoc dl = Op.getDebugLoc();
7111
7112   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7113     return SDValue();
7114
7115   if (VT.getSizeInBits() == 8) {
7116     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7117                                   Op.getOperand(0), Op.getOperand(1));
7118     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7119                                   DAG.getValueType(VT));
7120     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7121   }
7122
7123   if (VT.getSizeInBits() == 16) {
7124     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7125     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7126     if (Idx == 0)
7127       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7128                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7129                                      DAG.getNode(ISD::BITCAST, dl,
7130                                                  MVT::v4i32,
7131                                                  Op.getOperand(0)),
7132                                      Op.getOperand(1)));
7133     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7134                                   Op.getOperand(0), Op.getOperand(1));
7135     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7136                                   DAG.getValueType(VT));
7137     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7138   }
7139
7140   if (VT == MVT::f32) {
7141     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7142     // the result back to FR32 register. It's only worth matching if the
7143     // result has a single use which is a store or a bitcast to i32.  And in
7144     // the case of a store, it's not worth it if the index is a constant 0,
7145     // because a MOVSSmr can be used instead, which is smaller and faster.
7146     if (!Op.hasOneUse())
7147       return SDValue();
7148     SDNode *User = *Op.getNode()->use_begin();
7149     if ((User->getOpcode() != ISD::STORE ||
7150          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7151           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7152         (User->getOpcode() != ISD::BITCAST ||
7153          User->getValueType(0) != MVT::i32))
7154       return SDValue();
7155     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7156                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7157                                               Op.getOperand(0)),
7158                                               Op.getOperand(1));
7159     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7160   }
7161
7162   if (VT == MVT::i32 || VT == MVT::i64) {
7163     // ExtractPS/pextrq works with constant index.
7164     if (isa<ConstantSDNode>(Op.getOperand(1)))
7165       return Op;
7166   }
7167   return SDValue();
7168 }
7169
7170 SDValue
7171 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7172                                            SelectionDAG &DAG) const {
7173   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7174     return SDValue();
7175
7176   SDValue Vec = Op.getOperand(0);
7177   MVT VecVT = Vec.getValueType().getSimpleVT();
7178
7179   // If this is a 256-bit vector result, first extract the 128-bit vector and
7180   // then extract the element from the 128-bit vector.
7181   if (VecVT.is256BitVector()) {
7182     DebugLoc dl = Op.getNode()->getDebugLoc();
7183     unsigned NumElems = VecVT.getVectorNumElements();
7184     SDValue Idx = Op.getOperand(1);
7185     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7186
7187     // Get the 128-bit vector.
7188     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7189
7190     if (IdxVal >= NumElems/2)
7191       IdxVal -= NumElems/2;
7192     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7193                        DAG.getConstant(IdxVal, MVT::i32));
7194   }
7195
7196   assert(VecVT.is128BitVector() && "Unexpected vector length");
7197
7198   if (Subtarget->hasSSE41()) {
7199     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7200     if (Res.getNode())
7201       return Res;
7202   }
7203
7204   MVT VT = Op.getValueType().getSimpleVT();
7205   DebugLoc dl = Op.getDebugLoc();
7206   // TODO: handle v16i8.
7207   if (VT.getSizeInBits() == 16) {
7208     SDValue Vec = Op.getOperand(0);
7209     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7210     if (Idx == 0)
7211       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7212                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7213                                      DAG.getNode(ISD::BITCAST, dl,
7214                                                  MVT::v4i32, Vec),
7215                                      Op.getOperand(1)));
7216     // Transform it so it match pextrw which produces a 32-bit result.
7217     MVT EltVT = MVT::i32;
7218     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7219                                   Op.getOperand(0), Op.getOperand(1));
7220     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7221                                   DAG.getValueType(VT));
7222     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7223   }
7224
7225   if (VT.getSizeInBits() == 32) {
7226     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7227     if (Idx == 0)
7228       return Op;
7229
7230     // SHUFPS the element to the lowest double word, then movss.
7231     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7232     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7233     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7234                                        DAG.getUNDEF(VVT), Mask);
7235     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7236                        DAG.getIntPtrConstant(0));
7237   }
7238
7239   if (VT.getSizeInBits() == 64) {
7240     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7241     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7242     //        to match extract_elt for f64.
7243     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7244     if (Idx == 0)
7245       return Op;
7246
7247     // UNPCKHPD the element to the lowest double word, then movsd.
7248     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7249     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7250     int Mask[2] = { 1, -1 };
7251     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7252     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7253                                        DAG.getUNDEF(VVT), Mask);
7254     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7255                        DAG.getIntPtrConstant(0));
7256   }
7257
7258   return SDValue();
7259 }
7260
7261 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7262   MVT VT = Op.getValueType().getSimpleVT();
7263   MVT EltVT = VT.getVectorElementType();
7264   DebugLoc dl = Op.getDebugLoc();
7265
7266   SDValue N0 = Op.getOperand(0);
7267   SDValue N1 = Op.getOperand(1);
7268   SDValue N2 = Op.getOperand(2);
7269
7270   if (!VT.is128BitVector())
7271     return SDValue();
7272
7273   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7274       isa<ConstantSDNode>(N2)) {
7275     unsigned Opc;
7276     if (VT == MVT::v8i16)
7277       Opc = X86ISD::PINSRW;
7278     else if (VT == MVT::v16i8)
7279       Opc = X86ISD::PINSRB;
7280     else
7281       Opc = X86ISD::PINSRB;
7282
7283     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7284     // argument.
7285     if (N1.getValueType() != MVT::i32)
7286       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7287     if (N2.getValueType() != MVT::i32)
7288       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7289     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7290   }
7291
7292   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7293     // Bits [7:6] of the constant are the source select.  This will always be
7294     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7295     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7296     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7297     // Bits [5:4] of the constant are the destination select.  This is the
7298     //  value of the incoming immediate.
7299     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7300     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7301     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7302     // Create this as a scalar to vector..
7303     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7304     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7305   }
7306
7307   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7308     // PINSR* works with constant index.
7309     return Op;
7310   }
7311   return SDValue();
7312 }
7313
7314 SDValue
7315 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7316   MVT VT = Op.getValueType().getSimpleVT();
7317   MVT EltVT = VT.getVectorElementType();
7318
7319   DebugLoc dl = Op.getDebugLoc();
7320   SDValue N0 = Op.getOperand(0);
7321   SDValue N1 = Op.getOperand(1);
7322   SDValue N2 = Op.getOperand(2);
7323
7324   // If this is a 256-bit vector result, first extract the 128-bit vector,
7325   // insert the element into the extracted half and then place it back.
7326   if (VT.is256BitVector()) {
7327     if (!isa<ConstantSDNode>(N2))
7328       return SDValue();
7329
7330     // Get the desired 128-bit vector half.
7331     unsigned NumElems = VT.getVectorNumElements();
7332     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7333     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7334
7335     // Insert the element into the desired half.
7336     bool Upper = IdxVal >= NumElems/2;
7337     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7338                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7339
7340     // Insert the changed part back to the 256-bit vector
7341     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7342   }
7343
7344   if (Subtarget->hasSSE41())
7345     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7346
7347   if (EltVT == MVT::i8)
7348     return SDValue();
7349
7350   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7351     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7352     // as its second argument.
7353     if (N1.getValueType() != MVT::i32)
7354       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7355     if (N2.getValueType() != MVT::i32)
7356       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7357     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7358   }
7359   return SDValue();
7360 }
7361
7362 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7363   LLVMContext *Context = DAG.getContext();
7364   DebugLoc dl = Op.getDebugLoc();
7365   MVT OpVT = Op.getValueType().getSimpleVT();
7366
7367   // If this is a 256-bit vector result, first insert into a 128-bit
7368   // vector and then insert into the 256-bit vector.
7369   if (!OpVT.is128BitVector()) {
7370     // Insert into a 128-bit vector.
7371     EVT VT128 = EVT::getVectorVT(*Context,
7372                                  OpVT.getVectorElementType(),
7373                                  OpVT.getVectorNumElements() / 2);
7374
7375     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7376
7377     // Insert the 128-bit vector.
7378     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7379   }
7380
7381   if (OpVT == MVT::v1i64 &&
7382       Op.getOperand(0).getValueType() == MVT::i64)
7383     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7384
7385   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7386   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7387   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7388                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7389 }
7390
7391 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7392 // a simple subregister reference or explicit instructions to grab
7393 // upper bits of a vector.
7394 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7395                                       SelectionDAG &DAG) {
7396   if (Subtarget->hasFp256()) {
7397     DebugLoc dl = Op.getNode()->getDebugLoc();
7398     SDValue Vec = Op.getNode()->getOperand(0);
7399     SDValue Idx = Op.getNode()->getOperand(1);
7400
7401     if (Op.getNode()->getValueType(0).is128BitVector() &&
7402         Vec.getNode()->getValueType(0).is256BitVector() &&
7403         isa<ConstantSDNode>(Idx)) {
7404       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7405       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7406     }
7407   }
7408   return SDValue();
7409 }
7410
7411 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7412 // simple superregister reference or explicit instructions to insert
7413 // the upper bits of a vector.
7414 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7415                                      SelectionDAG &DAG) {
7416   if (Subtarget->hasFp256()) {
7417     DebugLoc dl = Op.getNode()->getDebugLoc();
7418     SDValue Vec = Op.getNode()->getOperand(0);
7419     SDValue SubVec = Op.getNode()->getOperand(1);
7420     SDValue Idx = Op.getNode()->getOperand(2);
7421
7422     if (Op.getNode()->getValueType(0).is256BitVector() &&
7423         SubVec.getNode()->getValueType(0).is128BitVector() &&
7424         isa<ConstantSDNode>(Idx)) {
7425       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7426       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7427     }
7428   }
7429   return SDValue();
7430 }
7431
7432 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7433 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7434 // one of the above mentioned nodes. It has to be wrapped because otherwise
7435 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7436 // be used to form addressing mode. These wrapped nodes will be selected
7437 // into MOV32ri.
7438 SDValue
7439 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7440   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7441
7442   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7443   // global base reg.
7444   unsigned char OpFlag = 0;
7445   unsigned WrapperKind = X86ISD::Wrapper;
7446   CodeModel::Model M = getTargetMachine().getCodeModel();
7447
7448   if (Subtarget->isPICStyleRIPRel() &&
7449       (M == CodeModel::Small || M == CodeModel::Kernel))
7450     WrapperKind = X86ISD::WrapperRIP;
7451   else if (Subtarget->isPICStyleGOT())
7452     OpFlag = X86II::MO_GOTOFF;
7453   else if (Subtarget->isPICStyleStubPIC())
7454     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7455
7456   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7457                                              CP->getAlignment(),
7458                                              CP->getOffset(), OpFlag);
7459   DebugLoc DL = CP->getDebugLoc();
7460   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7461   // With PIC, the address is actually $g + Offset.
7462   if (OpFlag) {
7463     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7464                          DAG.getNode(X86ISD::GlobalBaseReg,
7465                                      DebugLoc(), getPointerTy()),
7466                          Result);
7467   }
7468
7469   return Result;
7470 }
7471
7472 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7473   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7474
7475   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7476   // global base reg.
7477   unsigned char OpFlag = 0;
7478   unsigned WrapperKind = X86ISD::Wrapper;
7479   CodeModel::Model M = getTargetMachine().getCodeModel();
7480
7481   if (Subtarget->isPICStyleRIPRel() &&
7482       (M == CodeModel::Small || M == CodeModel::Kernel))
7483     WrapperKind = X86ISD::WrapperRIP;
7484   else if (Subtarget->isPICStyleGOT())
7485     OpFlag = X86II::MO_GOTOFF;
7486   else if (Subtarget->isPICStyleStubPIC())
7487     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7488
7489   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7490                                           OpFlag);
7491   DebugLoc DL = JT->getDebugLoc();
7492   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7493
7494   // With PIC, the address is actually $g + Offset.
7495   if (OpFlag)
7496     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7497                          DAG.getNode(X86ISD::GlobalBaseReg,
7498                                      DebugLoc(), getPointerTy()),
7499                          Result);
7500
7501   return Result;
7502 }
7503
7504 SDValue
7505 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7506   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7507
7508   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7509   // global base reg.
7510   unsigned char OpFlag = 0;
7511   unsigned WrapperKind = X86ISD::Wrapper;
7512   CodeModel::Model M = getTargetMachine().getCodeModel();
7513
7514   if (Subtarget->isPICStyleRIPRel() &&
7515       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7516     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7517       OpFlag = X86II::MO_GOTPCREL;
7518     WrapperKind = X86ISD::WrapperRIP;
7519   } else if (Subtarget->isPICStyleGOT()) {
7520     OpFlag = X86II::MO_GOT;
7521   } else if (Subtarget->isPICStyleStubPIC()) {
7522     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7523   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7524     OpFlag = X86II::MO_DARWIN_NONLAZY;
7525   }
7526
7527   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7528
7529   DebugLoc DL = Op.getDebugLoc();
7530   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7531
7532   // With PIC, the address is actually $g + Offset.
7533   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7534       !Subtarget->is64Bit()) {
7535     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7536                          DAG.getNode(X86ISD::GlobalBaseReg,
7537                                      DebugLoc(), getPointerTy()),
7538                          Result);
7539   }
7540
7541   // For symbols that require a load from a stub to get the address, emit the
7542   // load.
7543   if (isGlobalStubReference(OpFlag))
7544     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7545                          MachinePointerInfo::getGOT(), false, false, false, 0);
7546
7547   return Result;
7548 }
7549
7550 SDValue
7551 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7552   // Create the TargetBlockAddressAddress node.
7553   unsigned char OpFlags =
7554     Subtarget->ClassifyBlockAddressReference();
7555   CodeModel::Model M = getTargetMachine().getCodeModel();
7556   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7557   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7558   DebugLoc dl = Op.getDebugLoc();
7559   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7560                                              OpFlags);
7561
7562   if (Subtarget->isPICStyleRIPRel() &&
7563       (M == CodeModel::Small || M == CodeModel::Kernel))
7564     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7565   else
7566     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7567
7568   // With PIC, the address is actually $g + Offset.
7569   if (isGlobalRelativeToPICBase(OpFlags)) {
7570     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7571                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7572                          Result);
7573   }
7574
7575   return Result;
7576 }
7577
7578 SDValue
7579 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7580                                       int64_t Offset, SelectionDAG &DAG) const {
7581   // Create the TargetGlobalAddress node, folding in the constant
7582   // offset if it is legal.
7583   unsigned char OpFlags =
7584     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7585   CodeModel::Model M = getTargetMachine().getCodeModel();
7586   SDValue Result;
7587   if (OpFlags == X86II::MO_NO_FLAG &&
7588       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7589     // A direct static reference to a global.
7590     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7591     Offset = 0;
7592   } else {
7593     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7594   }
7595
7596   if (Subtarget->isPICStyleRIPRel() &&
7597       (M == CodeModel::Small || M == CodeModel::Kernel))
7598     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7599   else
7600     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7601
7602   // With PIC, the address is actually $g + Offset.
7603   if (isGlobalRelativeToPICBase(OpFlags)) {
7604     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7605                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7606                          Result);
7607   }
7608
7609   // For globals that require a load from a stub to get the address, emit the
7610   // load.
7611   if (isGlobalStubReference(OpFlags))
7612     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7613                          MachinePointerInfo::getGOT(), false, false, false, 0);
7614
7615   // If there was a non-zero offset that we didn't fold, create an explicit
7616   // addition for it.
7617   if (Offset != 0)
7618     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7619                          DAG.getConstant(Offset, getPointerTy()));
7620
7621   return Result;
7622 }
7623
7624 SDValue
7625 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7626   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7627   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7628   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7629 }
7630
7631 static SDValue
7632 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7633            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7634            unsigned char OperandFlags, bool LocalDynamic = false) {
7635   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7636   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7637   DebugLoc dl = GA->getDebugLoc();
7638   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7639                                            GA->getValueType(0),
7640                                            GA->getOffset(),
7641                                            OperandFlags);
7642
7643   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7644                                            : X86ISD::TLSADDR;
7645
7646   if (InFlag) {
7647     SDValue Ops[] = { Chain,  TGA, *InFlag };
7648     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7649   } else {
7650     SDValue Ops[]  = { Chain, TGA };
7651     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7652   }
7653
7654   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7655   MFI->setAdjustsStack(true);
7656
7657   SDValue Flag = Chain.getValue(1);
7658   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7659 }
7660
7661 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7662 static SDValue
7663 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7664                                 const EVT PtrVT) {
7665   SDValue InFlag;
7666   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7667   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7668                                    DAG.getNode(X86ISD::GlobalBaseReg,
7669                                                DebugLoc(), PtrVT), InFlag);
7670   InFlag = Chain.getValue(1);
7671
7672   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7673 }
7674
7675 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7676 static SDValue
7677 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7678                                 const EVT PtrVT) {
7679   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7680                     X86::RAX, X86II::MO_TLSGD);
7681 }
7682
7683 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7684                                            SelectionDAG &DAG,
7685                                            const EVT PtrVT,
7686                                            bool is64Bit) {
7687   DebugLoc dl = GA->getDebugLoc();
7688
7689   // Get the start address of the TLS block for this module.
7690   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7691       .getInfo<X86MachineFunctionInfo>();
7692   MFI->incNumLocalDynamicTLSAccesses();
7693
7694   SDValue Base;
7695   if (is64Bit) {
7696     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7697                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7698   } else {
7699     SDValue InFlag;
7700     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7701         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7702     InFlag = Chain.getValue(1);
7703     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7704                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7705   }
7706
7707   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7708   // of Base.
7709
7710   // Build x@dtpoff.
7711   unsigned char OperandFlags = X86II::MO_DTPOFF;
7712   unsigned WrapperKind = X86ISD::Wrapper;
7713   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7714                                            GA->getValueType(0),
7715                                            GA->getOffset(), OperandFlags);
7716   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7717
7718   // Add x@dtpoff with the base.
7719   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7720 }
7721
7722 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7723 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7724                                    const EVT PtrVT, TLSModel::Model model,
7725                                    bool is64Bit, bool isPIC) {
7726   DebugLoc dl = GA->getDebugLoc();
7727
7728   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7729   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7730                                                          is64Bit ? 257 : 256));
7731
7732   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7733                                       DAG.getIntPtrConstant(0),
7734                                       MachinePointerInfo(Ptr),
7735                                       false, false, false, 0);
7736
7737   unsigned char OperandFlags = 0;
7738   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7739   // initialexec.
7740   unsigned WrapperKind = X86ISD::Wrapper;
7741   if (model == TLSModel::LocalExec) {
7742     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7743   } else if (model == TLSModel::InitialExec) {
7744     if (is64Bit) {
7745       OperandFlags = X86II::MO_GOTTPOFF;
7746       WrapperKind = X86ISD::WrapperRIP;
7747     } else {
7748       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7749     }
7750   } else {
7751     llvm_unreachable("Unexpected model");
7752   }
7753
7754   // emit "addl x@ntpoff,%eax" (local exec)
7755   // or "addl x@indntpoff,%eax" (initial exec)
7756   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7757   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7758                                            GA->getValueType(0),
7759                                            GA->getOffset(), OperandFlags);
7760   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7761
7762   if (model == TLSModel::InitialExec) {
7763     if (isPIC && !is64Bit) {
7764       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7765                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7766                            Offset);
7767     }
7768
7769     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7770                          MachinePointerInfo::getGOT(), false, false, false,
7771                          0);
7772   }
7773
7774   // The address of the thread local variable is the add of the thread
7775   // pointer with the offset of the variable.
7776   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7777 }
7778
7779 SDValue
7780 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7781
7782   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7783   const GlobalValue *GV = GA->getGlobal();
7784
7785   if (Subtarget->isTargetELF()) {
7786     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7787
7788     switch (model) {
7789       case TLSModel::GeneralDynamic:
7790         if (Subtarget->is64Bit())
7791           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7792         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7793       case TLSModel::LocalDynamic:
7794         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7795                                            Subtarget->is64Bit());
7796       case TLSModel::InitialExec:
7797       case TLSModel::LocalExec:
7798         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7799                                    Subtarget->is64Bit(),
7800                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7801     }
7802     llvm_unreachable("Unknown TLS model.");
7803   }
7804
7805   if (Subtarget->isTargetDarwin()) {
7806     // Darwin only has one model of TLS.  Lower to that.
7807     unsigned char OpFlag = 0;
7808     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7809                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7810
7811     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7812     // global base reg.
7813     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7814                   !Subtarget->is64Bit();
7815     if (PIC32)
7816       OpFlag = X86II::MO_TLVP_PIC_BASE;
7817     else
7818       OpFlag = X86II::MO_TLVP;
7819     DebugLoc DL = Op.getDebugLoc();
7820     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7821                                                 GA->getValueType(0),
7822                                                 GA->getOffset(), OpFlag);
7823     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7824
7825     // With PIC32, the address is actually $g + Offset.
7826     if (PIC32)
7827       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7828                            DAG.getNode(X86ISD::GlobalBaseReg,
7829                                        DebugLoc(), getPointerTy()),
7830                            Offset);
7831
7832     // Lowering the machine isd will make sure everything is in the right
7833     // location.
7834     SDValue Chain = DAG.getEntryNode();
7835     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7836     SDValue Args[] = { Chain, Offset };
7837     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7838
7839     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7840     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7841     MFI->setAdjustsStack(true);
7842
7843     // And our return value (tls address) is in the standard call return value
7844     // location.
7845     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7846     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7847                               Chain.getValue(1));
7848   }
7849
7850   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7851     // Just use the implicit TLS architecture
7852     // Need to generate someting similar to:
7853     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7854     //                                  ; from TEB
7855     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7856     //   mov     rcx, qword [rdx+rcx*8]
7857     //   mov     eax, .tls$:tlsvar
7858     //   [rax+rcx] contains the address
7859     // Windows 64bit: gs:0x58
7860     // Windows 32bit: fs:__tls_array
7861
7862     // If GV is an alias then use the aliasee for determining
7863     // thread-localness.
7864     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7865       GV = GA->resolveAliasedGlobal(false);
7866     DebugLoc dl = GA->getDebugLoc();
7867     SDValue Chain = DAG.getEntryNode();
7868
7869     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7870     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7871     // use its literal value of 0x2C.
7872     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7873                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7874                                                              256)
7875                                         : Type::getInt32PtrTy(*DAG.getContext(),
7876                                                               257));
7877
7878     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7879       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7880         DAG.getExternalSymbol("_tls_array", getPointerTy()));
7881
7882     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7883                                         MachinePointerInfo(Ptr),
7884                                         false, false, false, 0);
7885
7886     // Load the _tls_index variable
7887     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7888     if (Subtarget->is64Bit())
7889       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7890                            IDX, MachinePointerInfo(), MVT::i32,
7891                            false, false, 0);
7892     else
7893       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7894                         false, false, false, 0);
7895
7896     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7897                                     getPointerTy());
7898     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7899
7900     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7901     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7902                       false, false, false, 0);
7903
7904     // Get the offset of start of .tls section
7905     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7906                                              GA->getValueType(0),
7907                                              GA->getOffset(), X86II::MO_SECREL);
7908     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7909
7910     // The address of the thread local variable is the add of the thread
7911     // pointer with the offset of the variable.
7912     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7913   }
7914
7915   llvm_unreachable("TLS not implemented for this target.");
7916 }
7917
7918 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7919 /// and take a 2 x i32 value to shift plus a shift amount.
7920 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7921   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7922   EVT VT = Op.getValueType();
7923   unsigned VTBits = VT.getSizeInBits();
7924   DebugLoc dl = Op.getDebugLoc();
7925   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7926   SDValue ShOpLo = Op.getOperand(0);
7927   SDValue ShOpHi = Op.getOperand(1);
7928   SDValue ShAmt  = Op.getOperand(2);
7929   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7930                                      DAG.getConstant(VTBits - 1, MVT::i8))
7931                        : DAG.getConstant(0, VT);
7932
7933   SDValue Tmp2, Tmp3;
7934   if (Op.getOpcode() == ISD::SHL_PARTS) {
7935     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7936     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7937   } else {
7938     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7939     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7940   }
7941
7942   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7943                                 DAG.getConstant(VTBits, MVT::i8));
7944   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7945                              AndNode, DAG.getConstant(0, MVT::i8));
7946
7947   SDValue Hi, Lo;
7948   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7949   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7950   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7951
7952   if (Op.getOpcode() == ISD::SHL_PARTS) {
7953     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7954     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7955   } else {
7956     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7957     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7958   }
7959
7960   SDValue Ops[2] = { Lo, Hi };
7961   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7962 }
7963
7964 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7965                                            SelectionDAG &DAG) const {
7966   EVT SrcVT = Op.getOperand(0).getValueType();
7967
7968   if (SrcVT.isVector())
7969     return SDValue();
7970
7971   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7972          "Unknown SINT_TO_FP to lower!");
7973
7974   // These are really Legal; return the operand so the caller accepts it as
7975   // Legal.
7976   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7977     return Op;
7978   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7979       Subtarget->is64Bit()) {
7980     return Op;
7981   }
7982
7983   DebugLoc dl = Op.getDebugLoc();
7984   unsigned Size = SrcVT.getSizeInBits()/8;
7985   MachineFunction &MF = DAG.getMachineFunction();
7986   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7987   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7988   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7989                                StackSlot,
7990                                MachinePointerInfo::getFixedStack(SSFI),
7991                                false, false, 0);
7992   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7993 }
7994
7995 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7996                                      SDValue StackSlot,
7997                                      SelectionDAG &DAG) const {
7998   // Build the FILD
7999   DebugLoc DL = Op.getDebugLoc();
8000   SDVTList Tys;
8001   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8002   if (useSSE)
8003     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8004   else
8005     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8006
8007   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8008
8009   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8010   MachineMemOperand *MMO;
8011   if (FI) {
8012     int SSFI = FI->getIndex();
8013     MMO =
8014       DAG.getMachineFunction()
8015       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8016                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8017   } else {
8018     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8019     StackSlot = StackSlot.getOperand(1);
8020   }
8021   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8022   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8023                                            X86ISD::FILD, DL,
8024                                            Tys, Ops, array_lengthof(Ops),
8025                                            SrcVT, MMO);
8026
8027   if (useSSE) {
8028     Chain = Result.getValue(1);
8029     SDValue InFlag = Result.getValue(2);
8030
8031     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8032     // shouldn't be necessary except that RFP cannot be live across
8033     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8034     MachineFunction &MF = DAG.getMachineFunction();
8035     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8036     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8037     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8038     Tys = DAG.getVTList(MVT::Other);
8039     SDValue Ops[] = {
8040       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8041     };
8042     MachineMemOperand *MMO =
8043       DAG.getMachineFunction()
8044       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8045                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8046
8047     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8048                                     Ops, array_lengthof(Ops),
8049                                     Op.getValueType(), MMO);
8050     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8051                          MachinePointerInfo::getFixedStack(SSFI),
8052                          false, false, false, 0);
8053   }
8054
8055   return Result;
8056 }
8057
8058 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8059 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8060                                                SelectionDAG &DAG) const {
8061   // This algorithm is not obvious. Here it is what we're trying to output:
8062   /*
8063      movq       %rax,  %xmm0
8064      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8065      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8066      #ifdef __SSE3__
8067        haddpd   %xmm0, %xmm0
8068      #else
8069        pshufd   $0x4e, %xmm0, %xmm1
8070        addpd    %xmm1, %xmm0
8071      #endif
8072   */
8073
8074   DebugLoc dl = Op.getDebugLoc();
8075   LLVMContext *Context = DAG.getContext();
8076
8077   // Build some magic constants.
8078   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8079   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8080   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8081
8082   SmallVector<Constant*,2> CV1;
8083   CV1.push_back(
8084     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8085                                       APInt(64, 0x4330000000000000ULL))));
8086   CV1.push_back(
8087     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8088                                       APInt(64, 0x4530000000000000ULL))));
8089   Constant *C1 = ConstantVector::get(CV1);
8090   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8091
8092   // Load the 64-bit value into an XMM register.
8093   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8094                             Op.getOperand(0));
8095   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8096                               MachinePointerInfo::getConstantPool(),
8097                               false, false, false, 16);
8098   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8099                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8100                               CLod0);
8101
8102   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8103                               MachinePointerInfo::getConstantPool(),
8104                               false, false, false, 16);
8105   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8106   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8107   SDValue Result;
8108
8109   if (Subtarget->hasSSE3()) {
8110     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8111     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8112   } else {
8113     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8114     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8115                                            S2F, 0x4E, DAG);
8116     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8117                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8118                          Sub);
8119   }
8120
8121   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8122                      DAG.getIntPtrConstant(0));
8123 }
8124
8125 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8126 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8127                                                SelectionDAG &DAG) const {
8128   DebugLoc dl = Op.getDebugLoc();
8129   // FP constant to bias correct the final result.
8130   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8131                                    MVT::f64);
8132
8133   // Load the 32-bit value into an XMM register.
8134   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8135                              Op.getOperand(0));
8136
8137   // Zero out the upper parts of the register.
8138   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8139
8140   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8141                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8142                      DAG.getIntPtrConstant(0));
8143
8144   // Or the load with the bias.
8145   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8146                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8147                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8148                                                    MVT::v2f64, Load)),
8149                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8150                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8151                                                    MVT::v2f64, Bias)));
8152   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8153                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8154                    DAG.getIntPtrConstant(0));
8155
8156   // Subtract the bias.
8157   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8158
8159   // Handle final rounding.
8160   EVT DestVT = Op.getValueType();
8161
8162   if (DestVT.bitsLT(MVT::f64))
8163     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8164                        DAG.getIntPtrConstant(0));
8165   if (DestVT.bitsGT(MVT::f64))
8166     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8167
8168   // Handle final rounding.
8169   return Sub;
8170 }
8171
8172 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8173                                                SelectionDAG &DAG) const {
8174   SDValue N0 = Op.getOperand(0);
8175   EVT SVT = N0.getValueType();
8176   DebugLoc dl = Op.getDebugLoc();
8177
8178   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8179           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8180          "Custom UINT_TO_FP is not supported!");
8181
8182   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8183                              SVT.getVectorNumElements());
8184   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8185                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8186 }
8187
8188 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8189                                            SelectionDAG &DAG) const {
8190   SDValue N0 = Op.getOperand(0);
8191   DebugLoc dl = Op.getDebugLoc();
8192
8193   if (Op.getValueType().isVector())
8194     return lowerUINT_TO_FP_vec(Op, DAG);
8195
8196   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8197   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8198   // the optimization here.
8199   if (DAG.SignBitIsZero(N0))
8200     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8201
8202   EVT SrcVT = N0.getValueType();
8203   EVT DstVT = Op.getValueType();
8204   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8205     return LowerUINT_TO_FP_i64(Op, DAG);
8206   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8207     return LowerUINT_TO_FP_i32(Op, DAG);
8208   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8209     return SDValue();
8210
8211   // Make a 64-bit buffer, and use it to build an FILD.
8212   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8213   if (SrcVT == MVT::i32) {
8214     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8215     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8216                                      getPointerTy(), StackSlot, WordOff);
8217     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8218                                   StackSlot, MachinePointerInfo(),
8219                                   false, false, 0);
8220     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8221                                   OffsetSlot, MachinePointerInfo(),
8222                                   false, false, 0);
8223     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8224     return Fild;
8225   }
8226
8227   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8228   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8229                                StackSlot, MachinePointerInfo(),
8230                                false, false, 0);
8231   // For i64 source, we need to add the appropriate power of 2 if the input
8232   // was negative.  This is the same as the optimization in
8233   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8234   // we must be careful to do the computation in x87 extended precision, not
8235   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8236   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8237   MachineMemOperand *MMO =
8238     DAG.getMachineFunction()
8239     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8240                           MachineMemOperand::MOLoad, 8, 8);
8241
8242   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8243   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8244   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8245                                          array_lengthof(Ops), MVT::i64, MMO);
8246
8247   APInt FF(32, 0x5F800000ULL);
8248
8249   // Check whether the sign bit is set.
8250   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8251                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8252                                  ISD::SETLT);
8253
8254   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8255   SDValue FudgePtr = DAG.getConstantPool(
8256                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8257                                          getPointerTy());
8258
8259   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8260   SDValue Zero = DAG.getIntPtrConstant(0);
8261   SDValue Four = DAG.getIntPtrConstant(4);
8262   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8263                                Zero, Four);
8264   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8265
8266   // Load the value out, extending it from f32 to f80.
8267   // FIXME: Avoid the extend by constructing the right constant pool?
8268   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8269                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8270                                  MVT::f32, false, false, 4);
8271   // Extend everything to 80 bits to force it to be done on x87.
8272   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8273   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8274 }
8275
8276 std::pair<SDValue,SDValue>
8277 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8278                                     bool IsSigned, bool IsReplace) const {
8279   DebugLoc DL = Op.getDebugLoc();
8280
8281   EVT DstTy = Op.getValueType();
8282
8283   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8284     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8285     DstTy = MVT::i64;
8286   }
8287
8288   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8289          DstTy.getSimpleVT() >= MVT::i16 &&
8290          "Unknown FP_TO_INT to lower!");
8291
8292   // These are really Legal.
8293   if (DstTy == MVT::i32 &&
8294       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8295     return std::make_pair(SDValue(), SDValue());
8296   if (Subtarget->is64Bit() &&
8297       DstTy == MVT::i64 &&
8298       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8299     return std::make_pair(SDValue(), SDValue());
8300
8301   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8302   // stack slot, or into the FTOL runtime function.
8303   MachineFunction &MF = DAG.getMachineFunction();
8304   unsigned MemSize = DstTy.getSizeInBits()/8;
8305   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8306   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8307
8308   unsigned Opc;
8309   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8310     Opc = X86ISD::WIN_FTOL;
8311   else
8312     switch (DstTy.getSimpleVT().SimpleTy) {
8313     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8314     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8315     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8316     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8317     }
8318
8319   SDValue Chain = DAG.getEntryNode();
8320   SDValue Value = Op.getOperand(0);
8321   EVT TheVT = Op.getOperand(0).getValueType();
8322   // FIXME This causes a redundant load/store if the SSE-class value is already
8323   // in memory, such as if it is on the callstack.
8324   if (isScalarFPTypeInSSEReg(TheVT)) {
8325     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8326     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8327                          MachinePointerInfo::getFixedStack(SSFI),
8328                          false, false, 0);
8329     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8330     SDValue Ops[] = {
8331       Chain, StackSlot, DAG.getValueType(TheVT)
8332     };
8333
8334     MachineMemOperand *MMO =
8335       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8336                               MachineMemOperand::MOLoad, MemSize, MemSize);
8337     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8338                                     array_lengthof(Ops), DstTy, MMO);
8339     Chain = Value.getValue(1);
8340     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8341     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8342   }
8343
8344   MachineMemOperand *MMO =
8345     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8346                             MachineMemOperand::MOStore, MemSize, MemSize);
8347
8348   if (Opc != X86ISD::WIN_FTOL) {
8349     // Build the FP_TO_INT*_IN_MEM
8350     SDValue Ops[] = { Chain, Value, StackSlot };
8351     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8352                                            Ops, array_lengthof(Ops), DstTy,
8353                                            MMO);
8354     return std::make_pair(FIST, StackSlot);
8355   } else {
8356     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8357       DAG.getVTList(MVT::Other, MVT::Glue),
8358       Chain, Value);
8359     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8360       MVT::i32, ftol.getValue(1));
8361     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8362       MVT::i32, eax.getValue(2));
8363     SDValue Ops[] = { eax, edx };
8364     SDValue pair = IsReplace
8365       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8366       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8367     return std::make_pair(pair, SDValue());
8368   }
8369 }
8370
8371 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8372                               const X86Subtarget *Subtarget) {
8373   MVT VT = Op->getValueType(0).getSimpleVT();
8374   SDValue In = Op->getOperand(0);
8375   MVT InVT = In.getValueType().getSimpleVT();
8376   DebugLoc dl = Op->getDebugLoc();
8377
8378   // Optimize vectors in AVX mode:
8379   //
8380   //   v8i16 -> v8i32
8381   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8382   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8383   //   Concat upper and lower parts.
8384   //
8385   //   v4i32 -> v4i64
8386   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8387   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8388   //   Concat upper and lower parts.
8389   //
8390
8391   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8392       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8393     return SDValue();
8394
8395   if (Subtarget->hasInt256())
8396     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8397
8398   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8399   SDValue Undef = DAG.getUNDEF(InVT);
8400   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8401   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8402   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8403
8404   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8405                              VT.getVectorNumElements()/2);
8406
8407   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8408   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8409
8410   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8411 }
8412
8413 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8414                                            SelectionDAG &DAG) const {
8415   if (Subtarget->hasFp256()) {
8416     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8417     if (Res.getNode())
8418       return Res;
8419   }
8420
8421   return SDValue();
8422 }
8423 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8424                                             SelectionDAG &DAG) const {
8425   DebugLoc DL = Op.getDebugLoc();
8426   MVT VT = Op.getValueType().getSimpleVT();
8427   SDValue In = Op.getOperand(0);
8428   MVT SVT = In.getValueType().getSimpleVT();
8429
8430   if (Subtarget->hasFp256()) {
8431     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8432     if (Res.getNode())
8433       return Res;
8434   }
8435
8436   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8437       VT.getVectorNumElements() != SVT.getVectorNumElements())
8438     return SDValue();
8439
8440   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8441
8442   // AVX2 has better support of integer extending.
8443   if (Subtarget->hasInt256())
8444     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8445
8446   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8447   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8448   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8449                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8450                                                 DAG.getUNDEF(MVT::v8i16),
8451                                                 &Mask[0]));
8452
8453   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8454 }
8455
8456 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8457   DebugLoc DL = Op.getDebugLoc();
8458   MVT VT = Op.getValueType().getSimpleVT();
8459   SDValue In = Op.getOperand(0);
8460   MVT SVT = In.getValueType().getSimpleVT();
8461
8462   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8463     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8464     if (Subtarget->hasInt256()) {
8465       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8466       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8467       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8468                                 ShufMask);
8469       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8470                          DAG.getIntPtrConstant(0));
8471     }
8472
8473     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8474     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8475                                DAG.getIntPtrConstant(0));
8476     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8477                                DAG.getIntPtrConstant(2));
8478
8479     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8480     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8481
8482     // The PSHUFD mask:
8483     static const int ShufMask1[] = {0, 2, 0, 0};
8484     SDValue Undef = DAG.getUNDEF(VT);
8485     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8486     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8487
8488     // The MOVLHPS mask:
8489     static const int ShufMask2[] = {0, 1, 4, 5};
8490     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8491   }
8492
8493   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8494     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8495     if (Subtarget->hasInt256()) {
8496       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8497
8498       SmallVector<SDValue,32> pshufbMask;
8499       for (unsigned i = 0; i < 2; ++i) {
8500         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8501         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8502         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8503         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8504         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8505         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8506         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8507         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8508         for (unsigned j = 0; j < 8; ++j)
8509           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8510       }
8511       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8512                                &pshufbMask[0], 32);
8513       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8514       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8515
8516       static const int ShufMask[] = {0,  2,  -1,  -1};
8517       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8518                                 &ShufMask[0]);
8519       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8520                        DAG.getIntPtrConstant(0));
8521       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8522     }
8523
8524     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8525                                DAG.getIntPtrConstant(0));
8526
8527     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8528                                DAG.getIntPtrConstant(4));
8529
8530     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8531     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8532
8533     // The PSHUFB mask:
8534     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8535                                    -1, -1, -1, -1, -1, -1, -1, -1};
8536
8537     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8538     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8539     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8540
8541     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8542     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8543
8544     // The MOVLHPS Mask:
8545     static const int ShufMask2[] = {0, 1, 4, 5};
8546     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8547     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8548   }
8549
8550   // Handle truncation of V256 to V128 using shuffles.
8551   if (!VT.is128BitVector() || !SVT.is256BitVector())
8552     return SDValue();
8553
8554   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8555          "Invalid op");
8556   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8557
8558   unsigned NumElems = VT.getVectorNumElements();
8559   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8560                              NumElems * 2);
8561
8562   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8563   // Prepare truncation shuffle mask
8564   for (unsigned i = 0; i != NumElems; ++i)
8565     MaskVec[i] = i * 2;
8566   SDValue V = DAG.getVectorShuffle(NVT, DL,
8567                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8568                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8569   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8570                      DAG.getIntPtrConstant(0));
8571 }
8572
8573 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8574                                            SelectionDAG &DAG) const {
8575   MVT VT = Op.getValueType().getSimpleVT();
8576   if (VT.isVector()) {
8577     if (VT == MVT::v8i16)
8578       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8579                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8580                                      MVT::v8i32, Op.getOperand(0)));
8581     return SDValue();
8582   }
8583
8584   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8585     /*IsSigned=*/ true, /*IsReplace=*/ false);
8586   SDValue FIST = Vals.first, StackSlot = Vals.second;
8587   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8588   if (FIST.getNode() == 0) return Op;
8589
8590   if (StackSlot.getNode())
8591     // Load the result.
8592     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8593                        FIST, StackSlot, MachinePointerInfo(),
8594                        false, false, false, 0);
8595
8596   // The node is the result.
8597   return FIST;
8598 }
8599
8600 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8601                                            SelectionDAG &DAG) const {
8602   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8603     /*IsSigned=*/ false, /*IsReplace=*/ false);
8604   SDValue FIST = Vals.first, StackSlot = Vals.second;
8605   assert(FIST.getNode() && "Unexpected failure");
8606
8607   if (StackSlot.getNode())
8608     // Load the result.
8609     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8610                        FIST, StackSlot, MachinePointerInfo(),
8611                        false, false, false, 0);
8612
8613   // The node is the result.
8614   return FIST;
8615 }
8616
8617 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8618   DebugLoc DL = Op.getDebugLoc();
8619   MVT VT = Op.getValueType().getSimpleVT();
8620   SDValue In = Op.getOperand(0);
8621   MVT SVT = In.getValueType().getSimpleVT();
8622
8623   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8624
8625   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8626                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8627                                  In, DAG.getUNDEF(SVT)));
8628 }
8629
8630 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8631   LLVMContext *Context = DAG.getContext();
8632   DebugLoc dl = Op.getDebugLoc();
8633   MVT VT = Op.getValueType().getSimpleVT();
8634   MVT EltVT = VT;
8635   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8636   if (VT.isVector()) {
8637     EltVT = VT.getVectorElementType();
8638     NumElts = VT.getVectorNumElements();
8639   }
8640   Constant *C;
8641   if (EltVT == MVT::f64)
8642     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8643                                           APInt(64, ~(1ULL << 63))));
8644   else
8645     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8646                                           APInt(32, ~(1U << 31))));
8647   C = ConstantVector::getSplat(NumElts, C);
8648   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8649   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8650   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8651                              MachinePointerInfo::getConstantPool(),
8652                              false, false, false, Alignment);
8653   if (VT.isVector()) {
8654     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8655     return DAG.getNode(ISD::BITCAST, dl, VT,
8656                        DAG.getNode(ISD::AND, dl, ANDVT,
8657                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8658                                                Op.getOperand(0)),
8659                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8660   }
8661   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8662 }
8663
8664 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8665   LLVMContext *Context = DAG.getContext();
8666   DebugLoc dl = Op.getDebugLoc();
8667   MVT VT = Op.getValueType().getSimpleVT();
8668   MVT EltVT = VT;
8669   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8670   if (VT.isVector()) {
8671     EltVT = VT.getVectorElementType();
8672     NumElts = VT.getVectorNumElements();
8673   }
8674   Constant *C;
8675   if (EltVT == MVT::f64)
8676     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8677                                           APInt(64, 1ULL << 63)));
8678   else
8679     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8680                                           APInt(32, 1U << 31)));
8681   C = ConstantVector::getSplat(NumElts, C);
8682   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8683   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8684   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8685                              MachinePointerInfo::getConstantPool(),
8686                              false, false, false, Alignment);
8687   if (VT.isVector()) {
8688     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8689     return DAG.getNode(ISD::BITCAST, dl, VT,
8690                        DAG.getNode(ISD::XOR, dl, XORVT,
8691                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8692                                                Op.getOperand(0)),
8693                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8694   }
8695
8696   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8697 }
8698
8699 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8700   LLVMContext *Context = DAG.getContext();
8701   SDValue Op0 = Op.getOperand(0);
8702   SDValue Op1 = Op.getOperand(1);
8703   DebugLoc dl = Op.getDebugLoc();
8704   MVT VT = Op.getValueType().getSimpleVT();
8705   MVT SrcVT = Op1.getValueType().getSimpleVT();
8706
8707   // If second operand is smaller, extend it first.
8708   if (SrcVT.bitsLT(VT)) {
8709     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8710     SrcVT = VT;
8711   }
8712   // And if it is bigger, shrink it first.
8713   if (SrcVT.bitsGT(VT)) {
8714     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8715     SrcVT = VT;
8716   }
8717
8718   // At this point the operands and the result should have the same
8719   // type, and that won't be f80 since that is not custom lowered.
8720
8721   // First get the sign bit of second operand.
8722   SmallVector<Constant*,4> CV;
8723   if (SrcVT == MVT::f64) {
8724     const fltSemantics &Sem = APFloat::IEEEdouble;
8725     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8726     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8727   } else {
8728     const fltSemantics &Sem = APFloat::IEEEsingle;
8729     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8730     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8731     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8732     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8733   }
8734   Constant *C = ConstantVector::get(CV);
8735   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8736   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8737                               MachinePointerInfo::getConstantPool(),
8738                               false, false, false, 16);
8739   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8740
8741   // Shift sign bit right or left if the two operands have different types.
8742   if (SrcVT.bitsGT(VT)) {
8743     // Op0 is MVT::f32, Op1 is MVT::f64.
8744     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8745     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8746                           DAG.getConstant(32, MVT::i32));
8747     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8748     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8749                           DAG.getIntPtrConstant(0));
8750   }
8751
8752   // Clear first operand sign bit.
8753   CV.clear();
8754   if (VT == MVT::f64) {
8755     const fltSemantics &Sem = APFloat::IEEEdouble;
8756     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8757                                                    APInt(64, ~(1ULL << 63)))));
8758     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8759   } else {
8760     const fltSemantics &Sem = APFloat::IEEEsingle;
8761     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8762                                                    APInt(32, ~(1U << 31)))));
8763     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8764     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8765     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8766   }
8767   C = ConstantVector::get(CV);
8768   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8769   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8770                               MachinePointerInfo::getConstantPool(),
8771                               false, false, false, 16);
8772   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8773
8774   // Or the value with the sign bit.
8775   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8776 }
8777
8778 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8779   SDValue N0 = Op.getOperand(0);
8780   DebugLoc dl = Op.getDebugLoc();
8781   MVT VT = Op.getValueType().getSimpleVT();
8782
8783   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8784   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8785                                   DAG.getConstant(1, VT));
8786   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8787 }
8788
8789 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8790 //
8791 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8792                                                   SelectionDAG &DAG) const {
8793   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8794
8795   if (!Subtarget->hasSSE41())
8796     return SDValue();
8797
8798   if (!Op->hasOneUse())
8799     return SDValue();
8800
8801   SDNode *N = Op.getNode();
8802   DebugLoc DL = N->getDebugLoc();
8803
8804   SmallVector<SDValue, 8> Opnds;
8805   DenseMap<SDValue, unsigned> VecInMap;
8806   EVT VT = MVT::Other;
8807
8808   // Recognize a special case where a vector is casted into wide integer to
8809   // test all 0s.
8810   Opnds.push_back(N->getOperand(0));
8811   Opnds.push_back(N->getOperand(1));
8812
8813   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8814     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8815     // BFS traverse all OR'd operands.
8816     if (I->getOpcode() == ISD::OR) {
8817       Opnds.push_back(I->getOperand(0));
8818       Opnds.push_back(I->getOperand(1));
8819       // Re-evaluate the number of nodes to be traversed.
8820       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8821       continue;
8822     }
8823
8824     // Quit if a non-EXTRACT_VECTOR_ELT
8825     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8826       return SDValue();
8827
8828     // Quit if without a constant index.
8829     SDValue Idx = I->getOperand(1);
8830     if (!isa<ConstantSDNode>(Idx))
8831       return SDValue();
8832
8833     SDValue ExtractedFromVec = I->getOperand(0);
8834     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8835     if (M == VecInMap.end()) {
8836       VT = ExtractedFromVec.getValueType();
8837       // Quit if not 128/256-bit vector.
8838       if (!VT.is128BitVector() && !VT.is256BitVector())
8839         return SDValue();
8840       // Quit if not the same type.
8841       if (VecInMap.begin() != VecInMap.end() &&
8842           VT != VecInMap.begin()->first.getValueType())
8843         return SDValue();
8844       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8845     }
8846     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8847   }
8848
8849   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8850          "Not extracted from 128-/256-bit vector.");
8851
8852   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8853   SmallVector<SDValue, 8> VecIns;
8854
8855   for (DenseMap<SDValue, unsigned>::const_iterator
8856         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8857     // Quit if not all elements are used.
8858     if (I->second != FullMask)
8859       return SDValue();
8860     VecIns.push_back(I->first);
8861   }
8862
8863   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8864
8865   // Cast all vectors into TestVT for PTEST.
8866   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8867     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8868
8869   // If more than one full vectors are evaluated, OR them first before PTEST.
8870   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8871     // Each iteration will OR 2 nodes and append the result until there is only
8872     // 1 node left, i.e. the final OR'd value of all vectors.
8873     SDValue LHS = VecIns[Slot];
8874     SDValue RHS = VecIns[Slot + 1];
8875     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8876   }
8877
8878   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8879                      VecIns.back(), VecIns.back());
8880 }
8881
8882 /// Emit nodes that will be selected as "test Op0,Op0", or something
8883 /// equivalent.
8884 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8885                                     SelectionDAG &DAG) const {
8886   DebugLoc dl = Op.getDebugLoc();
8887
8888   // CF and OF aren't always set the way we want. Determine which
8889   // of these we need.
8890   bool NeedCF = false;
8891   bool NeedOF = false;
8892   switch (X86CC) {
8893   default: break;
8894   case X86::COND_A: case X86::COND_AE:
8895   case X86::COND_B: case X86::COND_BE:
8896     NeedCF = true;
8897     break;
8898   case X86::COND_G: case X86::COND_GE:
8899   case X86::COND_L: case X86::COND_LE:
8900   case X86::COND_O: case X86::COND_NO:
8901     NeedOF = true;
8902     break;
8903   }
8904
8905   // See if we can use the EFLAGS value from the operand instead of
8906   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8907   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8908   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8909     // Emit a CMP with 0, which is the TEST pattern.
8910     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8911                        DAG.getConstant(0, Op.getValueType()));
8912
8913   unsigned Opcode = 0;
8914   unsigned NumOperands = 0;
8915
8916   // Truncate operations may prevent the merge of the SETCC instruction
8917   // and the arithmetic intruction before it. Attempt to truncate the operands
8918   // of the arithmetic instruction and use a reduced bit-width instruction.
8919   bool NeedTruncation = false;
8920   SDValue ArithOp = Op;
8921   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8922     SDValue Arith = Op->getOperand(0);
8923     // Both the trunc and the arithmetic op need to have one user each.
8924     if (Arith->hasOneUse())
8925       switch (Arith.getOpcode()) {
8926         default: break;
8927         case ISD::ADD:
8928         case ISD::SUB:
8929         case ISD::AND:
8930         case ISD::OR:
8931         case ISD::XOR: {
8932           NeedTruncation = true;
8933           ArithOp = Arith;
8934         }
8935       }
8936   }
8937
8938   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8939   // which may be the result of a CAST.  We use the variable 'Op', which is the
8940   // non-casted variable when we check for possible users.
8941   switch (ArithOp.getOpcode()) {
8942   case ISD::ADD:
8943     // Due to an isel shortcoming, be conservative if this add is likely to be
8944     // selected as part of a load-modify-store instruction. When the root node
8945     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8946     // uses of other nodes in the match, such as the ADD in this case. This
8947     // leads to the ADD being left around and reselected, with the result being
8948     // two adds in the output.  Alas, even if none our users are stores, that
8949     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8950     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8951     // climbing the DAG back to the root, and it doesn't seem to be worth the
8952     // effort.
8953     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8954          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8955       if (UI->getOpcode() != ISD::CopyToReg &&
8956           UI->getOpcode() != ISD::SETCC &&
8957           UI->getOpcode() != ISD::STORE)
8958         goto default_case;
8959
8960     if (ConstantSDNode *C =
8961         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8962       // An add of one will be selected as an INC.
8963       if (C->getAPIntValue() == 1) {
8964         Opcode = X86ISD::INC;
8965         NumOperands = 1;
8966         break;
8967       }
8968
8969       // An add of negative one (subtract of one) will be selected as a DEC.
8970       if (C->getAPIntValue().isAllOnesValue()) {
8971         Opcode = X86ISD::DEC;
8972         NumOperands = 1;
8973         break;
8974       }
8975     }
8976
8977     // Otherwise use a regular EFLAGS-setting add.
8978     Opcode = X86ISD::ADD;
8979     NumOperands = 2;
8980     break;
8981   case ISD::AND: {
8982     // If the primary and result isn't used, don't bother using X86ISD::AND,
8983     // because a TEST instruction will be better.
8984     bool NonFlagUse = false;
8985     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8986            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8987       SDNode *User = *UI;
8988       unsigned UOpNo = UI.getOperandNo();
8989       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8990         // Look pass truncate.
8991         UOpNo = User->use_begin().getOperandNo();
8992         User = *User->use_begin();
8993       }
8994
8995       if (User->getOpcode() != ISD::BRCOND &&
8996           User->getOpcode() != ISD::SETCC &&
8997           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8998         NonFlagUse = true;
8999         break;
9000       }
9001     }
9002
9003     if (!NonFlagUse)
9004       break;
9005   }
9006     // FALL THROUGH
9007   case ISD::SUB:
9008   case ISD::OR:
9009   case ISD::XOR:
9010     // Due to the ISEL shortcoming noted above, be conservative if this op is
9011     // likely to be selected as part of a load-modify-store instruction.
9012     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9013            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9014       if (UI->getOpcode() == ISD::STORE)
9015         goto default_case;
9016
9017     // Otherwise use a regular EFLAGS-setting instruction.
9018     switch (ArithOp.getOpcode()) {
9019     default: llvm_unreachable("unexpected operator!");
9020     case ISD::SUB: Opcode = X86ISD::SUB; break;
9021     case ISD::XOR: Opcode = X86ISD::XOR; break;
9022     case ISD::AND: Opcode = X86ISD::AND; break;
9023     case ISD::OR: {
9024       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9025         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9026         if (EFLAGS.getNode())
9027           return EFLAGS;
9028       }
9029       Opcode = X86ISD::OR;
9030       break;
9031     }
9032     }
9033
9034     NumOperands = 2;
9035     break;
9036   case X86ISD::ADD:
9037   case X86ISD::SUB:
9038   case X86ISD::INC:
9039   case X86ISD::DEC:
9040   case X86ISD::OR:
9041   case X86ISD::XOR:
9042   case X86ISD::AND:
9043     return SDValue(Op.getNode(), 1);
9044   default:
9045   default_case:
9046     break;
9047   }
9048
9049   // If we found that truncation is beneficial, perform the truncation and
9050   // update 'Op'.
9051   if (NeedTruncation) {
9052     EVT VT = Op.getValueType();
9053     SDValue WideVal = Op->getOperand(0);
9054     EVT WideVT = WideVal.getValueType();
9055     unsigned ConvertedOp = 0;
9056     // Use a target machine opcode to prevent further DAGCombine
9057     // optimizations that may separate the arithmetic operations
9058     // from the setcc node.
9059     switch (WideVal.getOpcode()) {
9060       default: break;
9061       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9062       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9063       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9064       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9065       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9066     }
9067
9068     if (ConvertedOp) {
9069       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9070       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9071         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9072         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9073         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9074       }
9075     }
9076   }
9077
9078   if (Opcode == 0)
9079     // Emit a CMP with 0, which is the TEST pattern.
9080     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9081                        DAG.getConstant(0, Op.getValueType()));
9082
9083   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9084   SmallVector<SDValue, 4> Ops;
9085   for (unsigned i = 0; i != NumOperands; ++i)
9086     Ops.push_back(Op.getOperand(i));
9087
9088   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9089   DAG.ReplaceAllUsesWith(Op, New);
9090   return SDValue(New.getNode(), 1);
9091 }
9092
9093 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9094 /// equivalent.
9095 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9096                                    SelectionDAG &DAG) const {
9097   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9098     if (C->getAPIntValue() == 0)
9099       return EmitTest(Op0, X86CC, DAG);
9100
9101   DebugLoc dl = Op0.getDebugLoc();
9102   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9103        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9104     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9105     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9106     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9107                               Op0, Op1);
9108     return SDValue(Sub.getNode(), 1);
9109   }
9110   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9111 }
9112
9113 /// Convert a comparison if required by the subtarget.
9114 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9115                                                  SelectionDAG &DAG) const {
9116   // If the subtarget does not support the FUCOMI instruction, floating-point
9117   // comparisons have to be converted.
9118   if (Subtarget->hasCMov() ||
9119       Cmp.getOpcode() != X86ISD::CMP ||
9120       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9121       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9122     return Cmp;
9123
9124   // The instruction selector will select an FUCOM instruction instead of
9125   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9126   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9127   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9128   DebugLoc dl = Cmp.getDebugLoc();
9129   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9130   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9131   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9132                             DAG.getConstant(8, MVT::i8));
9133   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9134   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9135 }
9136
9137 static bool isAllOnes(SDValue V) {
9138   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9139   return C && C->isAllOnesValue();
9140 }
9141
9142 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9143 /// if it's possible.
9144 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9145                                      DebugLoc dl, SelectionDAG &DAG) const {
9146   SDValue Op0 = And.getOperand(0);
9147   SDValue Op1 = And.getOperand(1);
9148   if (Op0.getOpcode() == ISD::TRUNCATE)
9149     Op0 = Op0.getOperand(0);
9150   if (Op1.getOpcode() == ISD::TRUNCATE)
9151     Op1 = Op1.getOperand(0);
9152
9153   SDValue LHS, RHS;
9154   if (Op1.getOpcode() == ISD::SHL)
9155     std::swap(Op0, Op1);
9156   if (Op0.getOpcode() == ISD::SHL) {
9157     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9158       if (And00C->getZExtValue() == 1) {
9159         // If we looked past a truncate, check that it's only truncating away
9160         // known zeros.
9161         unsigned BitWidth = Op0.getValueSizeInBits();
9162         unsigned AndBitWidth = And.getValueSizeInBits();
9163         if (BitWidth > AndBitWidth) {
9164           APInt Zeros, Ones;
9165           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9166           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9167             return SDValue();
9168         }
9169         LHS = Op1;
9170         RHS = Op0.getOperand(1);
9171       }
9172   } else if (Op1.getOpcode() == ISD::Constant) {
9173     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9174     uint64_t AndRHSVal = AndRHS->getZExtValue();
9175     SDValue AndLHS = Op0;
9176
9177     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9178       LHS = AndLHS.getOperand(0);
9179       RHS = AndLHS.getOperand(1);
9180     }
9181
9182     // Use BT if the immediate can't be encoded in a TEST instruction.
9183     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9184       LHS = AndLHS;
9185       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9186     }
9187   }
9188
9189   if (LHS.getNode()) {
9190     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9191     // the condition code later.
9192     bool Invert = false;
9193     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9194       Invert = true;
9195       LHS = LHS.getOperand(0);
9196     }
9197
9198     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9199     // instruction.  Since the shift amount is in-range-or-undefined, we know
9200     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9201     // the encoding for the i16 version is larger than the i32 version.
9202     // Also promote i16 to i32 for performance / code size reason.
9203     if (LHS.getValueType() == MVT::i8 ||
9204         LHS.getValueType() == MVT::i16)
9205       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9206
9207     // If the operand types disagree, extend the shift amount to match.  Since
9208     // BT ignores high bits (like shifts) we can use anyextend.
9209     if (LHS.getValueType() != RHS.getValueType())
9210       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9211
9212     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9213     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9214     // Flip the condition if the LHS was a not instruction
9215     if (Invert)
9216       Cond = X86::GetOppositeBranchCondition(Cond);
9217     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9218                        DAG.getConstant(Cond, MVT::i8), BT);
9219   }
9220
9221   return SDValue();
9222 }
9223
9224 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9225 // ones, and then concatenate the result back.
9226 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9227   MVT VT = Op.getValueType().getSimpleVT();
9228
9229   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9230          "Unsupported value type for operation");
9231
9232   unsigned NumElems = VT.getVectorNumElements();
9233   DebugLoc dl = Op.getDebugLoc();
9234   SDValue CC = Op.getOperand(2);
9235
9236   // Extract the LHS vectors
9237   SDValue LHS = Op.getOperand(0);
9238   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9239   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9240
9241   // Extract the RHS vectors
9242   SDValue RHS = Op.getOperand(1);
9243   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9244   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9245
9246   // Issue the operation on the smaller types and concatenate the result back
9247   MVT EltVT = VT.getVectorElementType();
9248   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9249   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9250                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9251                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9252 }
9253
9254 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9255                            SelectionDAG &DAG) {
9256   SDValue Cond;
9257   SDValue Op0 = Op.getOperand(0);
9258   SDValue Op1 = Op.getOperand(1);
9259   SDValue CC = Op.getOperand(2);
9260   MVT VT = Op.getValueType().getSimpleVT();
9261   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9262   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9263   DebugLoc dl = Op.getDebugLoc();
9264
9265   if (isFP) {
9266 #ifndef NDEBUG
9267     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9268     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9269 #endif
9270
9271     unsigned SSECC;
9272     bool Swap = false;
9273
9274     // SSE Condition code mapping:
9275     //  0 - EQ
9276     //  1 - LT
9277     //  2 - LE
9278     //  3 - UNORD
9279     //  4 - NEQ
9280     //  5 - NLT
9281     //  6 - NLE
9282     //  7 - ORD
9283     switch (SetCCOpcode) {
9284     default: llvm_unreachable("Unexpected SETCC condition");
9285     case ISD::SETOEQ:
9286     case ISD::SETEQ:  SSECC = 0; break;
9287     case ISD::SETOGT:
9288     case ISD::SETGT: Swap = true; // Fallthrough
9289     case ISD::SETLT:
9290     case ISD::SETOLT: SSECC = 1; break;
9291     case ISD::SETOGE:
9292     case ISD::SETGE: Swap = true; // Fallthrough
9293     case ISD::SETLE:
9294     case ISD::SETOLE: SSECC = 2; break;
9295     case ISD::SETUO:  SSECC = 3; break;
9296     case ISD::SETUNE:
9297     case ISD::SETNE:  SSECC = 4; break;
9298     case ISD::SETULE: Swap = true; // Fallthrough
9299     case ISD::SETUGE: SSECC = 5; break;
9300     case ISD::SETULT: Swap = true; // Fallthrough
9301     case ISD::SETUGT: SSECC = 6; break;
9302     case ISD::SETO:   SSECC = 7; break;
9303     case ISD::SETUEQ:
9304     case ISD::SETONE: SSECC = 8; break;
9305     }
9306     if (Swap)
9307       std::swap(Op0, Op1);
9308
9309     // In the two special cases we can't handle, emit two comparisons.
9310     if (SSECC == 8) {
9311       unsigned CC0, CC1;
9312       unsigned CombineOpc;
9313       if (SetCCOpcode == ISD::SETUEQ) {
9314         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9315       } else {
9316         assert(SetCCOpcode == ISD::SETONE);
9317         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9318       }
9319
9320       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9321                                  DAG.getConstant(CC0, MVT::i8));
9322       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9323                                  DAG.getConstant(CC1, MVT::i8));
9324       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9325     }
9326     // Handle all other FP comparisons here.
9327     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9328                        DAG.getConstant(SSECC, MVT::i8));
9329   }
9330
9331   // Break 256-bit integer vector compare into smaller ones.
9332   if (VT.is256BitVector() && !Subtarget->hasInt256())
9333     return Lower256IntVSETCC(Op, DAG);
9334
9335   // We are handling one of the integer comparisons here.  Since SSE only has
9336   // GT and EQ comparisons for integer, swapping operands and multiple
9337   // operations may be required for some comparisons.
9338   unsigned Opc;
9339   bool Swap = false, Invert = false, FlipSigns = false;
9340
9341   switch (SetCCOpcode) {
9342   default: llvm_unreachable("Unexpected SETCC condition");
9343   case ISD::SETNE:  Invert = true;
9344   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9345   case ISD::SETLT:  Swap = true;
9346   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9347   case ISD::SETGE:  Swap = true;
9348   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9349   case ISD::SETULT: Swap = true;
9350   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9351   case ISD::SETUGE: Swap = true;
9352   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9353   }
9354   if (Swap)
9355     std::swap(Op0, Op1);
9356
9357   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9358   // bits of the inputs before performing those operations.
9359   if (FlipSigns) {
9360     EVT EltVT = VT.getVectorElementType();
9361     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9362                                       EltVT);
9363     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9364     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9365                                     SignBits.size());
9366     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9367     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9368   }
9369
9370   // Check that the operation in question is available (most are plain SSE2,
9371   // but PCMPGTQ and PCMPEQQ have different requirements).
9372   if (VT == MVT::v2i64) {
9373     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9374       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9375
9376       // First cast everything to the right type,
9377       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9378       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9379
9380       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9381       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9382       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9383
9384       // Create masks for only the low parts/high parts of the 64 bit integers.
9385       const int MaskHi[] = { 1, 1, 3, 3 };
9386       const int MaskLo[] = { 0, 0, 2, 2 };
9387       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9388       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9389       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9390
9391       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9392       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9393
9394       if (Invert)
9395         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9396
9397       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9398     }
9399
9400     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9401       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9402       // pcmpeqd + pshufd + pand.
9403       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9404
9405       // First cast everything to the right type,
9406       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9407       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9408
9409       // Do the compare.
9410       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9411
9412       // Make sure the lower and upper halves are both all-ones.
9413       const int Mask[] = { 1, 0, 3, 2 };
9414       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9415       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9416
9417       if (Invert)
9418         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9419
9420       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9421     }
9422   }
9423
9424   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9425
9426   // If the logical-not of the result is required, perform that now.
9427   if (Invert)
9428     Result = DAG.getNOT(dl, Result, VT);
9429
9430   return Result;
9431 }
9432
9433 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9434
9435   MVT VT = Op.getValueType().getSimpleVT();
9436
9437   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9438
9439   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9440   SDValue Op0 = Op.getOperand(0);
9441   SDValue Op1 = Op.getOperand(1);
9442   DebugLoc dl = Op.getDebugLoc();
9443   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9444
9445   // Optimize to BT if possible.
9446   // Lower (X & (1 << N)) == 0 to BT(X, N).
9447   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9448   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9449   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9450       Op1.getOpcode() == ISD::Constant &&
9451       cast<ConstantSDNode>(Op1)->isNullValue() &&
9452       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9453     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9454     if (NewSetCC.getNode())
9455       return NewSetCC;
9456   }
9457
9458   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9459   // these.
9460   if (Op1.getOpcode() == ISD::Constant &&
9461       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9462        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9463       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9464
9465     // If the input is a setcc, then reuse the input setcc or use a new one with
9466     // the inverted condition.
9467     if (Op0.getOpcode() == X86ISD::SETCC) {
9468       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9469       bool Invert = (CC == ISD::SETNE) ^
9470         cast<ConstantSDNode>(Op1)->isNullValue();
9471       if (!Invert) return Op0;
9472
9473       CCode = X86::GetOppositeBranchCondition(CCode);
9474       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9475                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9476     }
9477   }
9478
9479   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9480   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9481   if (X86CC == X86::COND_INVALID)
9482     return SDValue();
9483
9484   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9485   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9486   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9487                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9488 }
9489
9490 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9491 static bool isX86LogicalCmp(SDValue Op) {
9492   unsigned Opc = Op.getNode()->getOpcode();
9493   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9494       Opc == X86ISD::SAHF)
9495     return true;
9496   if (Op.getResNo() == 1 &&
9497       (Opc == X86ISD::ADD ||
9498        Opc == X86ISD::SUB ||
9499        Opc == X86ISD::ADC ||
9500        Opc == X86ISD::SBB ||
9501        Opc == X86ISD::SMUL ||
9502        Opc == X86ISD::UMUL ||
9503        Opc == X86ISD::INC ||
9504        Opc == X86ISD::DEC ||
9505        Opc == X86ISD::OR ||
9506        Opc == X86ISD::XOR ||
9507        Opc == X86ISD::AND))
9508     return true;
9509
9510   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9511     return true;
9512
9513   return false;
9514 }
9515
9516 static bool isZero(SDValue V) {
9517   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9518   return C && C->isNullValue();
9519 }
9520
9521 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9522   if (V.getOpcode() != ISD::TRUNCATE)
9523     return false;
9524
9525   SDValue VOp0 = V.getOperand(0);
9526   unsigned InBits = VOp0.getValueSizeInBits();
9527   unsigned Bits = V.getValueSizeInBits();
9528   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9529 }
9530
9531 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9532   bool addTest = true;
9533   SDValue Cond  = Op.getOperand(0);
9534   SDValue Op1 = Op.getOperand(1);
9535   SDValue Op2 = Op.getOperand(2);
9536   DebugLoc DL = Op.getDebugLoc();
9537   SDValue CC;
9538
9539   if (Cond.getOpcode() == ISD::SETCC) {
9540     SDValue NewCond = LowerSETCC(Cond, DAG);
9541     if (NewCond.getNode())
9542       Cond = NewCond;
9543   }
9544
9545   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9546   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9547   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9548   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9549   if (Cond.getOpcode() == X86ISD::SETCC &&
9550       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9551       isZero(Cond.getOperand(1).getOperand(1))) {
9552     SDValue Cmp = Cond.getOperand(1);
9553
9554     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9555
9556     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9557         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9558       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9559
9560       SDValue CmpOp0 = Cmp.getOperand(0);
9561       // Apply further optimizations for special cases
9562       // (select (x != 0), -1, 0) -> neg & sbb
9563       // (select (x == 0), 0, -1) -> neg & sbb
9564       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9565         if (YC->isNullValue() &&
9566             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9567           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9568           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9569                                     DAG.getConstant(0, CmpOp0.getValueType()),
9570                                     CmpOp0);
9571           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9572                                     DAG.getConstant(X86::COND_B, MVT::i8),
9573                                     SDValue(Neg.getNode(), 1));
9574           return Res;
9575         }
9576
9577       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9578                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9579       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9580
9581       SDValue Res =   // Res = 0 or -1.
9582         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9583                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9584
9585       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9586         Res = DAG.getNOT(DL, Res, Res.getValueType());
9587
9588       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9589       if (N2C == 0 || !N2C->isNullValue())
9590         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9591       return Res;
9592     }
9593   }
9594
9595   // Look past (and (setcc_carry (cmp ...)), 1).
9596   if (Cond.getOpcode() == ISD::AND &&
9597       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9598     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9599     if (C && C->getAPIntValue() == 1)
9600       Cond = Cond.getOperand(0);
9601   }
9602
9603   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9604   // setting operand in place of the X86ISD::SETCC.
9605   unsigned CondOpcode = Cond.getOpcode();
9606   if (CondOpcode == X86ISD::SETCC ||
9607       CondOpcode == X86ISD::SETCC_CARRY) {
9608     CC = Cond.getOperand(0);
9609
9610     SDValue Cmp = Cond.getOperand(1);
9611     unsigned Opc = Cmp.getOpcode();
9612     MVT VT = Op.getValueType().getSimpleVT();
9613
9614     bool IllegalFPCMov = false;
9615     if (VT.isFloatingPoint() && !VT.isVector() &&
9616         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9617       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9618
9619     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9620         Opc == X86ISD::BT) { // FIXME
9621       Cond = Cmp;
9622       addTest = false;
9623     }
9624   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9625              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9626              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9627               Cond.getOperand(0).getValueType() != MVT::i8)) {
9628     SDValue LHS = Cond.getOperand(0);
9629     SDValue RHS = Cond.getOperand(1);
9630     unsigned X86Opcode;
9631     unsigned X86Cond;
9632     SDVTList VTs;
9633     switch (CondOpcode) {
9634     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9635     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9636     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9637     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9638     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9639     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9640     default: llvm_unreachable("unexpected overflowing operator");
9641     }
9642     if (CondOpcode == ISD::UMULO)
9643       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9644                           MVT::i32);
9645     else
9646       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9647
9648     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9649
9650     if (CondOpcode == ISD::UMULO)
9651       Cond = X86Op.getValue(2);
9652     else
9653       Cond = X86Op.getValue(1);
9654
9655     CC = DAG.getConstant(X86Cond, MVT::i8);
9656     addTest = false;
9657   }
9658
9659   if (addTest) {
9660     // Look pass the truncate if the high bits are known zero.
9661     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9662         Cond = Cond.getOperand(0);
9663
9664     // We know the result of AND is compared against zero. Try to match
9665     // it to BT.
9666     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9667       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9668       if (NewSetCC.getNode()) {
9669         CC = NewSetCC.getOperand(0);
9670         Cond = NewSetCC.getOperand(1);
9671         addTest = false;
9672       }
9673     }
9674   }
9675
9676   if (addTest) {
9677     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9678     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9679   }
9680
9681   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9682   // a <  b ?  0 : -1 -> RES = setcc_carry
9683   // a >= b ? -1 :  0 -> RES = setcc_carry
9684   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9685   if (Cond.getOpcode() == X86ISD::SUB) {
9686     Cond = ConvertCmpIfNecessary(Cond, DAG);
9687     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9688
9689     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9690         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9691       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9692                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9693       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9694         return DAG.getNOT(DL, Res, Res.getValueType());
9695       return Res;
9696     }
9697   }
9698
9699   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9700   // widen the cmov and push the truncate through. This avoids introducing a new
9701   // branch during isel and doesn't add any extensions.
9702   if (Op.getValueType() == MVT::i8 &&
9703       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9704     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9705     if (T1.getValueType() == T2.getValueType() &&
9706         // Blacklist CopyFromReg to avoid partial register stalls.
9707         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9708       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9709       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9710       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9711     }
9712   }
9713
9714   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9715   // condition is true.
9716   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9717   SDValue Ops[] = { Op2, Op1, CC, Cond };
9718   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9719 }
9720
9721 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9722                                             SelectionDAG &DAG) const {
9723   MVT VT = Op->getValueType(0).getSimpleVT();
9724   SDValue In = Op->getOperand(0);
9725   MVT InVT = In.getValueType().getSimpleVT();
9726   DebugLoc dl = Op->getDebugLoc();
9727
9728   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9729       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9730     return SDValue();
9731
9732   if (Subtarget->hasInt256())
9733     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9734
9735   // Optimize vectors in AVX mode
9736   // Sign extend  v8i16 to v8i32 and
9737   //              v4i32 to v4i64
9738   //
9739   // Divide input vector into two parts
9740   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9741   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9742   // concat the vectors to original VT
9743
9744   unsigned NumElems = InVT.getVectorNumElements();
9745   SDValue Undef = DAG.getUNDEF(InVT);
9746
9747   SmallVector<int,8> ShufMask1(NumElems, -1);
9748   for (unsigned i = 0; i != NumElems/2; ++i)
9749     ShufMask1[i] = i;
9750
9751   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9752
9753   SmallVector<int,8> ShufMask2(NumElems, -1);
9754   for (unsigned i = 0; i != NumElems/2; ++i)
9755     ShufMask2[i] = i + NumElems/2;
9756
9757   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9758
9759   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9760                                 VT.getVectorNumElements()/2);
9761
9762   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9763   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9764
9765   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9766 }
9767
9768 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9769 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9770 // from the AND / OR.
9771 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9772   Opc = Op.getOpcode();
9773   if (Opc != ISD::OR && Opc != ISD::AND)
9774     return false;
9775   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9776           Op.getOperand(0).hasOneUse() &&
9777           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9778           Op.getOperand(1).hasOneUse());
9779 }
9780
9781 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9782 // 1 and that the SETCC node has a single use.
9783 static bool isXor1OfSetCC(SDValue Op) {
9784   if (Op.getOpcode() != ISD::XOR)
9785     return false;
9786   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9787   if (N1C && N1C->getAPIntValue() == 1) {
9788     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9789       Op.getOperand(0).hasOneUse();
9790   }
9791   return false;
9792 }
9793
9794 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9795   bool addTest = true;
9796   SDValue Chain = Op.getOperand(0);
9797   SDValue Cond  = Op.getOperand(1);
9798   SDValue Dest  = Op.getOperand(2);
9799   DebugLoc dl = Op.getDebugLoc();
9800   SDValue CC;
9801   bool Inverted = false;
9802
9803   if (Cond.getOpcode() == ISD::SETCC) {
9804     // Check for setcc([su]{add,sub,mul}o == 0).
9805     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9806         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9807         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9808         Cond.getOperand(0).getResNo() == 1 &&
9809         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9810          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9811          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9812          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9813          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9814          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9815       Inverted = true;
9816       Cond = Cond.getOperand(0);
9817     } else {
9818       SDValue NewCond = LowerSETCC(Cond, DAG);
9819       if (NewCond.getNode())
9820         Cond = NewCond;
9821     }
9822   }
9823 #if 0
9824   // FIXME: LowerXALUO doesn't handle these!!
9825   else if (Cond.getOpcode() == X86ISD::ADD  ||
9826            Cond.getOpcode() == X86ISD::SUB  ||
9827            Cond.getOpcode() == X86ISD::SMUL ||
9828            Cond.getOpcode() == X86ISD::UMUL)
9829     Cond = LowerXALUO(Cond, DAG);
9830 #endif
9831
9832   // Look pass (and (setcc_carry (cmp ...)), 1).
9833   if (Cond.getOpcode() == ISD::AND &&
9834       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9835     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9836     if (C && C->getAPIntValue() == 1)
9837       Cond = Cond.getOperand(0);
9838   }
9839
9840   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9841   // setting operand in place of the X86ISD::SETCC.
9842   unsigned CondOpcode = Cond.getOpcode();
9843   if (CondOpcode == X86ISD::SETCC ||
9844       CondOpcode == X86ISD::SETCC_CARRY) {
9845     CC = Cond.getOperand(0);
9846
9847     SDValue Cmp = Cond.getOperand(1);
9848     unsigned Opc = Cmp.getOpcode();
9849     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9850     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9851       Cond = Cmp;
9852       addTest = false;
9853     } else {
9854       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9855       default: break;
9856       case X86::COND_O:
9857       case X86::COND_B:
9858         // These can only come from an arithmetic instruction with overflow,
9859         // e.g. SADDO, UADDO.
9860         Cond = Cond.getNode()->getOperand(1);
9861         addTest = false;
9862         break;
9863       }
9864     }
9865   }
9866   CondOpcode = Cond.getOpcode();
9867   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9868       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9869       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9870        Cond.getOperand(0).getValueType() != MVT::i8)) {
9871     SDValue LHS = Cond.getOperand(0);
9872     SDValue RHS = Cond.getOperand(1);
9873     unsigned X86Opcode;
9874     unsigned X86Cond;
9875     SDVTList VTs;
9876     switch (CondOpcode) {
9877     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9878     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9879     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9880     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9881     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9882     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9883     default: llvm_unreachable("unexpected overflowing operator");
9884     }
9885     if (Inverted)
9886       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9887     if (CondOpcode == ISD::UMULO)
9888       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9889                           MVT::i32);
9890     else
9891       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9892
9893     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9894
9895     if (CondOpcode == ISD::UMULO)
9896       Cond = X86Op.getValue(2);
9897     else
9898       Cond = X86Op.getValue(1);
9899
9900     CC = DAG.getConstant(X86Cond, MVT::i8);
9901     addTest = false;
9902   } else {
9903     unsigned CondOpc;
9904     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9905       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9906       if (CondOpc == ISD::OR) {
9907         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9908         // two branches instead of an explicit OR instruction with a
9909         // separate test.
9910         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9911             isX86LogicalCmp(Cmp)) {
9912           CC = Cond.getOperand(0).getOperand(0);
9913           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9914                               Chain, Dest, CC, Cmp);
9915           CC = Cond.getOperand(1).getOperand(0);
9916           Cond = Cmp;
9917           addTest = false;
9918         }
9919       } else { // ISD::AND
9920         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9921         // two branches instead of an explicit AND instruction with a
9922         // separate test. However, we only do this if this block doesn't
9923         // have a fall-through edge, because this requires an explicit
9924         // jmp when the condition is false.
9925         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9926             isX86LogicalCmp(Cmp) &&
9927             Op.getNode()->hasOneUse()) {
9928           X86::CondCode CCode =
9929             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9930           CCode = X86::GetOppositeBranchCondition(CCode);
9931           CC = DAG.getConstant(CCode, MVT::i8);
9932           SDNode *User = *Op.getNode()->use_begin();
9933           // Look for an unconditional branch following this conditional branch.
9934           // We need this because we need to reverse the successors in order
9935           // to implement FCMP_OEQ.
9936           if (User->getOpcode() == ISD::BR) {
9937             SDValue FalseBB = User->getOperand(1);
9938             SDNode *NewBR =
9939               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9940             assert(NewBR == User);
9941             (void)NewBR;
9942             Dest = FalseBB;
9943
9944             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9945                                 Chain, Dest, CC, Cmp);
9946             X86::CondCode CCode =
9947               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9948             CCode = X86::GetOppositeBranchCondition(CCode);
9949             CC = DAG.getConstant(CCode, MVT::i8);
9950             Cond = Cmp;
9951             addTest = false;
9952           }
9953         }
9954       }
9955     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9956       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9957       // It should be transformed during dag combiner except when the condition
9958       // is set by a arithmetics with overflow node.
9959       X86::CondCode CCode =
9960         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9961       CCode = X86::GetOppositeBranchCondition(CCode);
9962       CC = DAG.getConstant(CCode, MVT::i8);
9963       Cond = Cond.getOperand(0).getOperand(1);
9964       addTest = false;
9965     } else if (Cond.getOpcode() == ISD::SETCC &&
9966                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9967       // For FCMP_OEQ, we can emit
9968       // two branches instead of an explicit AND instruction with a
9969       // separate test. However, we only do this if this block doesn't
9970       // have a fall-through edge, because this requires an explicit
9971       // jmp when the condition is false.
9972       if (Op.getNode()->hasOneUse()) {
9973         SDNode *User = *Op.getNode()->use_begin();
9974         // Look for an unconditional branch following this conditional branch.
9975         // We need this because we need to reverse the successors in order
9976         // to implement FCMP_OEQ.
9977         if (User->getOpcode() == ISD::BR) {
9978           SDValue FalseBB = User->getOperand(1);
9979           SDNode *NewBR =
9980             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9981           assert(NewBR == User);
9982           (void)NewBR;
9983           Dest = FalseBB;
9984
9985           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9986                                     Cond.getOperand(0), Cond.getOperand(1));
9987           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9988           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9989           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9990                               Chain, Dest, CC, Cmp);
9991           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9992           Cond = Cmp;
9993           addTest = false;
9994         }
9995       }
9996     } else if (Cond.getOpcode() == ISD::SETCC &&
9997                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9998       // For FCMP_UNE, we can emit
9999       // two branches instead of an explicit AND instruction with a
10000       // separate test. However, we only do this if this block doesn't
10001       // have a fall-through edge, because this requires an explicit
10002       // jmp when the condition is false.
10003       if (Op.getNode()->hasOneUse()) {
10004         SDNode *User = *Op.getNode()->use_begin();
10005         // Look for an unconditional branch following this conditional branch.
10006         // We need this because we need to reverse the successors in order
10007         // to implement FCMP_UNE.
10008         if (User->getOpcode() == ISD::BR) {
10009           SDValue FalseBB = User->getOperand(1);
10010           SDNode *NewBR =
10011             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10012           assert(NewBR == User);
10013           (void)NewBR;
10014
10015           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10016                                     Cond.getOperand(0), Cond.getOperand(1));
10017           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10018           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10019           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10020                               Chain, Dest, CC, Cmp);
10021           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10022           Cond = Cmp;
10023           addTest = false;
10024           Dest = FalseBB;
10025         }
10026       }
10027     }
10028   }
10029
10030   if (addTest) {
10031     // Look pass the truncate if the high bits are known zero.
10032     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10033         Cond = Cond.getOperand(0);
10034
10035     // We know the result of AND is compared against zero. Try to match
10036     // it to BT.
10037     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10038       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10039       if (NewSetCC.getNode()) {
10040         CC = NewSetCC.getOperand(0);
10041         Cond = NewSetCC.getOperand(1);
10042         addTest = false;
10043       }
10044     }
10045   }
10046
10047   if (addTest) {
10048     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10049     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10050   }
10051   Cond = ConvertCmpIfNecessary(Cond, DAG);
10052   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10053                      Chain, Dest, CC, Cond);
10054 }
10055
10056 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10057 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10058 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10059 // that the guard pages used by the OS virtual memory manager are allocated in
10060 // correct sequence.
10061 SDValue
10062 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10063                                            SelectionDAG &DAG) const {
10064   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10065           getTargetMachine().Options.EnableSegmentedStacks) &&
10066          "This should be used only on Windows targets or when segmented stacks "
10067          "are being used");
10068   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10069   DebugLoc dl = Op.getDebugLoc();
10070
10071   // Get the inputs.
10072   SDValue Chain = Op.getOperand(0);
10073   SDValue Size  = Op.getOperand(1);
10074   // FIXME: Ensure alignment here
10075
10076   bool Is64Bit = Subtarget->is64Bit();
10077   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10078
10079   if (getTargetMachine().Options.EnableSegmentedStacks) {
10080     MachineFunction &MF = DAG.getMachineFunction();
10081     MachineRegisterInfo &MRI = MF.getRegInfo();
10082
10083     if (Is64Bit) {
10084       // The 64 bit implementation of segmented stacks needs to clobber both r10
10085       // r11. This makes it impossible to use it along with nested parameters.
10086       const Function *F = MF.getFunction();
10087
10088       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10089            I != E; ++I)
10090         if (I->hasNestAttr())
10091           report_fatal_error("Cannot use segmented stacks with functions that "
10092                              "have nested arguments.");
10093     }
10094
10095     const TargetRegisterClass *AddrRegClass =
10096       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10097     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10098     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10099     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10100                                 DAG.getRegister(Vreg, SPTy));
10101     SDValue Ops1[2] = { Value, Chain };
10102     return DAG.getMergeValues(Ops1, 2, dl);
10103   } else {
10104     SDValue Flag;
10105     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10106
10107     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10108     Flag = Chain.getValue(1);
10109     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10110
10111     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10112     Flag = Chain.getValue(1);
10113
10114     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10115                                SPTy).getValue(1);
10116
10117     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10118     return DAG.getMergeValues(Ops1, 2, dl);
10119   }
10120 }
10121
10122 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10123   MachineFunction &MF = DAG.getMachineFunction();
10124   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10125
10126   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10127   DebugLoc DL = Op.getDebugLoc();
10128
10129   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10130     // vastart just stores the address of the VarArgsFrameIndex slot into the
10131     // memory location argument.
10132     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10133                                    getPointerTy());
10134     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10135                         MachinePointerInfo(SV), false, false, 0);
10136   }
10137
10138   // __va_list_tag:
10139   //   gp_offset         (0 - 6 * 8)
10140   //   fp_offset         (48 - 48 + 8 * 16)
10141   //   overflow_arg_area (point to parameters coming in memory).
10142   //   reg_save_area
10143   SmallVector<SDValue, 8> MemOps;
10144   SDValue FIN = Op.getOperand(1);
10145   // Store gp_offset
10146   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10147                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10148                                                MVT::i32),
10149                                FIN, MachinePointerInfo(SV), false, false, 0);
10150   MemOps.push_back(Store);
10151
10152   // Store fp_offset
10153   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10154                     FIN, DAG.getIntPtrConstant(4));
10155   Store = DAG.getStore(Op.getOperand(0), DL,
10156                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10157                                        MVT::i32),
10158                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10159   MemOps.push_back(Store);
10160
10161   // Store ptr to overflow_arg_area
10162   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10163                     FIN, DAG.getIntPtrConstant(4));
10164   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10165                                     getPointerTy());
10166   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10167                        MachinePointerInfo(SV, 8),
10168                        false, false, 0);
10169   MemOps.push_back(Store);
10170
10171   // Store ptr to reg_save_area.
10172   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10173                     FIN, DAG.getIntPtrConstant(8));
10174   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10175                                     getPointerTy());
10176   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10177                        MachinePointerInfo(SV, 16), false, false, 0);
10178   MemOps.push_back(Store);
10179   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10180                      &MemOps[0], MemOps.size());
10181 }
10182
10183 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10184   assert(Subtarget->is64Bit() &&
10185          "LowerVAARG only handles 64-bit va_arg!");
10186   assert((Subtarget->isTargetLinux() ||
10187           Subtarget->isTargetDarwin()) &&
10188           "Unhandled target in LowerVAARG");
10189   assert(Op.getNode()->getNumOperands() == 4);
10190   SDValue Chain = Op.getOperand(0);
10191   SDValue SrcPtr = Op.getOperand(1);
10192   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10193   unsigned Align = Op.getConstantOperandVal(3);
10194   DebugLoc dl = Op.getDebugLoc();
10195
10196   EVT ArgVT = Op.getNode()->getValueType(0);
10197   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10198   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10199   uint8_t ArgMode;
10200
10201   // Decide which area this value should be read from.
10202   // TODO: Implement the AMD64 ABI in its entirety. This simple
10203   // selection mechanism works only for the basic types.
10204   if (ArgVT == MVT::f80) {
10205     llvm_unreachable("va_arg for f80 not yet implemented");
10206   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10207     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10208   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10209     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10210   } else {
10211     llvm_unreachable("Unhandled argument type in LowerVAARG");
10212   }
10213
10214   if (ArgMode == 2) {
10215     // Sanity Check: Make sure using fp_offset makes sense.
10216     assert(!getTargetMachine().Options.UseSoftFloat &&
10217            !(DAG.getMachineFunction()
10218                 .getFunction()->getAttributes()
10219                 .hasAttribute(AttributeSet::FunctionIndex,
10220                               Attribute::NoImplicitFloat)) &&
10221            Subtarget->hasSSE1());
10222   }
10223
10224   // Insert VAARG_64 node into the DAG
10225   // VAARG_64 returns two values: Variable Argument Address, Chain
10226   SmallVector<SDValue, 11> InstOps;
10227   InstOps.push_back(Chain);
10228   InstOps.push_back(SrcPtr);
10229   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10230   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10231   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10232   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10233   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10234                                           VTs, &InstOps[0], InstOps.size(),
10235                                           MVT::i64,
10236                                           MachinePointerInfo(SV),
10237                                           /*Align=*/0,
10238                                           /*Volatile=*/false,
10239                                           /*ReadMem=*/true,
10240                                           /*WriteMem=*/true);
10241   Chain = VAARG.getValue(1);
10242
10243   // Load the next argument and return it
10244   return DAG.getLoad(ArgVT, dl,
10245                      Chain,
10246                      VAARG,
10247                      MachinePointerInfo(),
10248                      false, false, false, 0);
10249 }
10250
10251 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10252                            SelectionDAG &DAG) {
10253   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10254   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10255   SDValue Chain = Op.getOperand(0);
10256   SDValue DstPtr = Op.getOperand(1);
10257   SDValue SrcPtr = Op.getOperand(2);
10258   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10259   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10260   DebugLoc DL = Op.getDebugLoc();
10261
10262   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10263                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10264                        false,
10265                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10266 }
10267
10268 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10269 // may or may not be a constant. Takes immediate version of shift as input.
10270 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10271                                    SDValue SrcOp, SDValue ShAmt,
10272                                    SelectionDAG &DAG) {
10273   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10274
10275   if (isa<ConstantSDNode>(ShAmt)) {
10276     // Constant may be a TargetConstant. Use a regular constant.
10277     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10278     switch (Opc) {
10279       default: llvm_unreachable("Unknown target vector shift node");
10280       case X86ISD::VSHLI:
10281       case X86ISD::VSRLI:
10282       case X86ISD::VSRAI:
10283         return DAG.getNode(Opc, dl, VT, SrcOp,
10284                            DAG.getConstant(ShiftAmt, MVT::i32));
10285     }
10286   }
10287
10288   // Change opcode to non-immediate version
10289   switch (Opc) {
10290     default: llvm_unreachable("Unknown target vector shift node");
10291     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10292     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10293     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10294   }
10295
10296   // Need to build a vector containing shift amount
10297   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10298   SDValue ShOps[4];
10299   ShOps[0] = ShAmt;
10300   ShOps[1] = DAG.getConstant(0, MVT::i32);
10301   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10302   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10303
10304   // The return type has to be a 128-bit type with the same element
10305   // type as the input type.
10306   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10307   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10308
10309   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10310   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10311 }
10312
10313 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10314   DebugLoc dl = Op.getDebugLoc();
10315   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10316   switch (IntNo) {
10317   default: return SDValue();    // Don't custom lower most intrinsics.
10318   // Comparison intrinsics.
10319   case Intrinsic::x86_sse_comieq_ss:
10320   case Intrinsic::x86_sse_comilt_ss:
10321   case Intrinsic::x86_sse_comile_ss:
10322   case Intrinsic::x86_sse_comigt_ss:
10323   case Intrinsic::x86_sse_comige_ss:
10324   case Intrinsic::x86_sse_comineq_ss:
10325   case Intrinsic::x86_sse_ucomieq_ss:
10326   case Intrinsic::x86_sse_ucomilt_ss:
10327   case Intrinsic::x86_sse_ucomile_ss:
10328   case Intrinsic::x86_sse_ucomigt_ss:
10329   case Intrinsic::x86_sse_ucomige_ss:
10330   case Intrinsic::x86_sse_ucomineq_ss:
10331   case Intrinsic::x86_sse2_comieq_sd:
10332   case Intrinsic::x86_sse2_comilt_sd:
10333   case Intrinsic::x86_sse2_comile_sd:
10334   case Intrinsic::x86_sse2_comigt_sd:
10335   case Intrinsic::x86_sse2_comige_sd:
10336   case Intrinsic::x86_sse2_comineq_sd:
10337   case Intrinsic::x86_sse2_ucomieq_sd:
10338   case Intrinsic::x86_sse2_ucomilt_sd:
10339   case Intrinsic::x86_sse2_ucomile_sd:
10340   case Intrinsic::x86_sse2_ucomigt_sd:
10341   case Intrinsic::x86_sse2_ucomige_sd:
10342   case Intrinsic::x86_sse2_ucomineq_sd: {
10343     unsigned Opc;
10344     ISD::CondCode CC;
10345     switch (IntNo) {
10346     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10347     case Intrinsic::x86_sse_comieq_ss:
10348     case Intrinsic::x86_sse2_comieq_sd:
10349       Opc = X86ISD::COMI;
10350       CC = ISD::SETEQ;
10351       break;
10352     case Intrinsic::x86_sse_comilt_ss:
10353     case Intrinsic::x86_sse2_comilt_sd:
10354       Opc = X86ISD::COMI;
10355       CC = ISD::SETLT;
10356       break;
10357     case Intrinsic::x86_sse_comile_ss:
10358     case Intrinsic::x86_sse2_comile_sd:
10359       Opc = X86ISD::COMI;
10360       CC = ISD::SETLE;
10361       break;
10362     case Intrinsic::x86_sse_comigt_ss:
10363     case Intrinsic::x86_sse2_comigt_sd:
10364       Opc = X86ISD::COMI;
10365       CC = ISD::SETGT;
10366       break;
10367     case Intrinsic::x86_sse_comige_ss:
10368     case Intrinsic::x86_sse2_comige_sd:
10369       Opc = X86ISD::COMI;
10370       CC = ISD::SETGE;
10371       break;
10372     case Intrinsic::x86_sse_comineq_ss:
10373     case Intrinsic::x86_sse2_comineq_sd:
10374       Opc = X86ISD::COMI;
10375       CC = ISD::SETNE;
10376       break;
10377     case Intrinsic::x86_sse_ucomieq_ss:
10378     case Intrinsic::x86_sse2_ucomieq_sd:
10379       Opc = X86ISD::UCOMI;
10380       CC = ISD::SETEQ;
10381       break;
10382     case Intrinsic::x86_sse_ucomilt_ss:
10383     case Intrinsic::x86_sse2_ucomilt_sd:
10384       Opc = X86ISD::UCOMI;
10385       CC = ISD::SETLT;
10386       break;
10387     case Intrinsic::x86_sse_ucomile_ss:
10388     case Intrinsic::x86_sse2_ucomile_sd:
10389       Opc = X86ISD::UCOMI;
10390       CC = ISD::SETLE;
10391       break;
10392     case Intrinsic::x86_sse_ucomigt_ss:
10393     case Intrinsic::x86_sse2_ucomigt_sd:
10394       Opc = X86ISD::UCOMI;
10395       CC = ISD::SETGT;
10396       break;
10397     case Intrinsic::x86_sse_ucomige_ss:
10398     case Intrinsic::x86_sse2_ucomige_sd:
10399       Opc = X86ISD::UCOMI;
10400       CC = ISD::SETGE;
10401       break;
10402     case Intrinsic::x86_sse_ucomineq_ss:
10403     case Intrinsic::x86_sse2_ucomineq_sd:
10404       Opc = X86ISD::UCOMI;
10405       CC = ISD::SETNE;
10406       break;
10407     }
10408
10409     SDValue LHS = Op.getOperand(1);
10410     SDValue RHS = Op.getOperand(2);
10411     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10412     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10413     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10414     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10415                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10416     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10417   }
10418
10419   // Arithmetic intrinsics.
10420   case Intrinsic::x86_sse2_pmulu_dq:
10421   case Intrinsic::x86_avx2_pmulu_dq:
10422     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10423                        Op.getOperand(1), Op.getOperand(2));
10424
10425   // SSE2/AVX2 sub with unsigned saturation intrinsics
10426   case Intrinsic::x86_sse2_psubus_b:
10427   case Intrinsic::x86_sse2_psubus_w:
10428   case Intrinsic::x86_avx2_psubus_b:
10429   case Intrinsic::x86_avx2_psubus_w:
10430     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10431                        Op.getOperand(1), Op.getOperand(2));
10432
10433   // SSE3/AVX horizontal add/sub intrinsics
10434   case Intrinsic::x86_sse3_hadd_ps:
10435   case Intrinsic::x86_sse3_hadd_pd:
10436   case Intrinsic::x86_avx_hadd_ps_256:
10437   case Intrinsic::x86_avx_hadd_pd_256:
10438   case Intrinsic::x86_sse3_hsub_ps:
10439   case Intrinsic::x86_sse3_hsub_pd:
10440   case Intrinsic::x86_avx_hsub_ps_256:
10441   case Intrinsic::x86_avx_hsub_pd_256:
10442   case Intrinsic::x86_ssse3_phadd_w_128:
10443   case Intrinsic::x86_ssse3_phadd_d_128:
10444   case Intrinsic::x86_avx2_phadd_w:
10445   case Intrinsic::x86_avx2_phadd_d:
10446   case Intrinsic::x86_ssse3_phsub_w_128:
10447   case Intrinsic::x86_ssse3_phsub_d_128:
10448   case Intrinsic::x86_avx2_phsub_w:
10449   case Intrinsic::x86_avx2_phsub_d: {
10450     unsigned Opcode;
10451     switch (IntNo) {
10452     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10453     case Intrinsic::x86_sse3_hadd_ps:
10454     case Intrinsic::x86_sse3_hadd_pd:
10455     case Intrinsic::x86_avx_hadd_ps_256:
10456     case Intrinsic::x86_avx_hadd_pd_256:
10457       Opcode = X86ISD::FHADD;
10458       break;
10459     case Intrinsic::x86_sse3_hsub_ps:
10460     case Intrinsic::x86_sse3_hsub_pd:
10461     case Intrinsic::x86_avx_hsub_ps_256:
10462     case Intrinsic::x86_avx_hsub_pd_256:
10463       Opcode = X86ISD::FHSUB;
10464       break;
10465     case Intrinsic::x86_ssse3_phadd_w_128:
10466     case Intrinsic::x86_ssse3_phadd_d_128:
10467     case Intrinsic::x86_avx2_phadd_w:
10468     case Intrinsic::x86_avx2_phadd_d:
10469       Opcode = X86ISD::HADD;
10470       break;
10471     case Intrinsic::x86_ssse3_phsub_w_128:
10472     case Intrinsic::x86_ssse3_phsub_d_128:
10473     case Intrinsic::x86_avx2_phsub_w:
10474     case Intrinsic::x86_avx2_phsub_d:
10475       Opcode = X86ISD::HSUB;
10476       break;
10477     }
10478     return DAG.getNode(Opcode, dl, Op.getValueType(),
10479                        Op.getOperand(1), Op.getOperand(2));
10480   }
10481
10482   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10483   case Intrinsic::x86_sse2_pmaxu_b:
10484   case Intrinsic::x86_sse41_pmaxuw:
10485   case Intrinsic::x86_sse41_pmaxud:
10486   case Intrinsic::x86_avx2_pmaxu_b:
10487   case Intrinsic::x86_avx2_pmaxu_w:
10488   case Intrinsic::x86_avx2_pmaxu_d:
10489   case Intrinsic::x86_sse2_pminu_b:
10490   case Intrinsic::x86_sse41_pminuw:
10491   case Intrinsic::x86_sse41_pminud:
10492   case Intrinsic::x86_avx2_pminu_b:
10493   case Intrinsic::x86_avx2_pminu_w:
10494   case Intrinsic::x86_avx2_pminu_d:
10495   case Intrinsic::x86_sse41_pmaxsb:
10496   case Intrinsic::x86_sse2_pmaxs_w:
10497   case Intrinsic::x86_sse41_pmaxsd:
10498   case Intrinsic::x86_avx2_pmaxs_b:
10499   case Intrinsic::x86_avx2_pmaxs_w:
10500   case Intrinsic::x86_avx2_pmaxs_d:
10501   case Intrinsic::x86_sse41_pminsb:
10502   case Intrinsic::x86_sse2_pmins_w:
10503   case Intrinsic::x86_sse41_pminsd:
10504   case Intrinsic::x86_avx2_pmins_b:
10505   case Intrinsic::x86_avx2_pmins_w:
10506   case Intrinsic::x86_avx2_pmins_d: {
10507     unsigned Opcode;
10508     switch (IntNo) {
10509     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10510     case Intrinsic::x86_sse2_pmaxu_b:
10511     case Intrinsic::x86_sse41_pmaxuw:
10512     case Intrinsic::x86_sse41_pmaxud:
10513     case Intrinsic::x86_avx2_pmaxu_b:
10514     case Intrinsic::x86_avx2_pmaxu_w:
10515     case Intrinsic::x86_avx2_pmaxu_d:
10516       Opcode = X86ISD::UMAX;
10517       break;
10518     case Intrinsic::x86_sse2_pminu_b:
10519     case Intrinsic::x86_sse41_pminuw:
10520     case Intrinsic::x86_sse41_pminud:
10521     case Intrinsic::x86_avx2_pminu_b:
10522     case Intrinsic::x86_avx2_pminu_w:
10523     case Intrinsic::x86_avx2_pminu_d:
10524       Opcode = X86ISD::UMIN;
10525       break;
10526     case Intrinsic::x86_sse41_pmaxsb:
10527     case Intrinsic::x86_sse2_pmaxs_w:
10528     case Intrinsic::x86_sse41_pmaxsd:
10529     case Intrinsic::x86_avx2_pmaxs_b:
10530     case Intrinsic::x86_avx2_pmaxs_w:
10531     case Intrinsic::x86_avx2_pmaxs_d:
10532       Opcode = X86ISD::SMAX;
10533       break;
10534     case Intrinsic::x86_sse41_pminsb:
10535     case Intrinsic::x86_sse2_pmins_w:
10536     case Intrinsic::x86_sse41_pminsd:
10537     case Intrinsic::x86_avx2_pmins_b:
10538     case Intrinsic::x86_avx2_pmins_w:
10539     case Intrinsic::x86_avx2_pmins_d:
10540       Opcode = X86ISD::SMIN;
10541       break;
10542     }
10543     return DAG.getNode(Opcode, dl, Op.getValueType(),
10544                        Op.getOperand(1), Op.getOperand(2));
10545   }
10546
10547   // SSE/SSE2/AVX floating point max/min intrinsics.
10548   case Intrinsic::x86_sse_max_ps:
10549   case Intrinsic::x86_sse2_max_pd:
10550   case Intrinsic::x86_avx_max_ps_256:
10551   case Intrinsic::x86_avx_max_pd_256:
10552   case Intrinsic::x86_sse_min_ps:
10553   case Intrinsic::x86_sse2_min_pd:
10554   case Intrinsic::x86_avx_min_ps_256:
10555   case Intrinsic::x86_avx_min_pd_256: {
10556     unsigned Opcode;
10557     switch (IntNo) {
10558     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10559     case Intrinsic::x86_sse_max_ps:
10560     case Intrinsic::x86_sse2_max_pd:
10561     case Intrinsic::x86_avx_max_ps_256:
10562     case Intrinsic::x86_avx_max_pd_256:
10563       Opcode = X86ISD::FMAX;
10564       break;
10565     case Intrinsic::x86_sse_min_ps:
10566     case Intrinsic::x86_sse2_min_pd:
10567     case Intrinsic::x86_avx_min_ps_256:
10568     case Intrinsic::x86_avx_min_pd_256:
10569       Opcode = X86ISD::FMIN;
10570       break;
10571     }
10572     return DAG.getNode(Opcode, dl, Op.getValueType(),
10573                        Op.getOperand(1), Op.getOperand(2));
10574   }
10575
10576   // AVX2 variable shift intrinsics
10577   case Intrinsic::x86_avx2_psllv_d:
10578   case Intrinsic::x86_avx2_psllv_q:
10579   case Intrinsic::x86_avx2_psllv_d_256:
10580   case Intrinsic::x86_avx2_psllv_q_256:
10581   case Intrinsic::x86_avx2_psrlv_d:
10582   case Intrinsic::x86_avx2_psrlv_q:
10583   case Intrinsic::x86_avx2_psrlv_d_256:
10584   case Intrinsic::x86_avx2_psrlv_q_256:
10585   case Intrinsic::x86_avx2_psrav_d:
10586   case Intrinsic::x86_avx2_psrav_d_256: {
10587     unsigned Opcode;
10588     switch (IntNo) {
10589     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10590     case Intrinsic::x86_avx2_psllv_d:
10591     case Intrinsic::x86_avx2_psllv_q:
10592     case Intrinsic::x86_avx2_psllv_d_256:
10593     case Intrinsic::x86_avx2_psllv_q_256:
10594       Opcode = ISD::SHL;
10595       break;
10596     case Intrinsic::x86_avx2_psrlv_d:
10597     case Intrinsic::x86_avx2_psrlv_q:
10598     case Intrinsic::x86_avx2_psrlv_d_256:
10599     case Intrinsic::x86_avx2_psrlv_q_256:
10600       Opcode = ISD::SRL;
10601       break;
10602     case Intrinsic::x86_avx2_psrav_d:
10603     case Intrinsic::x86_avx2_psrav_d_256:
10604       Opcode = ISD::SRA;
10605       break;
10606     }
10607     return DAG.getNode(Opcode, dl, Op.getValueType(),
10608                        Op.getOperand(1), Op.getOperand(2));
10609   }
10610
10611   case Intrinsic::x86_ssse3_pshuf_b_128:
10612   case Intrinsic::x86_avx2_pshuf_b:
10613     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10614                        Op.getOperand(1), Op.getOperand(2));
10615
10616   case Intrinsic::x86_ssse3_psign_b_128:
10617   case Intrinsic::x86_ssse3_psign_w_128:
10618   case Intrinsic::x86_ssse3_psign_d_128:
10619   case Intrinsic::x86_avx2_psign_b:
10620   case Intrinsic::x86_avx2_psign_w:
10621   case Intrinsic::x86_avx2_psign_d:
10622     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10623                        Op.getOperand(1), Op.getOperand(2));
10624
10625   case Intrinsic::x86_sse41_insertps:
10626     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10627                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10628
10629   case Intrinsic::x86_avx_vperm2f128_ps_256:
10630   case Intrinsic::x86_avx_vperm2f128_pd_256:
10631   case Intrinsic::x86_avx_vperm2f128_si_256:
10632   case Intrinsic::x86_avx2_vperm2i128:
10633     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10634                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10635
10636   case Intrinsic::x86_avx2_permd:
10637   case Intrinsic::x86_avx2_permps:
10638     // Operands intentionally swapped. Mask is last operand to intrinsic,
10639     // but second operand for node/intruction.
10640     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10641                        Op.getOperand(2), Op.getOperand(1));
10642
10643   case Intrinsic::x86_sse_sqrt_ps:
10644   case Intrinsic::x86_sse2_sqrt_pd:
10645   case Intrinsic::x86_avx_sqrt_ps_256:
10646   case Intrinsic::x86_avx_sqrt_pd_256:
10647     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10648
10649   // ptest and testp intrinsics. The intrinsic these come from are designed to
10650   // return an integer value, not just an instruction so lower it to the ptest
10651   // or testp pattern and a setcc for the result.
10652   case Intrinsic::x86_sse41_ptestz:
10653   case Intrinsic::x86_sse41_ptestc:
10654   case Intrinsic::x86_sse41_ptestnzc:
10655   case Intrinsic::x86_avx_ptestz_256:
10656   case Intrinsic::x86_avx_ptestc_256:
10657   case Intrinsic::x86_avx_ptestnzc_256:
10658   case Intrinsic::x86_avx_vtestz_ps:
10659   case Intrinsic::x86_avx_vtestc_ps:
10660   case Intrinsic::x86_avx_vtestnzc_ps:
10661   case Intrinsic::x86_avx_vtestz_pd:
10662   case Intrinsic::x86_avx_vtestc_pd:
10663   case Intrinsic::x86_avx_vtestnzc_pd:
10664   case Intrinsic::x86_avx_vtestz_ps_256:
10665   case Intrinsic::x86_avx_vtestc_ps_256:
10666   case Intrinsic::x86_avx_vtestnzc_ps_256:
10667   case Intrinsic::x86_avx_vtestz_pd_256:
10668   case Intrinsic::x86_avx_vtestc_pd_256:
10669   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10670     bool IsTestPacked = false;
10671     unsigned X86CC;
10672     switch (IntNo) {
10673     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10674     case Intrinsic::x86_avx_vtestz_ps:
10675     case Intrinsic::x86_avx_vtestz_pd:
10676     case Intrinsic::x86_avx_vtestz_ps_256:
10677     case Intrinsic::x86_avx_vtestz_pd_256:
10678       IsTestPacked = true; // Fallthrough
10679     case Intrinsic::x86_sse41_ptestz:
10680     case Intrinsic::x86_avx_ptestz_256:
10681       // ZF = 1
10682       X86CC = X86::COND_E;
10683       break;
10684     case Intrinsic::x86_avx_vtestc_ps:
10685     case Intrinsic::x86_avx_vtestc_pd:
10686     case Intrinsic::x86_avx_vtestc_ps_256:
10687     case Intrinsic::x86_avx_vtestc_pd_256:
10688       IsTestPacked = true; // Fallthrough
10689     case Intrinsic::x86_sse41_ptestc:
10690     case Intrinsic::x86_avx_ptestc_256:
10691       // CF = 1
10692       X86CC = X86::COND_B;
10693       break;
10694     case Intrinsic::x86_avx_vtestnzc_ps:
10695     case Intrinsic::x86_avx_vtestnzc_pd:
10696     case Intrinsic::x86_avx_vtestnzc_ps_256:
10697     case Intrinsic::x86_avx_vtestnzc_pd_256:
10698       IsTestPacked = true; // Fallthrough
10699     case Intrinsic::x86_sse41_ptestnzc:
10700     case Intrinsic::x86_avx_ptestnzc_256:
10701       // ZF and CF = 0
10702       X86CC = X86::COND_A;
10703       break;
10704     }
10705
10706     SDValue LHS = Op.getOperand(1);
10707     SDValue RHS = Op.getOperand(2);
10708     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10709     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10710     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10711     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10712     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10713   }
10714
10715   // SSE/AVX shift intrinsics
10716   case Intrinsic::x86_sse2_psll_w:
10717   case Intrinsic::x86_sse2_psll_d:
10718   case Intrinsic::x86_sse2_psll_q:
10719   case Intrinsic::x86_avx2_psll_w:
10720   case Intrinsic::x86_avx2_psll_d:
10721   case Intrinsic::x86_avx2_psll_q:
10722   case Intrinsic::x86_sse2_psrl_w:
10723   case Intrinsic::x86_sse2_psrl_d:
10724   case Intrinsic::x86_sse2_psrl_q:
10725   case Intrinsic::x86_avx2_psrl_w:
10726   case Intrinsic::x86_avx2_psrl_d:
10727   case Intrinsic::x86_avx2_psrl_q:
10728   case Intrinsic::x86_sse2_psra_w:
10729   case Intrinsic::x86_sse2_psra_d:
10730   case Intrinsic::x86_avx2_psra_w:
10731   case Intrinsic::x86_avx2_psra_d: {
10732     unsigned Opcode;
10733     switch (IntNo) {
10734     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10735     case Intrinsic::x86_sse2_psll_w:
10736     case Intrinsic::x86_sse2_psll_d:
10737     case Intrinsic::x86_sse2_psll_q:
10738     case Intrinsic::x86_avx2_psll_w:
10739     case Intrinsic::x86_avx2_psll_d:
10740     case Intrinsic::x86_avx2_psll_q:
10741       Opcode = X86ISD::VSHL;
10742       break;
10743     case Intrinsic::x86_sse2_psrl_w:
10744     case Intrinsic::x86_sse2_psrl_d:
10745     case Intrinsic::x86_sse2_psrl_q:
10746     case Intrinsic::x86_avx2_psrl_w:
10747     case Intrinsic::x86_avx2_psrl_d:
10748     case Intrinsic::x86_avx2_psrl_q:
10749       Opcode = X86ISD::VSRL;
10750       break;
10751     case Intrinsic::x86_sse2_psra_w:
10752     case Intrinsic::x86_sse2_psra_d:
10753     case Intrinsic::x86_avx2_psra_w:
10754     case Intrinsic::x86_avx2_psra_d:
10755       Opcode = X86ISD::VSRA;
10756       break;
10757     }
10758     return DAG.getNode(Opcode, dl, Op.getValueType(),
10759                        Op.getOperand(1), Op.getOperand(2));
10760   }
10761
10762   // SSE/AVX immediate shift intrinsics
10763   case Intrinsic::x86_sse2_pslli_w:
10764   case Intrinsic::x86_sse2_pslli_d:
10765   case Intrinsic::x86_sse2_pslli_q:
10766   case Intrinsic::x86_avx2_pslli_w:
10767   case Intrinsic::x86_avx2_pslli_d:
10768   case Intrinsic::x86_avx2_pslli_q:
10769   case Intrinsic::x86_sse2_psrli_w:
10770   case Intrinsic::x86_sse2_psrli_d:
10771   case Intrinsic::x86_sse2_psrli_q:
10772   case Intrinsic::x86_avx2_psrli_w:
10773   case Intrinsic::x86_avx2_psrli_d:
10774   case Intrinsic::x86_avx2_psrli_q:
10775   case Intrinsic::x86_sse2_psrai_w:
10776   case Intrinsic::x86_sse2_psrai_d:
10777   case Intrinsic::x86_avx2_psrai_w:
10778   case Intrinsic::x86_avx2_psrai_d: {
10779     unsigned Opcode;
10780     switch (IntNo) {
10781     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10782     case Intrinsic::x86_sse2_pslli_w:
10783     case Intrinsic::x86_sse2_pslli_d:
10784     case Intrinsic::x86_sse2_pslli_q:
10785     case Intrinsic::x86_avx2_pslli_w:
10786     case Intrinsic::x86_avx2_pslli_d:
10787     case Intrinsic::x86_avx2_pslli_q:
10788       Opcode = X86ISD::VSHLI;
10789       break;
10790     case Intrinsic::x86_sse2_psrli_w:
10791     case Intrinsic::x86_sse2_psrli_d:
10792     case Intrinsic::x86_sse2_psrli_q:
10793     case Intrinsic::x86_avx2_psrli_w:
10794     case Intrinsic::x86_avx2_psrli_d:
10795     case Intrinsic::x86_avx2_psrli_q:
10796       Opcode = X86ISD::VSRLI;
10797       break;
10798     case Intrinsic::x86_sse2_psrai_w:
10799     case Intrinsic::x86_sse2_psrai_d:
10800     case Intrinsic::x86_avx2_psrai_w:
10801     case Intrinsic::x86_avx2_psrai_d:
10802       Opcode = X86ISD::VSRAI;
10803       break;
10804     }
10805     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10806                                Op.getOperand(1), Op.getOperand(2), DAG);
10807   }
10808
10809   case Intrinsic::x86_sse42_pcmpistria128:
10810   case Intrinsic::x86_sse42_pcmpestria128:
10811   case Intrinsic::x86_sse42_pcmpistric128:
10812   case Intrinsic::x86_sse42_pcmpestric128:
10813   case Intrinsic::x86_sse42_pcmpistrio128:
10814   case Intrinsic::x86_sse42_pcmpestrio128:
10815   case Intrinsic::x86_sse42_pcmpistris128:
10816   case Intrinsic::x86_sse42_pcmpestris128:
10817   case Intrinsic::x86_sse42_pcmpistriz128:
10818   case Intrinsic::x86_sse42_pcmpestriz128: {
10819     unsigned Opcode;
10820     unsigned X86CC;
10821     switch (IntNo) {
10822     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10823     case Intrinsic::x86_sse42_pcmpistria128:
10824       Opcode = X86ISD::PCMPISTRI;
10825       X86CC = X86::COND_A;
10826       break;
10827     case Intrinsic::x86_sse42_pcmpestria128:
10828       Opcode = X86ISD::PCMPESTRI;
10829       X86CC = X86::COND_A;
10830       break;
10831     case Intrinsic::x86_sse42_pcmpistric128:
10832       Opcode = X86ISD::PCMPISTRI;
10833       X86CC = X86::COND_B;
10834       break;
10835     case Intrinsic::x86_sse42_pcmpestric128:
10836       Opcode = X86ISD::PCMPESTRI;
10837       X86CC = X86::COND_B;
10838       break;
10839     case Intrinsic::x86_sse42_pcmpistrio128:
10840       Opcode = X86ISD::PCMPISTRI;
10841       X86CC = X86::COND_O;
10842       break;
10843     case Intrinsic::x86_sse42_pcmpestrio128:
10844       Opcode = X86ISD::PCMPESTRI;
10845       X86CC = X86::COND_O;
10846       break;
10847     case Intrinsic::x86_sse42_pcmpistris128:
10848       Opcode = X86ISD::PCMPISTRI;
10849       X86CC = X86::COND_S;
10850       break;
10851     case Intrinsic::x86_sse42_pcmpestris128:
10852       Opcode = X86ISD::PCMPESTRI;
10853       X86CC = X86::COND_S;
10854       break;
10855     case Intrinsic::x86_sse42_pcmpistriz128:
10856       Opcode = X86ISD::PCMPISTRI;
10857       X86CC = X86::COND_E;
10858       break;
10859     case Intrinsic::x86_sse42_pcmpestriz128:
10860       Opcode = X86ISD::PCMPESTRI;
10861       X86CC = X86::COND_E;
10862       break;
10863     }
10864     SmallVector<SDValue, 5> NewOps;
10865     NewOps.append(Op->op_begin()+1, Op->op_end());
10866     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10867     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10868     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10869                                 DAG.getConstant(X86CC, MVT::i8),
10870                                 SDValue(PCMP.getNode(), 1));
10871     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10872   }
10873
10874   case Intrinsic::x86_sse42_pcmpistri128:
10875   case Intrinsic::x86_sse42_pcmpestri128: {
10876     unsigned Opcode;
10877     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10878       Opcode = X86ISD::PCMPISTRI;
10879     else
10880       Opcode = X86ISD::PCMPESTRI;
10881
10882     SmallVector<SDValue, 5> NewOps;
10883     NewOps.append(Op->op_begin()+1, Op->op_end());
10884     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10885     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10886   }
10887   case Intrinsic::x86_fma_vfmadd_ps:
10888   case Intrinsic::x86_fma_vfmadd_pd:
10889   case Intrinsic::x86_fma_vfmsub_ps:
10890   case Intrinsic::x86_fma_vfmsub_pd:
10891   case Intrinsic::x86_fma_vfnmadd_ps:
10892   case Intrinsic::x86_fma_vfnmadd_pd:
10893   case Intrinsic::x86_fma_vfnmsub_ps:
10894   case Intrinsic::x86_fma_vfnmsub_pd:
10895   case Intrinsic::x86_fma_vfmaddsub_ps:
10896   case Intrinsic::x86_fma_vfmaddsub_pd:
10897   case Intrinsic::x86_fma_vfmsubadd_ps:
10898   case Intrinsic::x86_fma_vfmsubadd_pd:
10899   case Intrinsic::x86_fma_vfmadd_ps_256:
10900   case Intrinsic::x86_fma_vfmadd_pd_256:
10901   case Intrinsic::x86_fma_vfmsub_ps_256:
10902   case Intrinsic::x86_fma_vfmsub_pd_256:
10903   case Intrinsic::x86_fma_vfnmadd_ps_256:
10904   case Intrinsic::x86_fma_vfnmadd_pd_256:
10905   case Intrinsic::x86_fma_vfnmsub_ps_256:
10906   case Intrinsic::x86_fma_vfnmsub_pd_256:
10907   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10908   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10909   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10910   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10911     unsigned Opc;
10912     switch (IntNo) {
10913     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10914     case Intrinsic::x86_fma_vfmadd_ps:
10915     case Intrinsic::x86_fma_vfmadd_pd:
10916     case Intrinsic::x86_fma_vfmadd_ps_256:
10917     case Intrinsic::x86_fma_vfmadd_pd_256:
10918       Opc = X86ISD::FMADD;
10919       break;
10920     case Intrinsic::x86_fma_vfmsub_ps:
10921     case Intrinsic::x86_fma_vfmsub_pd:
10922     case Intrinsic::x86_fma_vfmsub_ps_256:
10923     case Intrinsic::x86_fma_vfmsub_pd_256:
10924       Opc = X86ISD::FMSUB;
10925       break;
10926     case Intrinsic::x86_fma_vfnmadd_ps:
10927     case Intrinsic::x86_fma_vfnmadd_pd:
10928     case Intrinsic::x86_fma_vfnmadd_ps_256:
10929     case Intrinsic::x86_fma_vfnmadd_pd_256:
10930       Opc = X86ISD::FNMADD;
10931       break;
10932     case Intrinsic::x86_fma_vfnmsub_ps:
10933     case Intrinsic::x86_fma_vfnmsub_pd:
10934     case Intrinsic::x86_fma_vfnmsub_ps_256:
10935     case Intrinsic::x86_fma_vfnmsub_pd_256:
10936       Opc = X86ISD::FNMSUB;
10937       break;
10938     case Intrinsic::x86_fma_vfmaddsub_ps:
10939     case Intrinsic::x86_fma_vfmaddsub_pd:
10940     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10941     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10942       Opc = X86ISD::FMADDSUB;
10943       break;
10944     case Intrinsic::x86_fma_vfmsubadd_ps:
10945     case Intrinsic::x86_fma_vfmsubadd_pd:
10946     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10947     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10948       Opc = X86ISD::FMSUBADD;
10949       break;
10950     }
10951
10952     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10953                        Op.getOperand(2), Op.getOperand(3));
10954   }
10955   }
10956 }
10957
10958 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10959   DebugLoc dl = Op.getDebugLoc();
10960   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10961   switch (IntNo) {
10962   default: return SDValue();    // Don't custom lower most intrinsics.
10963
10964   // RDRAND/RDSEED intrinsics.
10965   case Intrinsic::x86_rdrand_16:
10966   case Intrinsic::x86_rdrand_32:
10967   case Intrinsic::x86_rdrand_64:
10968   case Intrinsic::x86_rdseed_16:
10969   case Intrinsic::x86_rdseed_32:
10970   case Intrinsic::x86_rdseed_64: {
10971     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10972                        IntNo == Intrinsic::x86_rdseed_32 ||
10973                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10974                                                             X86ISD::RDRAND;
10975     // Emit the node with the right value type.
10976     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10977     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10978
10979     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10980     // Otherwise return the value from Rand, which is always 0, casted to i32.
10981     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10982                       DAG.getConstant(1, Op->getValueType(1)),
10983                       DAG.getConstant(X86::COND_B, MVT::i32),
10984                       SDValue(Result.getNode(), 1) };
10985     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10986                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10987                                   Ops, array_lengthof(Ops));
10988
10989     // Return { result, isValid, chain }.
10990     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10991                        SDValue(Result.getNode(), 2));
10992   }
10993
10994   // XTEST intrinsics.
10995   case Intrinsic::x86_xtest: {
10996     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
10997     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
10998     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10999                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11000                                 InTrans);
11001     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11002     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11003                        Ret, SDValue(InTrans.getNode(), 1));
11004   }
11005   }
11006 }
11007
11008 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11009                                            SelectionDAG &DAG) const {
11010   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11011   MFI->setReturnAddressIsTaken(true);
11012
11013   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11014   DebugLoc dl = Op.getDebugLoc();
11015   EVT PtrVT = getPointerTy();
11016
11017   if (Depth > 0) {
11018     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11019     SDValue Offset =
11020       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11021     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11022                        DAG.getNode(ISD::ADD, dl, PtrVT,
11023                                    FrameAddr, Offset),
11024                        MachinePointerInfo(), false, false, false, 0);
11025   }
11026
11027   // Just load the return address.
11028   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11029   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11030                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11031 }
11032
11033 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11034   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11035   MFI->setFrameAddressIsTaken(true);
11036
11037   EVT VT = Op.getValueType();
11038   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
11039   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11040   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
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   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
11061                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
11062                                      getPointerTy());
11063   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
11064
11065   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
11066                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11067   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
11068   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11069                        false, false, 0);
11070   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11071
11072   return DAG.getNode(X86ISD::EH_RETURN, dl,
11073                      MVT::Other,
11074                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11075 }
11076
11077 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11078                                                SelectionDAG &DAG) const {
11079   DebugLoc DL = Op.getDebugLoc();
11080   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11081                      DAG.getVTList(MVT::i32, MVT::Other),
11082                      Op.getOperand(0), Op.getOperand(1));
11083 }
11084
11085 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11086                                                 SelectionDAG &DAG) const {
11087   DebugLoc DL = Op.getDebugLoc();
11088   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11089                      Op.getOperand(0), Op.getOperand(1));
11090 }
11091
11092 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11093   return Op.getOperand(0);
11094 }
11095
11096 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11097                                                 SelectionDAG &DAG) const {
11098   SDValue Root = Op.getOperand(0);
11099   SDValue Trmp = Op.getOperand(1); // trampoline
11100   SDValue FPtr = Op.getOperand(2); // nested function
11101   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11102   DebugLoc dl  = Op.getDebugLoc();
11103
11104   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11105   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11106
11107   if (Subtarget->is64Bit()) {
11108     SDValue OutChains[6];
11109
11110     // Large code-model.
11111     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11112     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11113
11114     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11115     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11116
11117     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11118
11119     // Load the pointer to the nested function into R11.
11120     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11121     SDValue Addr = Trmp;
11122     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11123                                 Addr, MachinePointerInfo(TrmpAddr),
11124                                 false, false, 0);
11125
11126     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11127                        DAG.getConstant(2, MVT::i64));
11128     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11129                                 MachinePointerInfo(TrmpAddr, 2),
11130                                 false, false, 2);
11131
11132     // Load the 'nest' parameter value into R10.
11133     // R10 is specified in X86CallingConv.td
11134     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11135     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11136                        DAG.getConstant(10, MVT::i64));
11137     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11138                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11139                                 false, false, 0);
11140
11141     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11142                        DAG.getConstant(12, MVT::i64));
11143     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11144                                 MachinePointerInfo(TrmpAddr, 12),
11145                                 false, false, 2);
11146
11147     // Jump to the nested function.
11148     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11149     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11150                        DAG.getConstant(20, MVT::i64));
11151     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11152                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11153                                 false, false, 0);
11154
11155     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11156     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11157                        DAG.getConstant(22, MVT::i64));
11158     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11159                                 MachinePointerInfo(TrmpAddr, 22),
11160                                 false, false, 0);
11161
11162     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11163   } else {
11164     const Function *Func =
11165       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11166     CallingConv::ID CC = Func->getCallingConv();
11167     unsigned NestReg;
11168
11169     switch (CC) {
11170     default:
11171       llvm_unreachable("Unsupported calling convention");
11172     case CallingConv::C:
11173     case CallingConv::X86_StdCall: {
11174       // Pass 'nest' parameter in ECX.
11175       // Must be kept in sync with X86CallingConv.td
11176       NestReg = X86::ECX;
11177
11178       // Check that ECX wasn't needed by an 'inreg' parameter.
11179       FunctionType *FTy = Func->getFunctionType();
11180       const AttributeSet &Attrs = Func->getAttributes();
11181
11182       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11183         unsigned InRegCount = 0;
11184         unsigned Idx = 1;
11185
11186         for (FunctionType::param_iterator I = FTy->param_begin(),
11187              E = FTy->param_end(); I != E; ++I, ++Idx)
11188           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11189             // FIXME: should only count parameters that are lowered to integers.
11190             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11191
11192         if (InRegCount > 2) {
11193           report_fatal_error("Nest register in use - reduce number of inreg"
11194                              " parameters!");
11195         }
11196       }
11197       break;
11198     }
11199     case CallingConv::X86_FastCall:
11200     case CallingConv::X86_ThisCall:
11201     case CallingConv::Fast:
11202       // Pass 'nest' parameter in EAX.
11203       // Must be kept in sync with X86CallingConv.td
11204       NestReg = X86::EAX;
11205       break;
11206     }
11207
11208     SDValue OutChains[4];
11209     SDValue Addr, Disp;
11210
11211     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11212                        DAG.getConstant(10, MVT::i32));
11213     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11214
11215     // This is storing the opcode for MOV32ri.
11216     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11217     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11218     OutChains[0] = DAG.getStore(Root, dl,
11219                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11220                                 Trmp, MachinePointerInfo(TrmpAddr),
11221                                 false, false, 0);
11222
11223     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11224                        DAG.getConstant(1, MVT::i32));
11225     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11226                                 MachinePointerInfo(TrmpAddr, 1),
11227                                 false, false, 1);
11228
11229     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11230     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11231                        DAG.getConstant(5, MVT::i32));
11232     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11233                                 MachinePointerInfo(TrmpAddr, 5),
11234                                 false, false, 1);
11235
11236     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11237                        DAG.getConstant(6, MVT::i32));
11238     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11239                                 MachinePointerInfo(TrmpAddr, 6),
11240                                 false, false, 1);
11241
11242     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11243   }
11244 }
11245
11246 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11247                                             SelectionDAG &DAG) const {
11248   /*
11249    The rounding mode is in bits 11:10 of FPSR, and has the following
11250    settings:
11251      00 Round to nearest
11252      01 Round to -inf
11253      10 Round to +inf
11254      11 Round to 0
11255
11256   FLT_ROUNDS, on the other hand, expects the following:
11257     -1 Undefined
11258      0 Round to 0
11259      1 Round to nearest
11260      2 Round to +inf
11261      3 Round to -inf
11262
11263   To perform the conversion, we do:
11264     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11265   */
11266
11267   MachineFunction &MF = DAG.getMachineFunction();
11268   const TargetMachine &TM = MF.getTarget();
11269   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11270   unsigned StackAlignment = TFI.getStackAlignment();
11271   EVT VT = Op.getValueType();
11272   DebugLoc DL = Op.getDebugLoc();
11273
11274   // Save FP Control Word to stack slot
11275   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11276   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11277
11278   MachineMemOperand *MMO =
11279    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11280                            MachineMemOperand::MOStore, 2, 2);
11281
11282   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11283   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11284                                           DAG.getVTList(MVT::Other),
11285                                           Ops, array_lengthof(Ops), MVT::i16,
11286                                           MMO);
11287
11288   // Load FP Control Word from stack slot
11289   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11290                             MachinePointerInfo(), false, false, false, 0);
11291
11292   // Transform as necessary
11293   SDValue CWD1 =
11294     DAG.getNode(ISD::SRL, DL, MVT::i16,
11295                 DAG.getNode(ISD::AND, DL, MVT::i16,
11296                             CWD, DAG.getConstant(0x800, MVT::i16)),
11297                 DAG.getConstant(11, MVT::i8));
11298   SDValue CWD2 =
11299     DAG.getNode(ISD::SRL, DL, MVT::i16,
11300                 DAG.getNode(ISD::AND, DL, MVT::i16,
11301                             CWD, DAG.getConstant(0x400, MVT::i16)),
11302                 DAG.getConstant(9, MVT::i8));
11303
11304   SDValue RetVal =
11305     DAG.getNode(ISD::AND, DL, MVT::i16,
11306                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11307                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11308                             DAG.getConstant(1, MVT::i16)),
11309                 DAG.getConstant(3, MVT::i16));
11310
11311   return DAG.getNode((VT.getSizeInBits() < 16 ?
11312                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11313 }
11314
11315 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11316   EVT VT = Op.getValueType();
11317   EVT OpVT = VT;
11318   unsigned NumBits = VT.getSizeInBits();
11319   DebugLoc dl = Op.getDebugLoc();
11320
11321   Op = Op.getOperand(0);
11322   if (VT == MVT::i8) {
11323     // Zero extend to i32 since there is not an i8 bsr.
11324     OpVT = MVT::i32;
11325     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11326   }
11327
11328   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11329   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11330   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11331
11332   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11333   SDValue Ops[] = {
11334     Op,
11335     DAG.getConstant(NumBits+NumBits-1, OpVT),
11336     DAG.getConstant(X86::COND_E, MVT::i8),
11337     Op.getValue(1)
11338   };
11339   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11340
11341   // Finally xor with NumBits-1.
11342   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11343
11344   if (VT == MVT::i8)
11345     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11346   return Op;
11347 }
11348
11349 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11350   EVT VT = Op.getValueType();
11351   EVT OpVT = VT;
11352   unsigned NumBits = VT.getSizeInBits();
11353   DebugLoc dl = Op.getDebugLoc();
11354
11355   Op = Op.getOperand(0);
11356   if (VT == MVT::i8) {
11357     // Zero extend to i32 since there is not an i8 bsr.
11358     OpVT = MVT::i32;
11359     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11360   }
11361
11362   // Issue a bsr (scan bits in reverse).
11363   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11364   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11365
11366   // And xor with NumBits-1.
11367   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11368
11369   if (VT == MVT::i8)
11370     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11371   return Op;
11372 }
11373
11374 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11375   EVT VT = Op.getValueType();
11376   unsigned NumBits = VT.getSizeInBits();
11377   DebugLoc dl = Op.getDebugLoc();
11378   Op = Op.getOperand(0);
11379
11380   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11381   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11382   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11383
11384   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11385   SDValue Ops[] = {
11386     Op,
11387     DAG.getConstant(NumBits, VT),
11388     DAG.getConstant(X86::COND_E, MVT::i8),
11389     Op.getValue(1)
11390   };
11391   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11392 }
11393
11394 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11395 // ones, and then concatenate the result back.
11396 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11397   EVT VT = Op.getValueType();
11398
11399   assert(VT.is256BitVector() && VT.isInteger() &&
11400          "Unsupported value type for operation");
11401
11402   unsigned NumElems = VT.getVectorNumElements();
11403   DebugLoc dl = Op.getDebugLoc();
11404
11405   // Extract the LHS vectors
11406   SDValue LHS = Op.getOperand(0);
11407   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11408   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11409
11410   // Extract the RHS vectors
11411   SDValue RHS = Op.getOperand(1);
11412   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11413   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11414
11415   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11416   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11417
11418   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11419                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11420                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11421 }
11422
11423 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11424   assert(Op.getValueType().is256BitVector() &&
11425          Op.getValueType().isInteger() &&
11426          "Only handle AVX 256-bit vector integer operation");
11427   return Lower256IntArith(Op, DAG);
11428 }
11429
11430 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11431   assert(Op.getValueType().is256BitVector() &&
11432          Op.getValueType().isInteger() &&
11433          "Only handle AVX 256-bit vector integer operation");
11434   return Lower256IntArith(Op, DAG);
11435 }
11436
11437 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11438                         SelectionDAG &DAG) {
11439   DebugLoc dl = Op.getDebugLoc();
11440   EVT VT = Op.getValueType();
11441
11442   // Decompose 256-bit ops into smaller 128-bit ops.
11443   if (VT.is256BitVector() && !Subtarget->hasInt256())
11444     return Lower256IntArith(Op, DAG);
11445
11446   SDValue A = Op.getOperand(0);
11447   SDValue B = Op.getOperand(1);
11448
11449   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11450   if (VT == MVT::v4i32) {
11451     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11452            "Should not custom lower when pmuldq is available!");
11453
11454     // Extract the odd parts.
11455     const int UnpackMask[] = { 1, -1, 3, -1 };
11456     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11457     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11458
11459     // Multiply the even parts.
11460     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11461     // Now multiply odd parts.
11462     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11463
11464     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11465     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11466
11467     // Merge the two vectors back together with a shuffle. This expands into 2
11468     // shuffles.
11469     const int ShufMask[] = { 0, 4, 2, 6 };
11470     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11471   }
11472
11473   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11474          "Only know how to lower V2I64/V4I64 multiply");
11475
11476   //  Ahi = psrlqi(a, 32);
11477   //  Bhi = psrlqi(b, 32);
11478   //
11479   //  AloBlo = pmuludq(a, b);
11480   //  AloBhi = pmuludq(a, Bhi);
11481   //  AhiBlo = pmuludq(Ahi, b);
11482
11483   //  AloBhi = psllqi(AloBhi, 32);
11484   //  AhiBlo = psllqi(AhiBlo, 32);
11485   //  return AloBlo + AloBhi + AhiBlo;
11486
11487   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11488
11489   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11490   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11491
11492   // Bit cast to 32-bit vectors for MULUDQ
11493   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11494   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11495   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11496   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11497   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11498
11499   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11500   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11501   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11502
11503   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11504   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11505
11506   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11507   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11508 }
11509
11510 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11511   EVT VT = Op.getValueType();
11512   EVT EltTy = VT.getVectorElementType();
11513   unsigned NumElts = VT.getVectorNumElements();
11514   SDValue N0 = Op.getOperand(0);
11515   DebugLoc dl = Op.getDebugLoc();
11516
11517   // Lower sdiv X, pow2-const.
11518   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11519   if (!C)
11520     return SDValue();
11521
11522   APInt SplatValue, SplatUndef;
11523   unsigned MinSplatBits;
11524   bool HasAnyUndefs;
11525   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11526     return SDValue();
11527
11528   if ((SplatValue != 0) &&
11529       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11530     unsigned lg2 = SplatValue.countTrailingZeros();
11531     // Splat the sign bit.
11532     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11533     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11534     // Add (N0 < 0) ? abs2 - 1 : 0;
11535     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11536     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11537     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11538     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11539     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11540
11541     // If we're dividing by a positive value, we're done.  Otherwise, we must
11542     // negate the result.
11543     if (SplatValue.isNonNegative())
11544       return SRA;
11545
11546     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11547     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11548     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11549   }
11550   return SDValue();
11551 }
11552
11553 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11554                                          const X86Subtarget *Subtarget) {
11555   EVT VT = Op.getValueType();
11556   DebugLoc dl = Op.getDebugLoc();
11557   SDValue R = Op.getOperand(0);
11558   SDValue Amt = Op.getOperand(1);
11559
11560   // Optimize shl/srl/sra with constant shift amount.
11561   if (isSplatVector(Amt.getNode())) {
11562     SDValue SclrAmt = Amt->getOperand(0);
11563     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11564       uint64_t ShiftAmt = C->getZExtValue();
11565
11566       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11567           (Subtarget->hasInt256() &&
11568            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11569         if (Op.getOpcode() == ISD::SHL)
11570           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11571                              DAG.getConstant(ShiftAmt, MVT::i32));
11572         if (Op.getOpcode() == ISD::SRL)
11573           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11574                              DAG.getConstant(ShiftAmt, MVT::i32));
11575         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11576           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11577                              DAG.getConstant(ShiftAmt, MVT::i32));
11578       }
11579
11580       if (VT == MVT::v16i8) {
11581         if (Op.getOpcode() == ISD::SHL) {
11582           // Make a large shift.
11583           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11584                                     DAG.getConstant(ShiftAmt, MVT::i32));
11585           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11586           // Zero out the rightmost bits.
11587           SmallVector<SDValue, 16> V(16,
11588                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11589                                                      MVT::i8));
11590           return DAG.getNode(ISD::AND, dl, VT, SHL,
11591                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11592         }
11593         if (Op.getOpcode() == ISD::SRL) {
11594           // Make a large shift.
11595           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11596                                     DAG.getConstant(ShiftAmt, MVT::i32));
11597           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11598           // Zero out the leftmost bits.
11599           SmallVector<SDValue, 16> V(16,
11600                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11601                                                      MVT::i8));
11602           return DAG.getNode(ISD::AND, dl, VT, SRL,
11603                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11604         }
11605         if (Op.getOpcode() == ISD::SRA) {
11606           if (ShiftAmt == 7) {
11607             // R s>> 7  ===  R s< 0
11608             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11609             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11610           }
11611
11612           // R s>> a === ((R u>> a) ^ m) - m
11613           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11614           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11615                                                          MVT::i8));
11616           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11617           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11618           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11619           return Res;
11620         }
11621         llvm_unreachable("Unknown shift opcode.");
11622       }
11623
11624       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11625         if (Op.getOpcode() == ISD::SHL) {
11626           // Make a large shift.
11627           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11628                                     DAG.getConstant(ShiftAmt, MVT::i32));
11629           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11630           // Zero out the rightmost bits.
11631           SmallVector<SDValue, 32> V(32,
11632                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11633                                                      MVT::i8));
11634           return DAG.getNode(ISD::AND, dl, VT, SHL,
11635                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11636         }
11637         if (Op.getOpcode() == ISD::SRL) {
11638           // Make a large shift.
11639           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11640                                     DAG.getConstant(ShiftAmt, MVT::i32));
11641           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11642           // Zero out the leftmost bits.
11643           SmallVector<SDValue, 32> V(32,
11644                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11645                                                      MVT::i8));
11646           return DAG.getNode(ISD::AND, dl, VT, SRL,
11647                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11648         }
11649         if (Op.getOpcode() == ISD::SRA) {
11650           if (ShiftAmt == 7) {
11651             // R s>> 7  ===  R s< 0
11652             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11653             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11654           }
11655
11656           // R s>> a === ((R u>> a) ^ m) - m
11657           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11658           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11659                                                          MVT::i8));
11660           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11661           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11662           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11663           return Res;
11664         }
11665         llvm_unreachable("Unknown shift opcode.");
11666       }
11667     }
11668   }
11669
11670   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11671   if (!Subtarget->is64Bit() &&
11672       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11673       Amt.getOpcode() == ISD::BITCAST &&
11674       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11675     Amt = Amt.getOperand(0);
11676     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11677                      VT.getVectorNumElements();
11678     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11679     uint64_t ShiftAmt = 0;
11680     for (unsigned i = 0; i != Ratio; ++i) {
11681       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11682       if (C == 0)
11683         return SDValue();
11684       // 6 == Log2(64)
11685       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11686     }
11687     // Check remaining shift amounts.
11688     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11689       uint64_t ShAmt = 0;
11690       for (unsigned j = 0; j != Ratio; ++j) {
11691         ConstantSDNode *C =
11692           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11693         if (C == 0)
11694           return SDValue();
11695         // 6 == Log2(64)
11696         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11697       }
11698       if (ShAmt != ShiftAmt)
11699         return SDValue();
11700     }
11701     switch (Op.getOpcode()) {
11702     default:
11703       llvm_unreachable("Unknown shift opcode!");
11704     case ISD::SHL:
11705       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11706                          DAG.getConstant(ShiftAmt, MVT::i32));
11707     case ISD::SRL:
11708       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11709                          DAG.getConstant(ShiftAmt, MVT::i32));
11710     case ISD::SRA:
11711       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11712                          DAG.getConstant(ShiftAmt, MVT::i32));
11713     }
11714   }
11715
11716   return SDValue();
11717 }
11718
11719 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11720                                         const X86Subtarget* Subtarget) {
11721   EVT VT = Op.getValueType();
11722   DebugLoc dl = Op.getDebugLoc();
11723   SDValue R = Op.getOperand(0);
11724   SDValue Amt = Op.getOperand(1);
11725
11726   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11727       VT == MVT::v4i32 || VT == MVT::v8i16 ||
11728       (Subtarget->hasInt256() &&
11729        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11730         VT == MVT::v8i32 || VT == MVT::v16i16))) {
11731     SDValue BaseShAmt;
11732     EVT EltVT = VT.getVectorElementType();
11733
11734     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11735       unsigned NumElts = VT.getVectorNumElements();
11736       unsigned i, j;
11737       for (i = 0; i != NumElts; ++i) {
11738         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11739           continue;
11740         break;
11741       }
11742       for (j = i; j != NumElts; ++j) {
11743         SDValue Arg = Amt.getOperand(j);
11744         if (Arg.getOpcode() == ISD::UNDEF) continue;
11745         if (Arg != Amt.getOperand(i))
11746           break;
11747       }
11748       if (i != NumElts && j == NumElts)
11749         BaseShAmt = Amt.getOperand(i);
11750     } else {
11751       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11752         Amt = Amt.getOperand(0);
11753       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11754                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11755         SDValue InVec = Amt.getOperand(0);
11756         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11757           unsigned NumElts = InVec.getValueType().getVectorNumElements();
11758           unsigned i = 0;
11759           for (; i != NumElts; ++i) {
11760             SDValue Arg = InVec.getOperand(i);
11761             if (Arg.getOpcode() == ISD::UNDEF) continue;
11762             BaseShAmt = Arg;
11763             break;
11764           }
11765         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11766            if (ConstantSDNode *C =
11767                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11768              unsigned SplatIdx =
11769                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11770              if (C->getZExtValue() == SplatIdx)
11771                BaseShAmt = InVec.getOperand(1);
11772            }
11773         }
11774         if (BaseShAmt.getNode() == 0)
11775           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11776                                   DAG.getIntPtrConstant(0));
11777       }
11778     }
11779
11780     if (BaseShAmt.getNode()) {
11781       if (EltVT.bitsGT(MVT::i32))
11782         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11783       else if (EltVT.bitsLT(MVT::i32))
11784         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11785
11786       switch (Op.getOpcode()) {
11787       default:
11788         llvm_unreachable("Unknown shift opcode!");
11789       case ISD::SHL:
11790         switch (VT.getSimpleVT().SimpleTy) {
11791         default: return SDValue();
11792         case MVT::v2i64:
11793         case MVT::v4i32:
11794         case MVT::v8i16:
11795         case MVT::v4i64:
11796         case MVT::v8i32:
11797         case MVT::v16i16:
11798           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11799         }
11800       case ISD::SRA:
11801         switch (VT.getSimpleVT().SimpleTy) {
11802         default: return SDValue();
11803         case MVT::v4i32:
11804         case MVT::v8i16:
11805         case MVT::v8i32:
11806         case MVT::v16i16:
11807           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11808         }
11809       case ISD::SRL:
11810         switch (VT.getSimpleVT().SimpleTy) {
11811         default: return SDValue();
11812         case MVT::v2i64:
11813         case MVT::v4i32:
11814         case MVT::v8i16:
11815         case MVT::v4i64:
11816         case MVT::v8i32:
11817         case MVT::v16i16:
11818           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11819         }
11820       }
11821     }
11822   }
11823
11824   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11825   if (!Subtarget->is64Bit() &&
11826       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11827       Amt.getOpcode() == ISD::BITCAST &&
11828       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11829     Amt = Amt.getOperand(0);
11830     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11831                      VT.getVectorNumElements();
11832     std::vector<SDValue> Vals(Ratio);
11833     for (unsigned i = 0; i != Ratio; ++i)
11834       Vals[i] = Amt.getOperand(i);
11835     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11836       for (unsigned j = 0; j != Ratio; ++j)
11837         if (Vals[j] != Amt.getOperand(i + j))
11838           return SDValue();
11839     }
11840     switch (Op.getOpcode()) {
11841     default:
11842       llvm_unreachable("Unknown shift opcode!");
11843     case ISD::SHL:
11844       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11845     case ISD::SRL:
11846       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11847     case ISD::SRA:
11848       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11849     }
11850   }
11851
11852   return SDValue();
11853 }
11854
11855 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11856
11857   EVT VT = Op.getValueType();
11858   DebugLoc dl = Op.getDebugLoc();
11859   SDValue R = Op.getOperand(0);
11860   SDValue Amt = Op.getOperand(1);
11861   SDValue V;
11862
11863   if (!Subtarget->hasSSE2())
11864     return SDValue();
11865
11866   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11867   if (V.getNode())
11868     return V;
11869
11870   V = LowerScalarVariableShift(Op, DAG, Subtarget);
11871   if (V.getNode())
11872       return V;
11873
11874   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11875   if (Subtarget->hasInt256()) {
11876     if (Op.getOpcode() == ISD::SRL &&
11877         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11878          VT == MVT::v4i64 || VT == MVT::v8i32))
11879       return Op;
11880     if (Op.getOpcode() == ISD::SHL &&
11881         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11882          VT == MVT::v4i64 || VT == MVT::v8i32))
11883       return Op;
11884     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11885       return Op;
11886   }
11887
11888   // Lower SHL with variable shift amount.
11889   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11890     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11891
11892     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11893     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11894     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11895     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11896   }
11897   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11898     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11899
11900     // a = a << 5;
11901     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11902     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11903
11904     // Turn 'a' into a mask suitable for VSELECT
11905     SDValue VSelM = DAG.getConstant(0x80, VT);
11906     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11907     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11908
11909     SDValue CM1 = DAG.getConstant(0x0f, VT);
11910     SDValue CM2 = DAG.getConstant(0x3f, VT);
11911
11912     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11913     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11914     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11915                             DAG.getConstant(4, MVT::i32), DAG);
11916     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11917     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11918
11919     // a += a
11920     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11921     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11922     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11923
11924     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11925     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11926     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11927                             DAG.getConstant(2, MVT::i32), DAG);
11928     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11929     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11930
11931     // a += a
11932     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11933     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11934     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11935
11936     // return VSELECT(r, r+r, a);
11937     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11938                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11939     return R;
11940   }
11941
11942   // Decompose 256-bit shifts into smaller 128-bit shifts.
11943   if (VT.is256BitVector()) {
11944     unsigned NumElems = VT.getVectorNumElements();
11945     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11946     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11947
11948     // Extract the two vectors
11949     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11950     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11951
11952     // Recreate the shift amount vectors
11953     SDValue Amt1, Amt2;
11954     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11955       // Constant shift amount
11956       SmallVector<SDValue, 4> Amt1Csts;
11957       SmallVector<SDValue, 4> Amt2Csts;
11958       for (unsigned i = 0; i != NumElems/2; ++i)
11959         Amt1Csts.push_back(Amt->getOperand(i));
11960       for (unsigned i = NumElems/2; i != NumElems; ++i)
11961         Amt2Csts.push_back(Amt->getOperand(i));
11962
11963       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11964                                  &Amt1Csts[0], NumElems/2);
11965       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11966                                  &Amt2Csts[0], NumElems/2);
11967     } else {
11968       // Variable shift amount
11969       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11970       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11971     }
11972
11973     // Issue new vector shifts for the smaller types
11974     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11975     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11976
11977     // Concatenate the result back
11978     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11979   }
11980
11981   return SDValue();
11982 }
11983
11984 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11985   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11986   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11987   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11988   // has only one use.
11989   SDNode *N = Op.getNode();
11990   SDValue LHS = N->getOperand(0);
11991   SDValue RHS = N->getOperand(1);
11992   unsigned BaseOp = 0;
11993   unsigned Cond = 0;
11994   DebugLoc DL = Op.getDebugLoc();
11995   switch (Op.getOpcode()) {
11996   default: llvm_unreachable("Unknown ovf instruction!");
11997   case ISD::SADDO:
11998     // A subtract of one will be selected as a INC. Note that INC doesn't
11999     // set CF, so we can't do this for UADDO.
12000     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12001       if (C->isOne()) {
12002         BaseOp = X86ISD::INC;
12003         Cond = X86::COND_O;
12004         break;
12005       }
12006     BaseOp = X86ISD::ADD;
12007     Cond = X86::COND_O;
12008     break;
12009   case ISD::UADDO:
12010     BaseOp = X86ISD::ADD;
12011     Cond = X86::COND_B;
12012     break;
12013   case ISD::SSUBO:
12014     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12015     // set CF, so we can't do this for USUBO.
12016     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12017       if (C->isOne()) {
12018         BaseOp = X86ISD::DEC;
12019         Cond = X86::COND_O;
12020         break;
12021       }
12022     BaseOp = X86ISD::SUB;
12023     Cond = X86::COND_O;
12024     break;
12025   case ISD::USUBO:
12026     BaseOp = X86ISD::SUB;
12027     Cond = X86::COND_B;
12028     break;
12029   case ISD::SMULO:
12030     BaseOp = X86ISD::SMUL;
12031     Cond = X86::COND_O;
12032     break;
12033   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12034     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12035                                  MVT::i32);
12036     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12037
12038     SDValue SetCC =
12039       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12040                   DAG.getConstant(X86::COND_O, MVT::i32),
12041                   SDValue(Sum.getNode(), 2));
12042
12043     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12044   }
12045   }
12046
12047   // Also sets EFLAGS.
12048   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12049   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12050
12051   SDValue SetCC =
12052     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12053                 DAG.getConstant(Cond, MVT::i32),
12054                 SDValue(Sum.getNode(), 1));
12055
12056   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12057 }
12058
12059 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12060                                                   SelectionDAG &DAG) const {
12061   DebugLoc dl = Op.getDebugLoc();
12062   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12063   EVT VT = Op.getValueType();
12064
12065   if (!Subtarget->hasSSE2() || !VT.isVector())
12066     return SDValue();
12067
12068   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12069                       ExtraVT.getScalarType().getSizeInBits();
12070   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12071
12072   switch (VT.getSimpleVT().SimpleTy) {
12073     default: return SDValue();
12074     case MVT::v8i32:
12075     case MVT::v16i16:
12076       if (!Subtarget->hasFp256())
12077         return SDValue();
12078       if (!Subtarget->hasInt256()) {
12079         // needs to be split
12080         unsigned NumElems = VT.getVectorNumElements();
12081
12082         // Extract the LHS vectors
12083         SDValue LHS = Op.getOperand(0);
12084         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12085         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12086
12087         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12088         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12089
12090         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12091         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12092         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12093                                    ExtraNumElems/2);
12094         SDValue Extra = DAG.getValueType(ExtraVT);
12095
12096         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12097         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12098
12099         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12100       }
12101       // fall through
12102     case MVT::v4i32:
12103     case MVT::v8i16: {
12104       // (sext (vzext x)) -> (vsext x)
12105       SDValue Op0 = Op.getOperand(0);
12106       SDValue Op00 = Op0.getOperand(0);
12107       SDValue Tmp1;
12108       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12109       if (Op0.getOpcode() == ISD::BITCAST &&
12110           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12111         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12112       if (Tmp1.getNode()) {
12113         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12114         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12115                "This optimization is invalid without a VZEXT.");
12116         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12117       }
12118
12119       // If the above didn't work, then just use Shift-Left + Shift-Right.
12120       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12121       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12122     }
12123   }
12124 }
12125
12126 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12127                                  SelectionDAG &DAG) {
12128   DebugLoc dl = Op.getDebugLoc();
12129   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12130     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12131   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12132     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12133
12134   // The only fence that needs an instruction is a sequentially-consistent
12135   // cross-thread fence.
12136   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12137     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12138     // no-sse2). There isn't any reason to disable it if the target processor
12139     // supports it.
12140     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12141       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12142
12143     SDValue Chain = Op.getOperand(0);
12144     SDValue Zero = DAG.getConstant(0, MVT::i32);
12145     SDValue Ops[] = {
12146       DAG.getRegister(X86::ESP, MVT::i32), // Base
12147       DAG.getTargetConstant(1, MVT::i8),   // Scale
12148       DAG.getRegister(0, MVT::i32),        // Index
12149       DAG.getTargetConstant(0, MVT::i32),  // Disp
12150       DAG.getRegister(0, MVT::i32),        // Segment.
12151       Zero,
12152       Chain
12153     };
12154     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12155     return SDValue(Res, 0);
12156   }
12157
12158   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12159   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12160 }
12161
12162 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12163                              SelectionDAG &DAG) {
12164   EVT T = Op.getValueType();
12165   DebugLoc DL = Op.getDebugLoc();
12166   unsigned Reg = 0;
12167   unsigned size = 0;
12168   switch(T.getSimpleVT().SimpleTy) {
12169   default: llvm_unreachable("Invalid value type!");
12170   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12171   case MVT::i16: Reg = X86::AX;  size = 2; break;
12172   case MVT::i32: Reg = X86::EAX; size = 4; break;
12173   case MVT::i64:
12174     assert(Subtarget->is64Bit() && "Node not type legal!");
12175     Reg = X86::RAX; size = 8;
12176     break;
12177   }
12178   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12179                                     Op.getOperand(2), SDValue());
12180   SDValue Ops[] = { cpIn.getValue(0),
12181                     Op.getOperand(1),
12182                     Op.getOperand(3),
12183                     DAG.getTargetConstant(size, MVT::i8),
12184                     cpIn.getValue(1) };
12185   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12186   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12187   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12188                                            Ops, array_lengthof(Ops), T, MMO);
12189   SDValue cpOut =
12190     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12191   return cpOut;
12192 }
12193
12194 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12195                                      SelectionDAG &DAG) {
12196   assert(Subtarget->is64Bit() && "Result not type legalized?");
12197   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12198   SDValue TheChain = Op.getOperand(0);
12199   DebugLoc dl = Op.getDebugLoc();
12200   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12201   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12202   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12203                                    rax.getValue(2));
12204   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12205                             DAG.getConstant(32, MVT::i8));
12206   SDValue Ops[] = {
12207     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12208     rdx.getValue(1)
12209   };
12210   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12211 }
12212
12213 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12214   EVT SrcVT = Op.getOperand(0).getValueType();
12215   EVT DstVT = Op.getValueType();
12216   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12217          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12218   assert((DstVT == MVT::i64 ||
12219           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12220          "Unexpected custom BITCAST");
12221   // i64 <=> MMX conversions are Legal.
12222   if (SrcVT==MVT::i64 && DstVT.isVector())
12223     return Op;
12224   if (DstVT==MVT::i64 && SrcVT.isVector())
12225     return Op;
12226   // MMX <=> MMX conversions are Legal.
12227   if (SrcVT.isVector() && DstVT.isVector())
12228     return Op;
12229   // All other conversions need to be expanded.
12230   return SDValue();
12231 }
12232
12233 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12234   SDNode *Node = Op.getNode();
12235   DebugLoc dl = Node->getDebugLoc();
12236   EVT T = Node->getValueType(0);
12237   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12238                               DAG.getConstant(0, T), Node->getOperand(2));
12239   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12240                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12241                        Node->getOperand(0),
12242                        Node->getOperand(1), negOp,
12243                        cast<AtomicSDNode>(Node)->getSrcValue(),
12244                        cast<AtomicSDNode>(Node)->getAlignment(),
12245                        cast<AtomicSDNode>(Node)->getOrdering(),
12246                        cast<AtomicSDNode>(Node)->getSynchScope());
12247 }
12248
12249 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12250   SDNode *Node = Op.getNode();
12251   DebugLoc dl = Node->getDebugLoc();
12252   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12253
12254   // Convert seq_cst store -> xchg
12255   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12256   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12257   //        (The only way to get a 16-byte store is cmpxchg16b)
12258   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12259   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12260       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12261     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12262                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12263                                  Node->getOperand(0),
12264                                  Node->getOperand(1), Node->getOperand(2),
12265                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12266                                  cast<AtomicSDNode>(Node)->getOrdering(),
12267                                  cast<AtomicSDNode>(Node)->getSynchScope());
12268     return Swap.getValue(1);
12269   }
12270   // Other atomic stores have a simple pattern.
12271   return Op;
12272 }
12273
12274 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12275   EVT VT = Op.getNode()->getValueType(0);
12276
12277   // Let legalize expand this if it isn't a legal type yet.
12278   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12279     return SDValue();
12280
12281   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12282
12283   unsigned Opc;
12284   bool ExtraOp = false;
12285   switch (Op.getOpcode()) {
12286   default: llvm_unreachable("Invalid code");
12287   case ISD::ADDC: Opc = X86ISD::ADD; break;
12288   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12289   case ISD::SUBC: Opc = X86ISD::SUB; break;
12290   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12291   }
12292
12293   if (!ExtraOp)
12294     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12295                        Op.getOperand(1));
12296   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12297                      Op.getOperand(1), Op.getOperand(2));
12298 }
12299
12300 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12301   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12302
12303   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12304   // which returns the values as { float, float } (in XMM0) or
12305   // { double, double } (which is returned in XMM0, XMM1).
12306   DebugLoc dl = Op.getDebugLoc();
12307   SDValue Arg = Op.getOperand(0);
12308   EVT ArgVT = Arg.getValueType();
12309   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12310
12311   ArgListTy Args;
12312   ArgListEntry Entry;
12313
12314   Entry.Node = Arg;
12315   Entry.Ty = ArgTy;
12316   Entry.isSExt = false;
12317   Entry.isZExt = false;
12318   Args.push_back(Entry);
12319
12320   bool isF64 = ArgVT == MVT::f64;
12321   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12322   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12323   // the results are returned via SRet in memory.
12324   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12325   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12326
12327   Type *RetTy = isF64
12328     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12329     : (Type*)VectorType::get(ArgTy, 4);
12330   TargetLowering::
12331     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12332                          false, false, false, false, 0,
12333                          CallingConv::C, /*isTaillCall=*/false,
12334                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12335                          Callee, Args, DAG, dl);
12336   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12337
12338   if (isF64)
12339     // Returned in xmm0 and xmm1.
12340     return CallResult.first;
12341
12342   // Returned in bits 0:31 and 32:64 xmm0.
12343   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12344                                CallResult.first, DAG.getIntPtrConstant(0));
12345   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12346                                CallResult.first, DAG.getIntPtrConstant(1));
12347   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12348   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12349 }
12350
12351 /// LowerOperation - Provide custom lowering hooks for some operations.
12352 ///
12353 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12354   switch (Op.getOpcode()) {
12355   default: llvm_unreachable("Should not custom lower this!");
12356   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12357   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12358   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12359   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12360   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12361   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12362   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12363   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12364   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12365   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12366   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12367   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12368   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12369   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12370   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12371   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12372   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12373   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12374   case ISD::SHL_PARTS:
12375   case ISD::SRA_PARTS:
12376   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12377   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12378   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12379   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12380   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12381   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12382   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12383   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12384   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12385   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12386   case ISD::FABS:               return LowerFABS(Op, DAG);
12387   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12388   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12389   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12390   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12391   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12392   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12393   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12394   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12395   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12396   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12397   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12398   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12399   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12400   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12401   case ISD::FRAME_TO_ARGS_OFFSET:
12402                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12403   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12404   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12405   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12406   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12407   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12408   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12409   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12410   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12411   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12412   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12413   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12414   case ISD::SRA:
12415   case ISD::SRL:
12416   case ISD::SHL:                return LowerShift(Op, DAG);
12417   case ISD::SADDO:
12418   case ISD::UADDO:
12419   case ISD::SSUBO:
12420   case ISD::USUBO:
12421   case ISD::SMULO:
12422   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12423   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12424   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12425   case ISD::ADDC:
12426   case ISD::ADDE:
12427   case ISD::SUBC:
12428   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12429   case ISD::ADD:                return LowerADD(Op, DAG);
12430   case ISD::SUB:                return LowerSUB(Op, DAG);
12431   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12432   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12433   }
12434 }
12435
12436 static void ReplaceATOMIC_LOAD(SDNode *Node,
12437                                   SmallVectorImpl<SDValue> &Results,
12438                                   SelectionDAG &DAG) {
12439   DebugLoc dl = Node->getDebugLoc();
12440   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12441
12442   // Convert wide load -> cmpxchg8b/cmpxchg16b
12443   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12444   //        (The only way to get a 16-byte load is cmpxchg16b)
12445   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12446   SDValue Zero = DAG.getConstant(0, VT);
12447   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12448                                Node->getOperand(0),
12449                                Node->getOperand(1), Zero, Zero,
12450                                cast<AtomicSDNode>(Node)->getMemOperand(),
12451                                cast<AtomicSDNode>(Node)->getOrdering(),
12452                                cast<AtomicSDNode>(Node)->getSynchScope());
12453   Results.push_back(Swap.getValue(0));
12454   Results.push_back(Swap.getValue(1));
12455 }
12456
12457 static void
12458 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12459                         SelectionDAG &DAG, unsigned NewOp) {
12460   DebugLoc dl = Node->getDebugLoc();
12461   assert (Node->getValueType(0) == MVT::i64 &&
12462           "Only know how to expand i64 atomics");
12463
12464   SDValue Chain = Node->getOperand(0);
12465   SDValue In1 = Node->getOperand(1);
12466   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12467                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12468   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12469                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12470   SDValue Ops[] = { Chain, In1, In2L, In2H };
12471   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12472   SDValue Result =
12473     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12474                             cast<MemSDNode>(Node)->getMemOperand());
12475   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12476   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12477   Results.push_back(Result.getValue(2));
12478 }
12479
12480 /// ReplaceNodeResults - Replace a node with an illegal result type
12481 /// with a new node built out of custom code.
12482 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12483                                            SmallVectorImpl<SDValue>&Results,
12484                                            SelectionDAG &DAG) const {
12485   DebugLoc dl = N->getDebugLoc();
12486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12487   switch (N->getOpcode()) {
12488   default:
12489     llvm_unreachable("Do not know how to custom type legalize this operation!");
12490   case ISD::SIGN_EXTEND_INREG:
12491   case ISD::ADDC:
12492   case ISD::ADDE:
12493   case ISD::SUBC:
12494   case ISD::SUBE:
12495     // We don't want to expand or promote these.
12496     return;
12497   case ISD::FP_TO_SINT:
12498   case ISD::FP_TO_UINT: {
12499     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12500
12501     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12502       return;
12503
12504     std::pair<SDValue,SDValue> Vals =
12505         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12506     SDValue FIST = Vals.first, StackSlot = Vals.second;
12507     if (FIST.getNode() != 0) {
12508       EVT VT = N->getValueType(0);
12509       // Return a load from the stack slot.
12510       if (StackSlot.getNode() != 0)
12511         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12512                                       MachinePointerInfo(),
12513                                       false, false, false, 0));
12514       else
12515         Results.push_back(FIST);
12516     }
12517     return;
12518   }
12519   case ISD::UINT_TO_FP: {
12520     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12521     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12522         N->getValueType(0) != MVT::v2f32)
12523       return;
12524     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12525                                  N->getOperand(0));
12526     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12527                                      MVT::f64);
12528     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12529     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12530                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12531     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12532     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12533     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12534     return;
12535   }
12536   case ISD::FP_ROUND: {
12537     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12538         return;
12539     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12540     Results.push_back(V);
12541     return;
12542   }
12543   case ISD::READCYCLECOUNTER: {
12544     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12545     SDValue TheChain = N->getOperand(0);
12546     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12547     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12548                                      rd.getValue(1));
12549     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12550                                      eax.getValue(2));
12551     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12552     SDValue Ops[] = { eax, edx };
12553     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12554                                   array_lengthof(Ops)));
12555     Results.push_back(edx.getValue(1));
12556     return;
12557   }
12558   case ISD::ATOMIC_CMP_SWAP: {
12559     EVT T = N->getValueType(0);
12560     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12561     bool Regs64bit = T == MVT::i128;
12562     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12563     SDValue cpInL, cpInH;
12564     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12565                         DAG.getConstant(0, HalfT));
12566     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12567                         DAG.getConstant(1, HalfT));
12568     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12569                              Regs64bit ? X86::RAX : X86::EAX,
12570                              cpInL, SDValue());
12571     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12572                              Regs64bit ? X86::RDX : X86::EDX,
12573                              cpInH, cpInL.getValue(1));
12574     SDValue swapInL, swapInH;
12575     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12576                           DAG.getConstant(0, HalfT));
12577     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12578                           DAG.getConstant(1, HalfT));
12579     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12580                                Regs64bit ? X86::RBX : X86::EBX,
12581                                swapInL, cpInH.getValue(1));
12582     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12583                                Regs64bit ? X86::RCX : X86::ECX,
12584                                swapInH, swapInL.getValue(1));
12585     SDValue Ops[] = { swapInH.getValue(0),
12586                       N->getOperand(1),
12587                       swapInH.getValue(1) };
12588     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12589     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12590     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12591                                   X86ISD::LCMPXCHG8_DAG;
12592     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12593                                              Ops, array_lengthof(Ops), T, MMO);
12594     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12595                                         Regs64bit ? X86::RAX : X86::EAX,
12596                                         HalfT, Result.getValue(1));
12597     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12598                                         Regs64bit ? X86::RDX : X86::EDX,
12599                                         HalfT, cpOutL.getValue(2));
12600     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12601     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12602     Results.push_back(cpOutH.getValue(1));
12603     return;
12604   }
12605   case ISD::ATOMIC_LOAD_ADD:
12606   case ISD::ATOMIC_LOAD_AND:
12607   case ISD::ATOMIC_LOAD_NAND:
12608   case ISD::ATOMIC_LOAD_OR:
12609   case ISD::ATOMIC_LOAD_SUB:
12610   case ISD::ATOMIC_LOAD_XOR:
12611   case ISD::ATOMIC_LOAD_MAX:
12612   case ISD::ATOMIC_LOAD_MIN:
12613   case ISD::ATOMIC_LOAD_UMAX:
12614   case ISD::ATOMIC_LOAD_UMIN:
12615   case ISD::ATOMIC_SWAP: {
12616     unsigned Opc;
12617     switch (N->getOpcode()) {
12618     default: llvm_unreachable("Unexpected opcode");
12619     case ISD::ATOMIC_LOAD_ADD:
12620       Opc = X86ISD::ATOMADD64_DAG;
12621       break;
12622     case ISD::ATOMIC_LOAD_AND:
12623       Opc = X86ISD::ATOMAND64_DAG;
12624       break;
12625     case ISD::ATOMIC_LOAD_NAND:
12626       Opc = X86ISD::ATOMNAND64_DAG;
12627       break;
12628     case ISD::ATOMIC_LOAD_OR:
12629       Opc = X86ISD::ATOMOR64_DAG;
12630       break;
12631     case ISD::ATOMIC_LOAD_SUB:
12632       Opc = X86ISD::ATOMSUB64_DAG;
12633       break;
12634     case ISD::ATOMIC_LOAD_XOR:
12635       Opc = X86ISD::ATOMXOR64_DAG;
12636       break;
12637     case ISD::ATOMIC_LOAD_MAX:
12638       Opc = X86ISD::ATOMMAX64_DAG;
12639       break;
12640     case ISD::ATOMIC_LOAD_MIN:
12641       Opc = X86ISD::ATOMMIN64_DAG;
12642       break;
12643     case ISD::ATOMIC_LOAD_UMAX:
12644       Opc = X86ISD::ATOMUMAX64_DAG;
12645       break;
12646     case ISD::ATOMIC_LOAD_UMIN:
12647       Opc = X86ISD::ATOMUMIN64_DAG;
12648       break;
12649     case ISD::ATOMIC_SWAP:
12650       Opc = X86ISD::ATOMSWAP64_DAG;
12651       break;
12652     }
12653     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12654     return;
12655   }
12656   case ISD::ATOMIC_LOAD:
12657     ReplaceATOMIC_LOAD(N, Results, DAG);
12658   }
12659 }
12660
12661 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12662   switch (Opcode) {
12663   default: return NULL;
12664   case X86ISD::BSF:                return "X86ISD::BSF";
12665   case X86ISD::BSR:                return "X86ISD::BSR";
12666   case X86ISD::SHLD:               return "X86ISD::SHLD";
12667   case X86ISD::SHRD:               return "X86ISD::SHRD";
12668   case X86ISD::FAND:               return "X86ISD::FAND";
12669   case X86ISD::FOR:                return "X86ISD::FOR";
12670   case X86ISD::FXOR:               return "X86ISD::FXOR";
12671   case X86ISD::FSRL:               return "X86ISD::FSRL";
12672   case X86ISD::FILD:               return "X86ISD::FILD";
12673   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12674   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12675   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12676   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12677   case X86ISD::FLD:                return "X86ISD::FLD";
12678   case X86ISD::FST:                return "X86ISD::FST";
12679   case X86ISD::CALL:               return "X86ISD::CALL";
12680   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12681   case X86ISD::BT:                 return "X86ISD::BT";
12682   case X86ISD::CMP:                return "X86ISD::CMP";
12683   case X86ISD::COMI:               return "X86ISD::COMI";
12684   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12685   case X86ISD::SETCC:              return "X86ISD::SETCC";
12686   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12687   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12688   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12689   case X86ISD::CMOV:               return "X86ISD::CMOV";
12690   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12691   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12692   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12693   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12694   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12695   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12696   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12697   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12698   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12699   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12700   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12701   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12702   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12703   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12704   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12705   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12706   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12707   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12708   case X86ISD::HADD:               return "X86ISD::HADD";
12709   case X86ISD::HSUB:               return "X86ISD::HSUB";
12710   case X86ISD::FHADD:              return "X86ISD::FHADD";
12711   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12712   case X86ISD::UMAX:               return "X86ISD::UMAX";
12713   case X86ISD::UMIN:               return "X86ISD::UMIN";
12714   case X86ISD::SMAX:               return "X86ISD::SMAX";
12715   case X86ISD::SMIN:               return "X86ISD::SMIN";
12716   case X86ISD::FMAX:               return "X86ISD::FMAX";
12717   case X86ISD::FMIN:               return "X86ISD::FMIN";
12718   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12719   case X86ISD::FMINC:              return "X86ISD::FMINC";
12720   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12721   case X86ISD::FRCP:               return "X86ISD::FRCP";
12722   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12723   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12724   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12725   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12726   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12727   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12728   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12729   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12730   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12731   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12732   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12733   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12734   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12735   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12736   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12737   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12738   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12739   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12740   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12741   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12742   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12743   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12744   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12745   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12746   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12747   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12748   case X86ISD::VSHL:               return "X86ISD::VSHL";
12749   case X86ISD::VSRL:               return "X86ISD::VSRL";
12750   case X86ISD::VSRA:               return "X86ISD::VSRA";
12751   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12752   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12753   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12754   case X86ISD::CMPP:               return "X86ISD::CMPP";
12755   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12756   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12757   case X86ISD::ADD:                return "X86ISD::ADD";
12758   case X86ISD::SUB:                return "X86ISD::SUB";
12759   case X86ISD::ADC:                return "X86ISD::ADC";
12760   case X86ISD::SBB:                return "X86ISD::SBB";
12761   case X86ISD::SMUL:               return "X86ISD::SMUL";
12762   case X86ISD::UMUL:               return "X86ISD::UMUL";
12763   case X86ISD::INC:                return "X86ISD::INC";
12764   case X86ISD::DEC:                return "X86ISD::DEC";
12765   case X86ISD::OR:                 return "X86ISD::OR";
12766   case X86ISD::XOR:                return "X86ISD::XOR";
12767   case X86ISD::AND:                return "X86ISD::AND";
12768   case X86ISD::BLSI:               return "X86ISD::BLSI";
12769   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12770   case X86ISD::BLSR:               return "X86ISD::BLSR";
12771   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12772   case X86ISD::PTEST:              return "X86ISD::PTEST";
12773   case X86ISD::TESTP:              return "X86ISD::TESTP";
12774   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12775   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12776   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12777   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12778   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12779   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12780   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12781   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12782   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12783   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12784   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12785   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12786   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12787   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12788   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12789   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12790   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12791   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12792   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12793   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12794   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12795   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12796   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12797   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12798   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12799   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12800   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12801   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12802   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12803   case X86ISD::SAHF:               return "X86ISD::SAHF";
12804   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12805   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12806   case X86ISD::FMADD:              return "X86ISD::FMADD";
12807   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12808   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12809   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12810   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12811   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12812   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12813   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12814   case X86ISD::XTEST:              return "X86ISD::XTEST";
12815   }
12816 }
12817
12818 // isLegalAddressingMode - Return true if the addressing mode represented
12819 // by AM is legal for this target, for a load/store of the specified type.
12820 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12821                                               Type *Ty) const {
12822   // X86 supports extremely general addressing modes.
12823   CodeModel::Model M = getTargetMachine().getCodeModel();
12824   Reloc::Model R = getTargetMachine().getRelocationModel();
12825
12826   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12827   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12828     return false;
12829
12830   if (AM.BaseGV) {
12831     unsigned GVFlags =
12832       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12833
12834     // If a reference to this global requires an extra load, we can't fold it.
12835     if (isGlobalStubReference(GVFlags))
12836       return false;
12837
12838     // If BaseGV requires a register for the PIC base, we cannot also have a
12839     // BaseReg specified.
12840     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12841       return false;
12842
12843     // If lower 4G is not available, then we must use rip-relative addressing.
12844     if ((M != CodeModel::Small || R != Reloc::Static) &&
12845         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12846       return false;
12847   }
12848
12849   switch (AM.Scale) {
12850   case 0:
12851   case 1:
12852   case 2:
12853   case 4:
12854   case 8:
12855     // These scales always work.
12856     break;
12857   case 3:
12858   case 5:
12859   case 9:
12860     // These scales are formed with basereg+scalereg.  Only accept if there is
12861     // no basereg yet.
12862     if (AM.HasBaseReg)
12863       return false;
12864     break;
12865   default:  // Other stuff never works.
12866     return false;
12867   }
12868
12869   return true;
12870 }
12871
12872 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12873   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12874     return false;
12875   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12876   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12877   return NumBits1 > NumBits2;
12878 }
12879
12880 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12881   return isInt<32>(Imm);
12882 }
12883
12884 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12885   // Can also use sub to handle negated immediates.
12886   return isInt<32>(Imm);
12887 }
12888
12889 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12890   if (!VT1.isInteger() || !VT2.isInteger())
12891     return false;
12892   unsigned NumBits1 = VT1.getSizeInBits();
12893   unsigned NumBits2 = VT2.getSizeInBits();
12894   return NumBits1 > NumBits2;
12895 }
12896
12897 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12898   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12899   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12900 }
12901
12902 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12903   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12904   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12905 }
12906
12907 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12908   EVT VT1 = Val.getValueType();
12909   if (isZExtFree(VT1, VT2))
12910     return true;
12911
12912   if (Val.getOpcode() != ISD::LOAD)
12913     return false;
12914
12915   if (!VT1.isSimple() || !VT1.isInteger() ||
12916       !VT2.isSimple() || !VT2.isInteger())
12917     return false;
12918
12919   switch (VT1.getSimpleVT().SimpleTy) {
12920   default: break;
12921   case MVT::i8:
12922   case MVT::i16:
12923   case MVT::i32:
12924     // X86 has 8, 16, and 32-bit zero-extending loads.
12925     return true;
12926   }
12927
12928   return false;
12929 }
12930
12931 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12932   // i16 instructions are longer (0x66 prefix) and potentially slower.
12933   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12934 }
12935
12936 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12937 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12938 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12939 /// are assumed to be legal.
12940 bool
12941 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12942                                       EVT VT) const {
12943   // Very little shuffling can be done for 64-bit vectors right now.
12944   if (VT.getSizeInBits() == 64)
12945     return false;
12946
12947   // FIXME: pshufb, blends, shifts.
12948   return (VT.getVectorNumElements() == 2 ||
12949           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12950           isMOVLMask(M, VT) ||
12951           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12952           isPSHUFDMask(M, VT) ||
12953           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12954           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12955           isPALIGNRMask(M, VT, Subtarget) ||
12956           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12957           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12958           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12959           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12960 }
12961
12962 bool
12963 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12964                                           EVT VT) const {
12965   unsigned NumElts = VT.getVectorNumElements();
12966   // FIXME: This collection of masks seems suspect.
12967   if (NumElts == 2)
12968     return true;
12969   if (NumElts == 4 && VT.is128BitVector()) {
12970     return (isMOVLMask(Mask, VT)  ||
12971             isCommutedMOVLMask(Mask, VT, true) ||
12972             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12973             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12974   }
12975   return false;
12976 }
12977
12978 //===----------------------------------------------------------------------===//
12979 //                           X86 Scheduler Hooks
12980 //===----------------------------------------------------------------------===//
12981
12982 /// Utility function to emit xbegin specifying the start of an RTM region.
12983 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12984                                      const TargetInstrInfo *TII) {
12985   DebugLoc DL = MI->getDebugLoc();
12986
12987   const BasicBlock *BB = MBB->getBasicBlock();
12988   MachineFunction::iterator I = MBB;
12989   ++I;
12990
12991   // For the v = xbegin(), we generate
12992   //
12993   // thisMBB:
12994   //  xbegin sinkMBB
12995   //
12996   // mainMBB:
12997   //  eax = -1
12998   //
12999   // sinkMBB:
13000   //  v = eax
13001
13002   MachineBasicBlock *thisMBB = MBB;
13003   MachineFunction *MF = MBB->getParent();
13004   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13005   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13006   MF->insert(I, mainMBB);
13007   MF->insert(I, sinkMBB);
13008
13009   // Transfer the remainder of BB and its successor edges to sinkMBB.
13010   sinkMBB->splice(sinkMBB->begin(), MBB,
13011                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13012   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13013
13014   // thisMBB:
13015   //  xbegin sinkMBB
13016   //  # fallthrough to mainMBB
13017   //  # abortion to sinkMBB
13018   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13019   thisMBB->addSuccessor(mainMBB);
13020   thisMBB->addSuccessor(sinkMBB);
13021
13022   // mainMBB:
13023   //  EAX = -1
13024   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13025   mainMBB->addSuccessor(sinkMBB);
13026
13027   // sinkMBB:
13028   // EAX is live into the sinkMBB
13029   sinkMBB->addLiveIn(X86::EAX);
13030   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13031           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13032     .addReg(X86::EAX);
13033
13034   MI->eraseFromParent();
13035   return sinkMBB;
13036 }
13037
13038 // Get CMPXCHG opcode for the specified data type.
13039 static unsigned getCmpXChgOpcode(EVT VT) {
13040   switch (VT.getSimpleVT().SimpleTy) {
13041   case MVT::i8:  return X86::LCMPXCHG8;
13042   case MVT::i16: return X86::LCMPXCHG16;
13043   case MVT::i32: return X86::LCMPXCHG32;
13044   case MVT::i64: return X86::LCMPXCHG64;
13045   default:
13046     break;
13047   }
13048   llvm_unreachable("Invalid operand size!");
13049 }
13050
13051 // Get LOAD opcode for the specified data type.
13052 static unsigned getLoadOpcode(EVT VT) {
13053   switch (VT.getSimpleVT().SimpleTy) {
13054   case MVT::i8:  return X86::MOV8rm;
13055   case MVT::i16: return X86::MOV16rm;
13056   case MVT::i32: return X86::MOV32rm;
13057   case MVT::i64: return X86::MOV64rm;
13058   default:
13059     break;
13060   }
13061   llvm_unreachable("Invalid operand size!");
13062 }
13063
13064 // Get opcode of the non-atomic one from the specified atomic instruction.
13065 static unsigned getNonAtomicOpcode(unsigned Opc) {
13066   switch (Opc) {
13067   case X86::ATOMAND8:  return X86::AND8rr;
13068   case X86::ATOMAND16: return X86::AND16rr;
13069   case X86::ATOMAND32: return X86::AND32rr;
13070   case X86::ATOMAND64: return X86::AND64rr;
13071   case X86::ATOMOR8:   return X86::OR8rr;
13072   case X86::ATOMOR16:  return X86::OR16rr;
13073   case X86::ATOMOR32:  return X86::OR32rr;
13074   case X86::ATOMOR64:  return X86::OR64rr;
13075   case X86::ATOMXOR8:  return X86::XOR8rr;
13076   case X86::ATOMXOR16: return X86::XOR16rr;
13077   case X86::ATOMXOR32: return X86::XOR32rr;
13078   case X86::ATOMXOR64: return X86::XOR64rr;
13079   }
13080   llvm_unreachable("Unhandled atomic-load-op opcode!");
13081 }
13082
13083 // Get opcode of the non-atomic one from the specified atomic instruction with
13084 // extra opcode.
13085 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13086                                                unsigned &ExtraOpc) {
13087   switch (Opc) {
13088   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13089   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13090   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13091   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13092   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13093   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13094   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13095   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13096   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13097   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13098   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13099   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13100   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13101   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13102   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13103   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13104   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13105   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13106   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13107   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13108   }
13109   llvm_unreachable("Unhandled atomic-load-op opcode!");
13110 }
13111
13112 // Get opcode of the non-atomic one from the specified atomic instruction for
13113 // 64-bit data type on 32-bit target.
13114 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13115   switch (Opc) {
13116   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13117   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13118   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13119   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13120   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13121   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13122   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13123   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13124   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13125   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13126   }
13127   llvm_unreachable("Unhandled atomic-load-op opcode!");
13128 }
13129
13130 // Get opcode of the non-atomic one from the specified atomic instruction for
13131 // 64-bit data type on 32-bit target with extra opcode.
13132 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13133                                                    unsigned &HiOpc,
13134                                                    unsigned &ExtraOpc) {
13135   switch (Opc) {
13136   case X86::ATOMNAND6432:
13137     ExtraOpc = X86::NOT32r;
13138     HiOpc = X86::AND32rr;
13139     return X86::AND32rr;
13140   }
13141   llvm_unreachable("Unhandled atomic-load-op opcode!");
13142 }
13143
13144 // Get pseudo CMOV opcode from the specified data type.
13145 static unsigned getPseudoCMOVOpc(EVT VT) {
13146   switch (VT.getSimpleVT().SimpleTy) {
13147   case MVT::i8:  return X86::CMOV_GR8;
13148   case MVT::i16: return X86::CMOV_GR16;
13149   case MVT::i32: return X86::CMOV_GR32;
13150   default:
13151     break;
13152   }
13153   llvm_unreachable("Unknown CMOV opcode!");
13154 }
13155
13156 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13157 // They will be translated into a spin-loop or compare-exchange loop from
13158 //
13159 //    ...
13160 //    dst = atomic-fetch-op MI.addr, MI.val
13161 //    ...
13162 //
13163 // to
13164 //
13165 //    ...
13166 //    t1 = LOAD MI.addr
13167 // loop:
13168 //    t4 = phi(t1, t3 / loop)
13169 //    t2 = OP MI.val, t4
13170 //    EAX = t4
13171 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13172 //    t3 = EAX
13173 //    JNE loop
13174 // sink:
13175 //    dst = t3
13176 //    ...
13177 MachineBasicBlock *
13178 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13179                                        MachineBasicBlock *MBB) const {
13180   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13181   DebugLoc DL = MI->getDebugLoc();
13182
13183   MachineFunction *MF = MBB->getParent();
13184   MachineRegisterInfo &MRI = MF->getRegInfo();
13185
13186   const BasicBlock *BB = MBB->getBasicBlock();
13187   MachineFunction::iterator I = MBB;
13188   ++I;
13189
13190   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13191          "Unexpected number of operands");
13192
13193   assert(MI->hasOneMemOperand() &&
13194          "Expected atomic-load-op to have one memoperand");
13195
13196   // Memory Reference
13197   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13198   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13199
13200   unsigned DstReg, SrcReg;
13201   unsigned MemOpndSlot;
13202
13203   unsigned CurOp = 0;
13204
13205   DstReg = MI->getOperand(CurOp++).getReg();
13206   MemOpndSlot = CurOp;
13207   CurOp += X86::AddrNumOperands;
13208   SrcReg = MI->getOperand(CurOp++).getReg();
13209
13210   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13211   MVT::SimpleValueType VT = *RC->vt_begin();
13212   unsigned t1 = MRI.createVirtualRegister(RC);
13213   unsigned t2 = MRI.createVirtualRegister(RC);
13214   unsigned t3 = MRI.createVirtualRegister(RC);
13215   unsigned t4 = MRI.createVirtualRegister(RC);
13216   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13217
13218   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13219   unsigned LOADOpc = getLoadOpcode(VT);
13220
13221   // For the atomic load-arith operator, we generate
13222   //
13223   //  thisMBB:
13224   //    t1 = LOAD [MI.addr]
13225   //  mainMBB:
13226   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13227   //    t1 = OP MI.val, EAX
13228   //    EAX = t4
13229   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13230   //    t3 = EAX
13231   //    JNE mainMBB
13232   //  sinkMBB:
13233   //    dst = t3
13234
13235   MachineBasicBlock *thisMBB = MBB;
13236   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13237   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13238   MF->insert(I, mainMBB);
13239   MF->insert(I, sinkMBB);
13240
13241   MachineInstrBuilder MIB;
13242
13243   // Transfer the remainder of BB and its successor edges to sinkMBB.
13244   sinkMBB->splice(sinkMBB->begin(), MBB,
13245                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13246   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13247
13248   // thisMBB:
13249   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13250   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13251     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13252     if (NewMO.isReg())
13253       NewMO.setIsKill(false);
13254     MIB.addOperand(NewMO);
13255   }
13256   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13257     unsigned flags = (*MMOI)->getFlags();
13258     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13259     MachineMemOperand *MMO =
13260       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13261                                (*MMOI)->getSize(),
13262                                (*MMOI)->getBaseAlignment(),
13263                                (*MMOI)->getTBAAInfo(),
13264                                (*MMOI)->getRanges());
13265     MIB.addMemOperand(MMO);
13266   }
13267
13268   thisMBB->addSuccessor(mainMBB);
13269
13270   // mainMBB:
13271   MachineBasicBlock *origMainMBB = mainMBB;
13272
13273   // Add a PHI.
13274   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13275                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13276
13277   unsigned Opc = MI->getOpcode();
13278   switch (Opc) {
13279   default:
13280     llvm_unreachable("Unhandled atomic-load-op opcode!");
13281   case X86::ATOMAND8:
13282   case X86::ATOMAND16:
13283   case X86::ATOMAND32:
13284   case X86::ATOMAND64:
13285   case X86::ATOMOR8:
13286   case X86::ATOMOR16:
13287   case X86::ATOMOR32:
13288   case X86::ATOMOR64:
13289   case X86::ATOMXOR8:
13290   case X86::ATOMXOR16:
13291   case X86::ATOMXOR32:
13292   case X86::ATOMXOR64: {
13293     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13294     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13295       .addReg(t4);
13296     break;
13297   }
13298   case X86::ATOMNAND8:
13299   case X86::ATOMNAND16:
13300   case X86::ATOMNAND32:
13301   case X86::ATOMNAND64: {
13302     unsigned Tmp = MRI.createVirtualRegister(RC);
13303     unsigned NOTOpc;
13304     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13305     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13306       .addReg(t4);
13307     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13308     break;
13309   }
13310   case X86::ATOMMAX8:
13311   case X86::ATOMMAX16:
13312   case X86::ATOMMAX32:
13313   case X86::ATOMMAX64:
13314   case X86::ATOMMIN8:
13315   case X86::ATOMMIN16:
13316   case X86::ATOMMIN32:
13317   case X86::ATOMMIN64:
13318   case X86::ATOMUMAX8:
13319   case X86::ATOMUMAX16:
13320   case X86::ATOMUMAX32:
13321   case X86::ATOMUMAX64:
13322   case X86::ATOMUMIN8:
13323   case X86::ATOMUMIN16:
13324   case X86::ATOMUMIN32:
13325   case X86::ATOMUMIN64: {
13326     unsigned CMPOpc;
13327     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13328
13329     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13330       .addReg(SrcReg)
13331       .addReg(t4);
13332
13333     if (Subtarget->hasCMov()) {
13334       if (VT != MVT::i8) {
13335         // Native support
13336         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13337           .addReg(SrcReg)
13338           .addReg(t4);
13339       } else {
13340         // Promote i8 to i32 to use CMOV32
13341         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13342         const TargetRegisterClass *RC32 =
13343           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13344         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13345         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13346         unsigned Tmp = MRI.createVirtualRegister(RC32);
13347
13348         unsigned Undef = MRI.createVirtualRegister(RC32);
13349         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13350
13351         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13352           .addReg(Undef)
13353           .addReg(SrcReg)
13354           .addImm(X86::sub_8bit);
13355         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13356           .addReg(Undef)
13357           .addReg(t4)
13358           .addImm(X86::sub_8bit);
13359
13360         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13361           .addReg(SrcReg32)
13362           .addReg(AccReg32);
13363
13364         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13365           .addReg(Tmp, 0, X86::sub_8bit);
13366       }
13367     } else {
13368       // Use pseudo select and lower them.
13369       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13370              "Invalid atomic-load-op transformation!");
13371       unsigned SelOpc = getPseudoCMOVOpc(VT);
13372       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13373       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13374       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13375               .addReg(SrcReg).addReg(t4)
13376               .addImm(CC);
13377       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13378       // Replace the original PHI node as mainMBB is changed after CMOV
13379       // lowering.
13380       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13381         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13382       Phi->eraseFromParent();
13383     }
13384     break;
13385   }
13386   }
13387
13388   // Copy PhyReg back from virtual register.
13389   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13390     .addReg(t4);
13391
13392   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13393   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13394     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13395     if (NewMO.isReg())
13396       NewMO.setIsKill(false);
13397     MIB.addOperand(NewMO);
13398   }
13399   MIB.addReg(t2);
13400   MIB.setMemRefs(MMOBegin, MMOEnd);
13401
13402   // Copy PhyReg back to virtual register.
13403   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13404     .addReg(PhyReg);
13405
13406   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13407
13408   mainMBB->addSuccessor(origMainMBB);
13409   mainMBB->addSuccessor(sinkMBB);
13410
13411   // sinkMBB:
13412   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13413           TII->get(TargetOpcode::COPY), DstReg)
13414     .addReg(t3);
13415
13416   MI->eraseFromParent();
13417   return sinkMBB;
13418 }
13419
13420 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13421 // instructions. They will be translated into a spin-loop or compare-exchange
13422 // loop from
13423 //
13424 //    ...
13425 //    dst = atomic-fetch-op MI.addr, MI.val
13426 //    ...
13427 //
13428 // to
13429 //
13430 //    ...
13431 //    t1L = LOAD [MI.addr + 0]
13432 //    t1H = LOAD [MI.addr + 4]
13433 // loop:
13434 //    t4L = phi(t1L, t3L / loop)
13435 //    t4H = phi(t1H, t3H / loop)
13436 //    t2L = OP MI.val.lo, t4L
13437 //    t2H = OP MI.val.hi, t4H
13438 //    EAX = t4L
13439 //    EDX = t4H
13440 //    EBX = t2L
13441 //    ECX = t2H
13442 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13443 //    t3L = EAX
13444 //    t3H = EDX
13445 //    JNE loop
13446 // sink:
13447 //    dstL = t3L
13448 //    dstH = t3H
13449 //    ...
13450 MachineBasicBlock *
13451 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13452                                            MachineBasicBlock *MBB) const {
13453   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13454   DebugLoc DL = MI->getDebugLoc();
13455
13456   MachineFunction *MF = MBB->getParent();
13457   MachineRegisterInfo &MRI = MF->getRegInfo();
13458
13459   const BasicBlock *BB = MBB->getBasicBlock();
13460   MachineFunction::iterator I = MBB;
13461   ++I;
13462
13463   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13464          "Unexpected number of operands");
13465
13466   assert(MI->hasOneMemOperand() &&
13467          "Expected atomic-load-op32 to have one memoperand");
13468
13469   // Memory Reference
13470   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13471   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13472
13473   unsigned DstLoReg, DstHiReg;
13474   unsigned SrcLoReg, SrcHiReg;
13475   unsigned MemOpndSlot;
13476
13477   unsigned CurOp = 0;
13478
13479   DstLoReg = MI->getOperand(CurOp++).getReg();
13480   DstHiReg = MI->getOperand(CurOp++).getReg();
13481   MemOpndSlot = CurOp;
13482   CurOp += X86::AddrNumOperands;
13483   SrcLoReg = MI->getOperand(CurOp++).getReg();
13484   SrcHiReg = MI->getOperand(CurOp++).getReg();
13485
13486   const TargetRegisterClass *RC = &X86::GR32RegClass;
13487   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13488
13489   unsigned t1L = MRI.createVirtualRegister(RC);
13490   unsigned t1H = MRI.createVirtualRegister(RC);
13491   unsigned t2L = MRI.createVirtualRegister(RC);
13492   unsigned t2H = MRI.createVirtualRegister(RC);
13493   unsigned t3L = MRI.createVirtualRegister(RC);
13494   unsigned t3H = MRI.createVirtualRegister(RC);
13495   unsigned t4L = MRI.createVirtualRegister(RC);
13496   unsigned t4H = MRI.createVirtualRegister(RC);
13497
13498   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13499   unsigned LOADOpc = X86::MOV32rm;
13500
13501   // For the atomic load-arith operator, we generate
13502   //
13503   //  thisMBB:
13504   //    t1L = LOAD [MI.addr + 0]
13505   //    t1H = LOAD [MI.addr + 4]
13506   //  mainMBB:
13507   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13508   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13509   //    t2L = OP MI.val.lo, t4L
13510   //    t2H = OP MI.val.hi, t4H
13511   //    EBX = t2L
13512   //    ECX = t2H
13513   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13514   //    t3L = EAX
13515   //    t3H = EDX
13516   //    JNE loop
13517   //  sinkMBB:
13518   //    dstL = t3L
13519   //    dstH = t3H
13520
13521   MachineBasicBlock *thisMBB = MBB;
13522   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13523   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13524   MF->insert(I, mainMBB);
13525   MF->insert(I, sinkMBB);
13526
13527   MachineInstrBuilder MIB;
13528
13529   // Transfer the remainder of BB and its successor edges to sinkMBB.
13530   sinkMBB->splice(sinkMBB->begin(), MBB,
13531                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13532   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13533
13534   // thisMBB:
13535   // Lo
13536   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13537   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13538     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13539     if (NewMO.isReg())
13540       NewMO.setIsKill(false);
13541     MIB.addOperand(NewMO);
13542   }
13543   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13544     unsigned flags = (*MMOI)->getFlags();
13545     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13546     MachineMemOperand *MMO =
13547       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13548                                (*MMOI)->getSize(),
13549                                (*MMOI)->getBaseAlignment(),
13550                                (*MMOI)->getTBAAInfo(),
13551                                (*MMOI)->getRanges());
13552     MIB.addMemOperand(MMO);
13553   };
13554   MachineInstr *LowMI = MIB;
13555
13556   // Hi
13557   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13558   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13559     if (i == X86::AddrDisp) {
13560       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13561     } else {
13562       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13563       if (NewMO.isReg())
13564         NewMO.setIsKill(false);
13565       MIB.addOperand(NewMO);
13566     }
13567   }
13568   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13569
13570   thisMBB->addSuccessor(mainMBB);
13571
13572   // mainMBB:
13573   MachineBasicBlock *origMainMBB = mainMBB;
13574
13575   // Add PHIs.
13576   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13577                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13578   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13579                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13580
13581   unsigned Opc = MI->getOpcode();
13582   switch (Opc) {
13583   default:
13584     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13585   case X86::ATOMAND6432:
13586   case X86::ATOMOR6432:
13587   case X86::ATOMXOR6432:
13588   case X86::ATOMADD6432:
13589   case X86::ATOMSUB6432: {
13590     unsigned HiOpc;
13591     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13592     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13593       .addReg(SrcLoReg);
13594     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13595       .addReg(SrcHiReg);
13596     break;
13597   }
13598   case X86::ATOMNAND6432: {
13599     unsigned HiOpc, NOTOpc;
13600     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13601     unsigned TmpL = MRI.createVirtualRegister(RC);
13602     unsigned TmpH = MRI.createVirtualRegister(RC);
13603     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13604       .addReg(t4L);
13605     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13606       .addReg(t4H);
13607     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13608     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13609     break;
13610   }
13611   case X86::ATOMMAX6432:
13612   case X86::ATOMMIN6432:
13613   case X86::ATOMUMAX6432:
13614   case X86::ATOMUMIN6432: {
13615     unsigned HiOpc;
13616     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13617     unsigned cL = MRI.createVirtualRegister(RC8);
13618     unsigned cH = MRI.createVirtualRegister(RC8);
13619     unsigned cL32 = MRI.createVirtualRegister(RC);
13620     unsigned cH32 = MRI.createVirtualRegister(RC);
13621     unsigned cc = MRI.createVirtualRegister(RC);
13622     // cl := cmp src_lo, lo
13623     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13624       .addReg(SrcLoReg).addReg(t4L);
13625     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13626     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13627     // ch := cmp src_hi, hi
13628     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13629       .addReg(SrcHiReg).addReg(t4H);
13630     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13631     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13632     // cc := if (src_hi == hi) ? cl : ch;
13633     if (Subtarget->hasCMov()) {
13634       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13635         .addReg(cH32).addReg(cL32);
13636     } else {
13637       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13638               .addReg(cH32).addReg(cL32)
13639               .addImm(X86::COND_E);
13640       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13641     }
13642     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13643     if (Subtarget->hasCMov()) {
13644       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13645         .addReg(SrcLoReg).addReg(t4L);
13646       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13647         .addReg(SrcHiReg).addReg(t4H);
13648     } else {
13649       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13650               .addReg(SrcLoReg).addReg(t4L)
13651               .addImm(X86::COND_NE);
13652       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13653       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13654       // 2nd CMOV lowering.
13655       mainMBB->addLiveIn(X86::EFLAGS);
13656       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13657               .addReg(SrcHiReg).addReg(t4H)
13658               .addImm(X86::COND_NE);
13659       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13660       // Replace the original PHI node as mainMBB is changed after CMOV
13661       // lowering.
13662       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13663         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13664       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13665         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13666       PhiL->eraseFromParent();
13667       PhiH->eraseFromParent();
13668     }
13669     break;
13670   }
13671   case X86::ATOMSWAP6432: {
13672     unsigned HiOpc;
13673     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13674     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13675     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13676     break;
13677   }
13678   }
13679
13680   // Copy EDX:EAX back from HiReg:LoReg
13681   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13682   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13683   // Copy ECX:EBX from t1H:t1L
13684   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13685   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13686
13687   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13688   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13689     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13690     if (NewMO.isReg())
13691       NewMO.setIsKill(false);
13692     MIB.addOperand(NewMO);
13693   }
13694   MIB.setMemRefs(MMOBegin, MMOEnd);
13695
13696   // Copy EDX:EAX back to t3H:t3L
13697   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13698   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13699
13700   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13701
13702   mainMBB->addSuccessor(origMainMBB);
13703   mainMBB->addSuccessor(sinkMBB);
13704
13705   // sinkMBB:
13706   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13707           TII->get(TargetOpcode::COPY), DstLoReg)
13708     .addReg(t3L);
13709   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13710           TII->get(TargetOpcode::COPY), DstHiReg)
13711     .addReg(t3H);
13712
13713   MI->eraseFromParent();
13714   return sinkMBB;
13715 }
13716
13717 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13718 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13719 // in the .td file.
13720 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13721                                        const TargetInstrInfo *TII) {
13722   unsigned Opc;
13723   switch (MI->getOpcode()) {
13724   default: llvm_unreachable("illegal opcode!");
13725   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13726   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13727   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13728   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13729   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13730   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13731   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13732   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13733   }
13734
13735   DebugLoc dl = MI->getDebugLoc();
13736   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13737
13738   unsigned NumArgs = MI->getNumOperands();
13739   for (unsigned i = 1; i < NumArgs; ++i) {
13740     MachineOperand &Op = MI->getOperand(i);
13741     if (!(Op.isReg() && Op.isImplicit()))
13742       MIB.addOperand(Op);
13743   }
13744   if (MI->hasOneMemOperand())
13745     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13746
13747   BuildMI(*BB, MI, dl,
13748     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13749     .addReg(X86::XMM0);
13750
13751   MI->eraseFromParent();
13752   return BB;
13753 }
13754
13755 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13756 // defs in an instruction pattern
13757 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13758                                        const TargetInstrInfo *TII) {
13759   unsigned Opc;
13760   switch (MI->getOpcode()) {
13761   default: llvm_unreachable("illegal opcode!");
13762   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13763   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13764   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13765   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13766   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13767   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13768   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13769   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13770   }
13771
13772   DebugLoc dl = MI->getDebugLoc();
13773   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13774
13775   unsigned NumArgs = MI->getNumOperands(); // remove the results
13776   for (unsigned i = 1; i < NumArgs; ++i) {
13777     MachineOperand &Op = MI->getOperand(i);
13778     if (!(Op.isReg() && Op.isImplicit()))
13779       MIB.addOperand(Op);
13780   }
13781   if (MI->hasOneMemOperand())
13782     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13783
13784   BuildMI(*BB, MI, dl,
13785     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13786     .addReg(X86::ECX);
13787
13788   MI->eraseFromParent();
13789   return BB;
13790 }
13791
13792 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13793                                        const TargetInstrInfo *TII,
13794                                        const X86Subtarget* Subtarget) {
13795   DebugLoc dl = MI->getDebugLoc();
13796
13797   // Address into RAX/EAX, other two args into ECX, EDX.
13798   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13799   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13800   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13801   for (int i = 0; i < X86::AddrNumOperands; ++i)
13802     MIB.addOperand(MI->getOperand(i));
13803
13804   unsigned ValOps = X86::AddrNumOperands;
13805   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13806     .addReg(MI->getOperand(ValOps).getReg());
13807   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13808     .addReg(MI->getOperand(ValOps+1).getReg());
13809
13810   // The instruction doesn't actually take any operands though.
13811   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13812
13813   MI->eraseFromParent(); // The pseudo is gone now.
13814   return BB;
13815 }
13816
13817 MachineBasicBlock *
13818 X86TargetLowering::EmitVAARG64WithCustomInserter(
13819                    MachineInstr *MI,
13820                    MachineBasicBlock *MBB) const {
13821   // Emit va_arg instruction on X86-64.
13822
13823   // Operands to this pseudo-instruction:
13824   // 0  ) Output        : destination address (reg)
13825   // 1-5) Input         : va_list address (addr, i64mem)
13826   // 6  ) ArgSize       : Size (in bytes) of vararg type
13827   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13828   // 8  ) Align         : Alignment of type
13829   // 9  ) EFLAGS (implicit-def)
13830
13831   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13832   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13833
13834   unsigned DestReg = MI->getOperand(0).getReg();
13835   MachineOperand &Base = MI->getOperand(1);
13836   MachineOperand &Scale = MI->getOperand(2);
13837   MachineOperand &Index = MI->getOperand(3);
13838   MachineOperand &Disp = MI->getOperand(4);
13839   MachineOperand &Segment = MI->getOperand(5);
13840   unsigned ArgSize = MI->getOperand(6).getImm();
13841   unsigned ArgMode = MI->getOperand(7).getImm();
13842   unsigned Align = MI->getOperand(8).getImm();
13843
13844   // Memory Reference
13845   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13846   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13847   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13848
13849   // Machine Information
13850   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13851   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13852   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13853   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13854   DebugLoc DL = MI->getDebugLoc();
13855
13856   // struct va_list {
13857   //   i32   gp_offset
13858   //   i32   fp_offset
13859   //   i64   overflow_area (address)
13860   //   i64   reg_save_area (address)
13861   // }
13862   // sizeof(va_list) = 24
13863   // alignment(va_list) = 8
13864
13865   unsigned TotalNumIntRegs = 6;
13866   unsigned TotalNumXMMRegs = 8;
13867   bool UseGPOffset = (ArgMode == 1);
13868   bool UseFPOffset = (ArgMode == 2);
13869   unsigned MaxOffset = TotalNumIntRegs * 8 +
13870                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13871
13872   /* Align ArgSize to a multiple of 8 */
13873   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13874   bool NeedsAlign = (Align > 8);
13875
13876   MachineBasicBlock *thisMBB = MBB;
13877   MachineBasicBlock *overflowMBB;
13878   MachineBasicBlock *offsetMBB;
13879   MachineBasicBlock *endMBB;
13880
13881   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13882   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13883   unsigned OffsetReg = 0;
13884
13885   if (!UseGPOffset && !UseFPOffset) {
13886     // If we only pull from the overflow region, we don't create a branch.
13887     // We don't need to alter control flow.
13888     OffsetDestReg = 0; // unused
13889     OverflowDestReg = DestReg;
13890
13891     offsetMBB = NULL;
13892     overflowMBB = thisMBB;
13893     endMBB = thisMBB;
13894   } else {
13895     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13896     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13897     // If not, pull from overflow_area. (branch to overflowMBB)
13898     //
13899     //       thisMBB
13900     //         |     .
13901     //         |        .
13902     //     offsetMBB   overflowMBB
13903     //         |        .
13904     //         |     .
13905     //        endMBB
13906
13907     // Registers for the PHI in endMBB
13908     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13909     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13910
13911     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13912     MachineFunction *MF = MBB->getParent();
13913     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13914     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13915     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13916
13917     MachineFunction::iterator MBBIter = MBB;
13918     ++MBBIter;
13919
13920     // Insert the new basic blocks
13921     MF->insert(MBBIter, offsetMBB);
13922     MF->insert(MBBIter, overflowMBB);
13923     MF->insert(MBBIter, endMBB);
13924
13925     // Transfer the remainder of MBB and its successor edges to endMBB.
13926     endMBB->splice(endMBB->begin(), thisMBB,
13927                     llvm::next(MachineBasicBlock::iterator(MI)),
13928                     thisMBB->end());
13929     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13930
13931     // Make offsetMBB and overflowMBB successors of thisMBB
13932     thisMBB->addSuccessor(offsetMBB);
13933     thisMBB->addSuccessor(overflowMBB);
13934
13935     // endMBB is a successor of both offsetMBB and overflowMBB
13936     offsetMBB->addSuccessor(endMBB);
13937     overflowMBB->addSuccessor(endMBB);
13938
13939     // Load the offset value into a register
13940     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13941     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13942       .addOperand(Base)
13943       .addOperand(Scale)
13944       .addOperand(Index)
13945       .addDisp(Disp, UseFPOffset ? 4 : 0)
13946       .addOperand(Segment)
13947       .setMemRefs(MMOBegin, MMOEnd);
13948
13949     // Check if there is enough room left to pull this argument.
13950     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13951       .addReg(OffsetReg)
13952       .addImm(MaxOffset + 8 - ArgSizeA8);
13953
13954     // Branch to "overflowMBB" if offset >= max
13955     // Fall through to "offsetMBB" otherwise
13956     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13957       .addMBB(overflowMBB);
13958   }
13959
13960   // In offsetMBB, emit code to use the reg_save_area.
13961   if (offsetMBB) {
13962     assert(OffsetReg != 0);
13963
13964     // Read the reg_save_area address.
13965     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13966     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13967       .addOperand(Base)
13968       .addOperand(Scale)
13969       .addOperand(Index)
13970       .addDisp(Disp, 16)
13971       .addOperand(Segment)
13972       .setMemRefs(MMOBegin, MMOEnd);
13973
13974     // Zero-extend the offset
13975     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13976       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13977         .addImm(0)
13978         .addReg(OffsetReg)
13979         .addImm(X86::sub_32bit);
13980
13981     // Add the offset to the reg_save_area to get the final address.
13982     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13983       .addReg(OffsetReg64)
13984       .addReg(RegSaveReg);
13985
13986     // Compute the offset for the next argument
13987     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13988     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13989       .addReg(OffsetReg)
13990       .addImm(UseFPOffset ? 16 : 8);
13991
13992     // Store it back into the va_list.
13993     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13994       .addOperand(Base)
13995       .addOperand(Scale)
13996       .addOperand(Index)
13997       .addDisp(Disp, UseFPOffset ? 4 : 0)
13998       .addOperand(Segment)
13999       .addReg(NextOffsetReg)
14000       .setMemRefs(MMOBegin, MMOEnd);
14001
14002     // Jump to endMBB
14003     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14004       .addMBB(endMBB);
14005   }
14006
14007   //
14008   // Emit code to use overflow area
14009   //
14010
14011   // Load the overflow_area address into a register.
14012   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14013   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14014     .addOperand(Base)
14015     .addOperand(Scale)
14016     .addOperand(Index)
14017     .addDisp(Disp, 8)
14018     .addOperand(Segment)
14019     .setMemRefs(MMOBegin, MMOEnd);
14020
14021   // If we need to align it, do so. Otherwise, just copy the address
14022   // to OverflowDestReg.
14023   if (NeedsAlign) {
14024     // Align the overflow address
14025     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14026     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14027
14028     // aligned_addr = (addr + (align-1)) & ~(align-1)
14029     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14030       .addReg(OverflowAddrReg)
14031       .addImm(Align-1);
14032
14033     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14034       .addReg(TmpReg)
14035       .addImm(~(uint64_t)(Align-1));
14036   } else {
14037     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14038       .addReg(OverflowAddrReg);
14039   }
14040
14041   // Compute the next overflow address after this argument.
14042   // (the overflow address should be kept 8-byte aligned)
14043   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14044   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14045     .addReg(OverflowDestReg)
14046     .addImm(ArgSizeA8);
14047
14048   // Store the new overflow address.
14049   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14050     .addOperand(Base)
14051     .addOperand(Scale)
14052     .addOperand(Index)
14053     .addDisp(Disp, 8)
14054     .addOperand(Segment)
14055     .addReg(NextAddrReg)
14056     .setMemRefs(MMOBegin, MMOEnd);
14057
14058   // If we branched, emit the PHI to the front of endMBB.
14059   if (offsetMBB) {
14060     BuildMI(*endMBB, endMBB->begin(), DL,
14061             TII->get(X86::PHI), DestReg)
14062       .addReg(OffsetDestReg).addMBB(offsetMBB)
14063       .addReg(OverflowDestReg).addMBB(overflowMBB);
14064   }
14065
14066   // Erase the pseudo instruction
14067   MI->eraseFromParent();
14068
14069   return endMBB;
14070 }
14071
14072 MachineBasicBlock *
14073 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14074                                                  MachineInstr *MI,
14075                                                  MachineBasicBlock *MBB) const {
14076   // Emit code to save XMM registers to the stack. The ABI says that the
14077   // number of registers to save is given in %al, so it's theoretically
14078   // possible to do an indirect jump trick to avoid saving all of them,
14079   // however this code takes a simpler approach and just executes all
14080   // of the stores if %al is non-zero. It's less code, and it's probably
14081   // easier on the hardware branch predictor, and stores aren't all that
14082   // expensive anyway.
14083
14084   // Create the new basic blocks. One block contains all the XMM stores,
14085   // and one block is the final destination regardless of whether any
14086   // stores were performed.
14087   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14088   MachineFunction *F = MBB->getParent();
14089   MachineFunction::iterator MBBIter = MBB;
14090   ++MBBIter;
14091   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14092   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14093   F->insert(MBBIter, XMMSaveMBB);
14094   F->insert(MBBIter, EndMBB);
14095
14096   // Transfer the remainder of MBB and its successor edges to EndMBB.
14097   EndMBB->splice(EndMBB->begin(), MBB,
14098                  llvm::next(MachineBasicBlock::iterator(MI)),
14099                  MBB->end());
14100   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14101
14102   // The original block will now fall through to the XMM save block.
14103   MBB->addSuccessor(XMMSaveMBB);
14104   // The XMMSaveMBB will fall through to the end block.
14105   XMMSaveMBB->addSuccessor(EndMBB);
14106
14107   // Now add the instructions.
14108   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14109   DebugLoc DL = MI->getDebugLoc();
14110
14111   unsigned CountReg = MI->getOperand(0).getReg();
14112   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14113   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14114
14115   if (!Subtarget->isTargetWin64()) {
14116     // If %al is 0, branch around the XMM save block.
14117     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14118     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14119     MBB->addSuccessor(EndMBB);
14120   }
14121
14122   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14123   // In the XMM save block, save all the XMM argument registers.
14124   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14125     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14126     MachineMemOperand *MMO =
14127       F->getMachineMemOperand(
14128           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14129         MachineMemOperand::MOStore,
14130         /*Size=*/16, /*Align=*/16);
14131     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14132       .addFrameIndex(RegSaveFrameIndex)
14133       .addImm(/*Scale=*/1)
14134       .addReg(/*IndexReg=*/0)
14135       .addImm(/*Disp=*/Offset)
14136       .addReg(/*Segment=*/0)
14137       .addReg(MI->getOperand(i).getReg())
14138       .addMemOperand(MMO);
14139   }
14140
14141   MI->eraseFromParent();   // The pseudo instruction is gone now.
14142
14143   return EndMBB;
14144 }
14145
14146 // The EFLAGS operand of SelectItr might be missing a kill marker
14147 // because there were multiple uses of EFLAGS, and ISel didn't know
14148 // which to mark. Figure out whether SelectItr should have had a
14149 // kill marker, and set it if it should. Returns the correct kill
14150 // marker value.
14151 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14152                                      MachineBasicBlock* BB,
14153                                      const TargetRegisterInfo* TRI) {
14154   // Scan forward through BB for a use/def of EFLAGS.
14155   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14156   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14157     const MachineInstr& mi = *miI;
14158     if (mi.readsRegister(X86::EFLAGS))
14159       return false;
14160     if (mi.definesRegister(X86::EFLAGS))
14161       break; // Should have kill-flag - update below.
14162   }
14163
14164   // If we hit the end of the block, check whether EFLAGS is live into a
14165   // successor.
14166   if (miI == BB->end()) {
14167     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14168                                           sEnd = BB->succ_end();
14169          sItr != sEnd; ++sItr) {
14170       MachineBasicBlock* succ = *sItr;
14171       if (succ->isLiveIn(X86::EFLAGS))
14172         return false;
14173     }
14174   }
14175
14176   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14177   // out. SelectMI should have a kill flag on EFLAGS.
14178   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14179   return true;
14180 }
14181
14182 MachineBasicBlock *
14183 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14184                                      MachineBasicBlock *BB) const {
14185   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14186   DebugLoc DL = MI->getDebugLoc();
14187
14188   // To "insert" a SELECT_CC instruction, we actually have to insert the
14189   // diamond control-flow pattern.  The incoming instruction knows the
14190   // destination vreg to set, the condition code register to branch on, the
14191   // true/false values to select between, and a branch opcode to use.
14192   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14193   MachineFunction::iterator It = BB;
14194   ++It;
14195
14196   //  thisMBB:
14197   //  ...
14198   //   TrueVal = ...
14199   //   cmpTY ccX, r1, r2
14200   //   bCC copy1MBB
14201   //   fallthrough --> copy0MBB
14202   MachineBasicBlock *thisMBB = BB;
14203   MachineFunction *F = BB->getParent();
14204   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14205   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14206   F->insert(It, copy0MBB);
14207   F->insert(It, sinkMBB);
14208
14209   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14210   // live into the sink and copy blocks.
14211   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14212   if (!MI->killsRegister(X86::EFLAGS) &&
14213       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14214     copy0MBB->addLiveIn(X86::EFLAGS);
14215     sinkMBB->addLiveIn(X86::EFLAGS);
14216   }
14217
14218   // Transfer the remainder of BB and its successor edges to sinkMBB.
14219   sinkMBB->splice(sinkMBB->begin(), BB,
14220                   llvm::next(MachineBasicBlock::iterator(MI)),
14221                   BB->end());
14222   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14223
14224   // Add the true and fallthrough blocks as its successors.
14225   BB->addSuccessor(copy0MBB);
14226   BB->addSuccessor(sinkMBB);
14227
14228   // Create the conditional branch instruction.
14229   unsigned Opc =
14230     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14231   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14232
14233   //  copy0MBB:
14234   //   %FalseValue = ...
14235   //   # fallthrough to sinkMBB
14236   copy0MBB->addSuccessor(sinkMBB);
14237
14238   //  sinkMBB:
14239   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14240   //  ...
14241   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14242           TII->get(X86::PHI), MI->getOperand(0).getReg())
14243     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14244     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14245
14246   MI->eraseFromParent();   // The pseudo instruction is gone now.
14247   return sinkMBB;
14248 }
14249
14250 MachineBasicBlock *
14251 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14252                                         bool Is64Bit) const {
14253   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14254   DebugLoc DL = MI->getDebugLoc();
14255   MachineFunction *MF = BB->getParent();
14256   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14257
14258   assert(getTargetMachine().Options.EnableSegmentedStacks);
14259
14260   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14261   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14262
14263   // BB:
14264   //  ... [Till the alloca]
14265   // If stacklet is not large enough, jump to mallocMBB
14266   //
14267   // bumpMBB:
14268   //  Allocate by subtracting from RSP
14269   //  Jump to continueMBB
14270   //
14271   // mallocMBB:
14272   //  Allocate by call to runtime
14273   //
14274   // continueMBB:
14275   //  ...
14276   //  [rest of original BB]
14277   //
14278
14279   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14280   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14281   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14282
14283   MachineRegisterInfo &MRI = MF->getRegInfo();
14284   const TargetRegisterClass *AddrRegClass =
14285     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14286
14287   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14288     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14289     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14290     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14291     sizeVReg = MI->getOperand(1).getReg(),
14292     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14293
14294   MachineFunction::iterator MBBIter = BB;
14295   ++MBBIter;
14296
14297   MF->insert(MBBIter, bumpMBB);
14298   MF->insert(MBBIter, mallocMBB);
14299   MF->insert(MBBIter, continueMBB);
14300
14301   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14302                       (MachineBasicBlock::iterator(MI)), BB->end());
14303   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14304
14305   // Add code to the main basic block to check if the stack limit has been hit,
14306   // and if so, jump to mallocMBB otherwise to bumpMBB.
14307   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14308   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14309     .addReg(tmpSPVReg).addReg(sizeVReg);
14310   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14311     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14312     .addReg(SPLimitVReg);
14313   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14314
14315   // bumpMBB simply decreases the stack pointer, since we know the current
14316   // stacklet has enough space.
14317   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14318     .addReg(SPLimitVReg);
14319   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14320     .addReg(SPLimitVReg);
14321   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14322
14323   // Calls into a routine in libgcc to allocate more space from the heap.
14324   const uint32_t *RegMask =
14325     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14326   if (Is64Bit) {
14327     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14328       .addReg(sizeVReg);
14329     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14330       .addExternalSymbol("__morestack_allocate_stack_space")
14331       .addRegMask(RegMask)
14332       .addReg(X86::RDI, RegState::Implicit)
14333       .addReg(X86::RAX, RegState::ImplicitDefine);
14334   } else {
14335     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14336       .addImm(12);
14337     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14338     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14339       .addExternalSymbol("__morestack_allocate_stack_space")
14340       .addRegMask(RegMask)
14341       .addReg(X86::EAX, RegState::ImplicitDefine);
14342   }
14343
14344   if (!Is64Bit)
14345     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14346       .addImm(16);
14347
14348   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14349     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14350   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14351
14352   // Set up the CFG correctly.
14353   BB->addSuccessor(bumpMBB);
14354   BB->addSuccessor(mallocMBB);
14355   mallocMBB->addSuccessor(continueMBB);
14356   bumpMBB->addSuccessor(continueMBB);
14357
14358   // Take care of the PHI nodes.
14359   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14360           MI->getOperand(0).getReg())
14361     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14362     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14363
14364   // Delete the original pseudo instruction.
14365   MI->eraseFromParent();
14366
14367   // And we're done.
14368   return continueMBB;
14369 }
14370
14371 MachineBasicBlock *
14372 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14373                                           MachineBasicBlock *BB) const {
14374   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14375   DebugLoc DL = MI->getDebugLoc();
14376
14377   assert(!Subtarget->isTargetEnvMacho());
14378
14379   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14380   // non-trivial part is impdef of ESP.
14381
14382   if (Subtarget->isTargetWin64()) {
14383     if (Subtarget->isTargetCygMing()) {
14384       // ___chkstk(Mingw64):
14385       // Clobbers R10, R11, RAX and EFLAGS.
14386       // Updates RSP.
14387       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14388         .addExternalSymbol("___chkstk")
14389         .addReg(X86::RAX, RegState::Implicit)
14390         .addReg(X86::RSP, RegState::Implicit)
14391         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14392         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14393         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14394     } else {
14395       // __chkstk(MSVCRT): does not update stack pointer.
14396       // Clobbers R10, R11 and EFLAGS.
14397       // FIXME: RAX(allocated size) might be reused and not killed.
14398       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14399         .addExternalSymbol("__chkstk")
14400         .addReg(X86::RAX, RegState::Implicit)
14401         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14402       // RAX has the offset to subtracted from RSP.
14403       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14404         .addReg(X86::RSP)
14405         .addReg(X86::RAX);
14406     }
14407   } else {
14408     const char *StackProbeSymbol =
14409       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14410
14411     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14412       .addExternalSymbol(StackProbeSymbol)
14413       .addReg(X86::EAX, RegState::Implicit)
14414       .addReg(X86::ESP, RegState::Implicit)
14415       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14416       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14417       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14418   }
14419
14420   MI->eraseFromParent();   // The pseudo instruction is gone now.
14421   return BB;
14422 }
14423
14424 MachineBasicBlock *
14425 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14426                                       MachineBasicBlock *BB) const {
14427   // This is pretty easy.  We're taking the value that we received from
14428   // our load from the relocation, sticking it in either RDI (x86-64)
14429   // or EAX and doing an indirect call.  The return value will then
14430   // be in the normal return register.
14431   const X86InstrInfo *TII
14432     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14433   DebugLoc DL = MI->getDebugLoc();
14434   MachineFunction *F = BB->getParent();
14435
14436   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14437   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14438
14439   // Get a register mask for the lowered call.
14440   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14441   // proper register mask.
14442   const uint32_t *RegMask =
14443     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14444   if (Subtarget->is64Bit()) {
14445     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14446                                       TII->get(X86::MOV64rm), X86::RDI)
14447     .addReg(X86::RIP)
14448     .addImm(0).addReg(0)
14449     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14450                       MI->getOperand(3).getTargetFlags())
14451     .addReg(0);
14452     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14453     addDirectMem(MIB, X86::RDI);
14454     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14455   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14456     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14457                                       TII->get(X86::MOV32rm), X86::EAX)
14458     .addReg(0)
14459     .addImm(0).addReg(0)
14460     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14461                       MI->getOperand(3).getTargetFlags())
14462     .addReg(0);
14463     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14464     addDirectMem(MIB, X86::EAX);
14465     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14466   } else {
14467     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14468                                       TII->get(X86::MOV32rm), X86::EAX)
14469     .addReg(TII->getGlobalBaseReg(F))
14470     .addImm(0).addReg(0)
14471     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14472                       MI->getOperand(3).getTargetFlags())
14473     .addReg(0);
14474     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14475     addDirectMem(MIB, X86::EAX);
14476     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14477   }
14478
14479   MI->eraseFromParent(); // The pseudo instruction is gone now.
14480   return BB;
14481 }
14482
14483 MachineBasicBlock *
14484 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14485                                     MachineBasicBlock *MBB) const {
14486   DebugLoc DL = MI->getDebugLoc();
14487   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14488
14489   MachineFunction *MF = MBB->getParent();
14490   MachineRegisterInfo &MRI = MF->getRegInfo();
14491
14492   const BasicBlock *BB = MBB->getBasicBlock();
14493   MachineFunction::iterator I = MBB;
14494   ++I;
14495
14496   // Memory Reference
14497   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14498   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14499
14500   unsigned DstReg;
14501   unsigned MemOpndSlot = 0;
14502
14503   unsigned CurOp = 0;
14504
14505   DstReg = MI->getOperand(CurOp++).getReg();
14506   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14507   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14508   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14509   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14510
14511   MemOpndSlot = CurOp;
14512
14513   MVT PVT = getPointerTy();
14514   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14515          "Invalid Pointer Size!");
14516
14517   // For v = setjmp(buf), we generate
14518   //
14519   // thisMBB:
14520   //  buf[LabelOffset] = restoreMBB
14521   //  SjLjSetup restoreMBB
14522   //
14523   // mainMBB:
14524   //  v_main = 0
14525   //
14526   // sinkMBB:
14527   //  v = phi(main, restore)
14528   //
14529   // restoreMBB:
14530   //  v_restore = 1
14531
14532   MachineBasicBlock *thisMBB = MBB;
14533   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14534   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14535   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14536   MF->insert(I, mainMBB);
14537   MF->insert(I, sinkMBB);
14538   MF->push_back(restoreMBB);
14539
14540   MachineInstrBuilder MIB;
14541
14542   // Transfer the remainder of BB and its successor edges to sinkMBB.
14543   sinkMBB->splice(sinkMBB->begin(), MBB,
14544                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14545   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14546
14547   // thisMBB:
14548   unsigned PtrStoreOpc = 0;
14549   unsigned LabelReg = 0;
14550   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14551   Reloc::Model RM = getTargetMachine().getRelocationModel();
14552   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14553                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14554
14555   // Prepare IP either in reg or imm.
14556   if (!UseImmLabel) {
14557     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14558     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14559     LabelReg = MRI.createVirtualRegister(PtrRC);
14560     if (Subtarget->is64Bit()) {
14561       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14562               .addReg(X86::RIP)
14563               .addImm(0)
14564               .addReg(0)
14565               .addMBB(restoreMBB)
14566               .addReg(0);
14567     } else {
14568       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14569       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14570               .addReg(XII->getGlobalBaseReg(MF))
14571               .addImm(0)
14572               .addReg(0)
14573               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14574               .addReg(0);
14575     }
14576   } else
14577     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14578   // Store IP
14579   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14580   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14581     if (i == X86::AddrDisp)
14582       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14583     else
14584       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14585   }
14586   if (!UseImmLabel)
14587     MIB.addReg(LabelReg);
14588   else
14589     MIB.addMBB(restoreMBB);
14590   MIB.setMemRefs(MMOBegin, MMOEnd);
14591   // Setup
14592   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14593           .addMBB(restoreMBB);
14594   MIB.addRegMask(RegInfo->getNoPreservedMask());
14595   thisMBB->addSuccessor(mainMBB);
14596   thisMBB->addSuccessor(restoreMBB);
14597
14598   // mainMBB:
14599   //  EAX = 0
14600   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14601   mainMBB->addSuccessor(sinkMBB);
14602
14603   // sinkMBB:
14604   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14605           TII->get(X86::PHI), DstReg)
14606     .addReg(mainDstReg).addMBB(mainMBB)
14607     .addReg(restoreDstReg).addMBB(restoreMBB);
14608
14609   // restoreMBB:
14610   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14611   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14612   restoreMBB->addSuccessor(sinkMBB);
14613
14614   MI->eraseFromParent();
14615   return sinkMBB;
14616 }
14617
14618 MachineBasicBlock *
14619 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14620                                      MachineBasicBlock *MBB) const {
14621   DebugLoc DL = MI->getDebugLoc();
14622   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14623
14624   MachineFunction *MF = MBB->getParent();
14625   MachineRegisterInfo &MRI = MF->getRegInfo();
14626
14627   // Memory Reference
14628   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14629   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14630
14631   MVT PVT = getPointerTy();
14632   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14633          "Invalid Pointer Size!");
14634
14635   const TargetRegisterClass *RC =
14636     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14637   unsigned Tmp = MRI.createVirtualRegister(RC);
14638   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14639   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14640   unsigned SP = RegInfo->getStackRegister();
14641
14642   MachineInstrBuilder MIB;
14643
14644   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14645   const int64_t SPOffset = 2 * PVT.getStoreSize();
14646
14647   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14648   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14649
14650   // Reload FP
14651   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14652   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14653     MIB.addOperand(MI->getOperand(i));
14654   MIB.setMemRefs(MMOBegin, MMOEnd);
14655   // Reload IP
14656   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14657   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14658     if (i == X86::AddrDisp)
14659       MIB.addDisp(MI->getOperand(i), LabelOffset);
14660     else
14661       MIB.addOperand(MI->getOperand(i));
14662   }
14663   MIB.setMemRefs(MMOBegin, MMOEnd);
14664   // Reload SP
14665   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14666   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14667     if (i == X86::AddrDisp)
14668       MIB.addDisp(MI->getOperand(i), SPOffset);
14669     else
14670       MIB.addOperand(MI->getOperand(i));
14671   }
14672   MIB.setMemRefs(MMOBegin, MMOEnd);
14673   // Jump
14674   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14675
14676   MI->eraseFromParent();
14677   return MBB;
14678 }
14679
14680 MachineBasicBlock *
14681 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14682                                                MachineBasicBlock *BB) const {
14683   switch (MI->getOpcode()) {
14684   default: llvm_unreachable("Unexpected instr type to insert");
14685   case X86::TAILJMPd64:
14686   case X86::TAILJMPr64:
14687   case X86::TAILJMPm64:
14688     llvm_unreachable("TAILJMP64 would not be touched here.");
14689   case X86::TCRETURNdi64:
14690   case X86::TCRETURNri64:
14691   case X86::TCRETURNmi64:
14692     return BB;
14693   case X86::WIN_ALLOCA:
14694     return EmitLoweredWinAlloca(MI, BB);
14695   case X86::SEG_ALLOCA_32:
14696     return EmitLoweredSegAlloca(MI, BB, false);
14697   case X86::SEG_ALLOCA_64:
14698     return EmitLoweredSegAlloca(MI, BB, true);
14699   case X86::TLSCall_32:
14700   case X86::TLSCall_64:
14701     return EmitLoweredTLSCall(MI, BB);
14702   case X86::CMOV_GR8:
14703   case X86::CMOV_FR32:
14704   case X86::CMOV_FR64:
14705   case X86::CMOV_V4F32:
14706   case X86::CMOV_V2F64:
14707   case X86::CMOV_V2I64:
14708   case X86::CMOV_V8F32:
14709   case X86::CMOV_V4F64:
14710   case X86::CMOV_V4I64:
14711   case X86::CMOV_GR16:
14712   case X86::CMOV_GR32:
14713   case X86::CMOV_RFP32:
14714   case X86::CMOV_RFP64:
14715   case X86::CMOV_RFP80:
14716     return EmitLoweredSelect(MI, BB);
14717
14718   case X86::FP32_TO_INT16_IN_MEM:
14719   case X86::FP32_TO_INT32_IN_MEM:
14720   case X86::FP32_TO_INT64_IN_MEM:
14721   case X86::FP64_TO_INT16_IN_MEM:
14722   case X86::FP64_TO_INT32_IN_MEM:
14723   case X86::FP64_TO_INT64_IN_MEM:
14724   case X86::FP80_TO_INT16_IN_MEM:
14725   case X86::FP80_TO_INT32_IN_MEM:
14726   case X86::FP80_TO_INT64_IN_MEM: {
14727     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14728     DebugLoc DL = MI->getDebugLoc();
14729
14730     // Change the floating point control register to use "round towards zero"
14731     // mode when truncating to an integer value.
14732     MachineFunction *F = BB->getParent();
14733     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14734     addFrameReference(BuildMI(*BB, MI, DL,
14735                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14736
14737     // Load the old value of the high byte of the control word...
14738     unsigned OldCW =
14739       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14740     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14741                       CWFrameIdx);
14742
14743     // Set the high part to be round to zero...
14744     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14745       .addImm(0xC7F);
14746
14747     // Reload the modified control word now...
14748     addFrameReference(BuildMI(*BB, MI, DL,
14749                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14750
14751     // Restore the memory image of control word to original value
14752     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14753       .addReg(OldCW);
14754
14755     // Get the X86 opcode to use.
14756     unsigned Opc;
14757     switch (MI->getOpcode()) {
14758     default: llvm_unreachable("illegal opcode!");
14759     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14760     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14761     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14762     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14763     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14764     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14765     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14766     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14767     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14768     }
14769
14770     X86AddressMode AM;
14771     MachineOperand &Op = MI->getOperand(0);
14772     if (Op.isReg()) {
14773       AM.BaseType = X86AddressMode::RegBase;
14774       AM.Base.Reg = Op.getReg();
14775     } else {
14776       AM.BaseType = X86AddressMode::FrameIndexBase;
14777       AM.Base.FrameIndex = Op.getIndex();
14778     }
14779     Op = MI->getOperand(1);
14780     if (Op.isImm())
14781       AM.Scale = Op.getImm();
14782     Op = MI->getOperand(2);
14783     if (Op.isImm())
14784       AM.IndexReg = Op.getImm();
14785     Op = MI->getOperand(3);
14786     if (Op.isGlobal()) {
14787       AM.GV = Op.getGlobal();
14788     } else {
14789       AM.Disp = Op.getImm();
14790     }
14791     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14792                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14793
14794     // Reload the original control word now.
14795     addFrameReference(BuildMI(*BB, MI, DL,
14796                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14797
14798     MI->eraseFromParent();   // The pseudo instruction is gone now.
14799     return BB;
14800   }
14801     // String/text processing lowering.
14802   case X86::PCMPISTRM128REG:
14803   case X86::VPCMPISTRM128REG:
14804   case X86::PCMPISTRM128MEM:
14805   case X86::VPCMPISTRM128MEM:
14806   case X86::PCMPESTRM128REG:
14807   case X86::VPCMPESTRM128REG:
14808   case X86::PCMPESTRM128MEM:
14809   case X86::VPCMPESTRM128MEM:
14810     assert(Subtarget->hasSSE42() &&
14811            "Target must have SSE4.2 or AVX features enabled");
14812     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14813
14814   // String/text processing lowering.
14815   case X86::PCMPISTRIREG:
14816   case X86::VPCMPISTRIREG:
14817   case X86::PCMPISTRIMEM:
14818   case X86::VPCMPISTRIMEM:
14819   case X86::PCMPESTRIREG:
14820   case X86::VPCMPESTRIREG:
14821   case X86::PCMPESTRIMEM:
14822   case X86::VPCMPESTRIMEM:
14823     assert(Subtarget->hasSSE42() &&
14824            "Target must have SSE4.2 or AVX features enabled");
14825     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14826
14827   // Thread synchronization.
14828   case X86::MONITOR:
14829     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14830
14831   // xbegin
14832   case X86::XBEGIN:
14833     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14834
14835   // Atomic Lowering.
14836   case X86::ATOMAND8:
14837   case X86::ATOMAND16:
14838   case X86::ATOMAND32:
14839   case X86::ATOMAND64:
14840     // Fall through
14841   case X86::ATOMOR8:
14842   case X86::ATOMOR16:
14843   case X86::ATOMOR32:
14844   case X86::ATOMOR64:
14845     // Fall through
14846   case X86::ATOMXOR16:
14847   case X86::ATOMXOR8:
14848   case X86::ATOMXOR32:
14849   case X86::ATOMXOR64:
14850     // Fall through
14851   case X86::ATOMNAND8:
14852   case X86::ATOMNAND16:
14853   case X86::ATOMNAND32:
14854   case X86::ATOMNAND64:
14855     // Fall through
14856   case X86::ATOMMAX8:
14857   case X86::ATOMMAX16:
14858   case X86::ATOMMAX32:
14859   case X86::ATOMMAX64:
14860     // Fall through
14861   case X86::ATOMMIN8:
14862   case X86::ATOMMIN16:
14863   case X86::ATOMMIN32:
14864   case X86::ATOMMIN64:
14865     // Fall through
14866   case X86::ATOMUMAX8:
14867   case X86::ATOMUMAX16:
14868   case X86::ATOMUMAX32:
14869   case X86::ATOMUMAX64:
14870     // Fall through
14871   case X86::ATOMUMIN8:
14872   case X86::ATOMUMIN16:
14873   case X86::ATOMUMIN32:
14874   case X86::ATOMUMIN64:
14875     return EmitAtomicLoadArith(MI, BB);
14876
14877   // This group does 64-bit operations on a 32-bit host.
14878   case X86::ATOMAND6432:
14879   case X86::ATOMOR6432:
14880   case X86::ATOMXOR6432:
14881   case X86::ATOMNAND6432:
14882   case X86::ATOMADD6432:
14883   case X86::ATOMSUB6432:
14884   case X86::ATOMMAX6432:
14885   case X86::ATOMMIN6432:
14886   case X86::ATOMUMAX6432:
14887   case X86::ATOMUMIN6432:
14888   case X86::ATOMSWAP6432:
14889     return EmitAtomicLoadArith6432(MI, BB);
14890
14891   case X86::VASTART_SAVE_XMM_REGS:
14892     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14893
14894   case X86::VAARG_64:
14895     return EmitVAARG64WithCustomInserter(MI, BB);
14896
14897   case X86::EH_SjLj_SetJmp32:
14898   case X86::EH_SjLj_SetJmp64:
14899     return emitEHSjLjSetJmp(MI, BB);
14900
14901   case X86::EH_SjLj_LongJmp32:
14902   case X86::EH_SjLj_LongJmp64:
14903     return emitEHSjLjLongJmp(MI, BB);
14904   }
14905 }
14906
14907 //===----------------------------------------------------------------------===//
14908 //                           X86 Optimization Hooks
14909 //===----------------------------------------------------------------------===//
14910
14911 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14912                                                        APInt &KnownZero,
14913                                                        APInt &KnownOne,
14914                                                        const SelectionDAG &DAG,
14915                                                        unsigned Depth) const {
14916   unsigned BitWidth = KnownZero.getBitWidth();
14917   unsigned Opc = Op.getOpcode();
14918   assert((Opc >= ISD::BUILTIN_OP_END ||
14919           Opc == ISD::INTRINSIC_WO_CHAIN ||
14920           Opc == ISD::INTRINSIC_W_CHAIN ||
14921           Opc == ISD::INTRINSIC_VOID) &&
14922          "Should use MaskedValueIsZero if you don't know whether Op"
14923          " is a target node!");
14924
14925   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14926   switch (Opc) {
14927   default: break;
14928   case X86ISD::ADD:
14929   case X86ISD::SUB:
14930   case X86ISD::ADC:
14931   case X86ISD::SBB:
14932   case X86ISD::SMUL:
14933   case X86ISD::UMUL:
14934   case X86ISD::INC:
14935   case X86ISD::DEC:
14936   case X86ISD::OR:
14937   case X86ISD::XOR:
14938   case X86ISD::AND:
14939     // These nodes' second result is a boolean.
14940     if (Op.getResNo() == 0)
14941       break;
14942     // Fallthrough
14943   case X86ISD::SETCC:
14944     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14945     break;
14946   case ISD::INTRINSIC_WO_CHAIN: {
14947     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14948     unsigned NumLoBits = 0;
14949     switch (IntId) {
14950     default: break;
14951     case Intrinsic::x86_sse_movmsk_ps:
14952     case Intrinsic::x86_avx_movmsk_ps_256:
14953     case Intrinsic::x86_sse2_movmsk_pd:
14954     case Intrinsic::x86_avx_movmsk_pd_256:
14955     case Intrinsic::x86_mmx_pmovmskb:
14956     case Intrinsic::x86_sse2_pmovmskb_128:
14957     case Intrinsic::x86_avx2_pmovmskb: {
14958       // High bits of movmskp{s|d}, pmovmskb are known zero.
14959       switch (IntId) {
14960         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14961         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14962         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14963         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14964         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14965         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14966         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14967         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14968       }
14969       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14970       break;
14971     }
14972     }
14973     break;
14974   }
14975   }
14976 }
14977
14978 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14979                                                          unsigned Depth) const {
14980   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14981   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14982     return Op.getValueType().getScalarType().getSizeInBits();
14983
14984   // Fallback case.
14985   return 1;
14986 }
14987
14988 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14989 /// node is a GlobalAddress + offset.
14990 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14991                                        const GlobalValue* &GA,
14992                                        int64_t &Offset) const {
14993   if (N->getOpcode() == X86ISD::Wrapper) {
14994     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14995       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14996       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14997       return true;
14998     }
14999   }
15000   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15001 }
15002
15003 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15004 /// same as extracting the high 128-bit part of 256-bit vector and then
15005 /// inserting the result into the low part of a new 256-bit vector
15006 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15007   EVT VT = SVOp->getValueType(0);
15008   unsigned NumElems = VT.getVectorNumElements();
15009
15010   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15011   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15012     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15013         SVOp->getMaskElt(j) >= 0)
15014       return false;
15015
15016   return true;
15017 }
15018
15019 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15020 /// same as extracting the low 128-bit part of 256-bit vector and then
15021 /// inserting the result into the high part of a new 256-bit vector
15022 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15023   EVT VT = SVOp->getValueType(0);
15024   unsigned NumElems = VT.getVectorNumElements();
15025
15026   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15027   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15028     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15029         SVOp->getMaskElt(j) >= 0)
15030       return false;
15031
15032   return true;
15033 }
15034
15035 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15036 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15037                                         TargetLowering::DAGCombinerInfo &DCI,
15038                                         const X86Subtarget* Subtarget) {
15039   DebugLoc dl = N->getDebugLoc();
15040   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15041   SDValue V1 = SVOp->getOperand(0);
15042   SDValue V2 = SVOp->getOperand(1);
15043   EVT VT = SVOp->getValueType(0);
15044   unsigned NumElems = VT.getVectorNumElements();
15045
15046   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15047       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15048     //
15049     //                   0,0,0,...
15050     //                      |
15051     //    V      UNDEF    BUILD_VECTOR    UNDEF
15052     //     \      /           \           /
15053     //  CONCAT_VECTOR         CONCAT_VECTOR
15054     //         \                  /
15055     //          \                /
15056     //          RESULT: V + zero extended
15057     //
15058     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15059         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15060         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15061       return SDValue();
15062
15063     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15064       return SDValue();
15065
15066     // To match the shuffle mask, the first half of the mask should
15067     // be exactly the first vector, and all the rest a splat with the
15068     // first element of the second one.
15069     for (unsigned i = 0; i != NumElems/2; ++i)
15070       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15071           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15072         return SDValue();
15073
15074     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15075     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15076       if (Ld->hasNUsesOfValue(1, 0)) {
15077         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15078         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15079         SDValue ResNode =
15080           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15081                                   array_lengthof(Ops),
15082                                   Ld->getMemoryVT(),
15083                                   Ld->getPointerInfo(),
15084                                   Ld->getAlignment(),
15085                                   false/*isVolatile*/, true/*ReadMem*/,
15086                                   false/*WriteMem*/);
15087
15088         // Make sure the newly-created LOAD is in the same position as Ld in
15089         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15090         // and update uses of Ld's output chain to use the TokenFactor.
15091         if (Ld->hasAnyUseOfValue(1)) {
15092           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15093                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15094           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15095           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15096                                  SDValue(ResNode.getNode(), 1));
15097         }
15098
15099         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15100       }
15101     }
15102
15103     // Emit a zeroed vector and insert the desired subvector on its
15104     // first half.
15105     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15106     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15107     return DCI.CombineTo(N, InsV);
15108   }
15109
15110   //===--------------------------------------------------------------------===//
15111   // Combine some shuffles into subvector extracts and inserts:
15112   //
15113
15114   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15115   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15116     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15117     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15118     return DCI.CombineTo(N, InsV);
15119   }
15120
15121   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15122   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15123     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15124     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15125     return DCI.CombineTo(N, InsV);
15126   }
15127
15128   return SDValue();
15129 }
15130
15131 /// PerformShuffleCombine - Performs several different shuffle combines.
15132 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15133                                      TargetLowering::DAGCombinerInfo &DCI,
15134                                      const X86Subtarget *Subtarget) {
15135   DebugLoc dl = N->getDebugLoc();
15136   EVT VT = N->getValueType(0);
15137
15138   // Don't create instructions with illegal types after legalize types has run.
15139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15140   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15141     return SDValue();
15142
15143   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15144   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15145       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15146     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15147
15148   // Only handle 128 wide vector from here on.
15149   if (!VT.is128BitVector())
15150     return SDValue();
15151
15152   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15153   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15154   // consecutive, non-overlapping, and in the right order.
15155   SmallVector<SDValue, 16> Elts;
15156   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15157     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15158
15159   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15160 }
15161
15162 /// PerformTruncateCombine - Converts truncate operation to
15163 /// a sequence of vector shuffle operations.
15164 /// It is possible when we truncate 256-bit vector to 128-bit vector
15165 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15166                                       TargetLowering::DAGCombinerInfo &DCI,
15167                                       const X86Subtarget *Subtarget)  {
15168   return SDValue();
15169 }
15170
15171 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15172 /// specific shuffle of a load can be folded into a single element load.
15173 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15174 /// shuffles have been customed lowered so we need to handle those here.
15175 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15176                                          TargetLowering::DAGCombinerInfo &DCI) {
15177   if (DCI.isBeforeLegalizeOps())
15178     return SDValue();
15179
15180   SDValue InVec = N->getOperand(0);
15181   SDValue EltNo = N->getOperand(1);
15182
15183   if (!isa<ConstantSDNode>(EltNo))
15184     return SDValue();
15185
15186   EVT VT = InVec.getValueType();
15187
15188   bool HasShuffleIntoBitcast = false;
15189   if (InVec.getOpcode() == ISD::BITCAST) {
15190     // Don't duplicate a load with other uses.
15191     if (!InVec.hasOneUse())
15192       return SDValue();
15193     EVT BCVT = InVec.getOperand(0).getValueType();
15194     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15195       return SDValue();
15196     InVec = InVec.getOperand(0);
15197     HasShuffleIntoBitcast = true;
15198   }
15199
15200   if (!isTargetShuffle(InVec.getOpcode()))
15201     return SDValue();
15202
15203   // Don't duplicate a load with other uses.
15204   if (!InVec.hasOneUse())
15205     return SDValue();
15206
15207   SmallVector<int, 16> ShuffleMask;
15208   bool UnaryShuffle;
15209   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15210                             UnaryShuffle))
15211     return SDValue();
15212
15213   // Select the input vector, guarding against out of range extract vector.
15214   unsigned NumElems = VT.getVectorNumElements();
15215   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15216   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15217   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15218                                          : InVec.getOperand(1);
15219
15220   // If inputs to shuffle are the same for both ops, then allow 2 uses
15221   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15222
15223   if (LdNode.getOpcode() == ISD::BITCAST) {
15224     // Don't duplicate a load with other uses.
15225     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15226       return SDValue();
15227
15228     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15229     LdNode = LdNode.getOperand(0);
15230   }
15231
15232   if (!ISD::isNormalLoad(LdNode.getNode()))
15233     return SDValue();
15234
15235   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15236
15237   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15238     return SDValue();
15239
15240   if (HasShuffleIntoBitcast) {
15241     // If there's a bitcast before the shuffle, check if the load type and
15242     // alignment is valid.
15243     unsigned Align = LN0->getAlignment();
15244     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15245     unsigned NewAlign = TLI.getDataLayout()->
15246       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15247
15248     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15249       return SDValue();
15250   }
15251
15252   // All checks match so transform back to vector_shuffle so that DAG combiner
15253   // can finish the job
15254   DebugLoc dl = N->getDebugLoc();
15255
15256   // Create shuffle node taking into account the case that its a unary shuffle
15257   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15258   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15259                                  InVec.getOperand(0), Shuffle,
15260                                  &ShuffleMask[0]);
15261   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15262   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15263                      EltNo);
15264 }
15265
15266 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15267 /// generation and convert it from being a bunch of shuffles and extracts
15268 /// to a simple store and scalar loads to extract the elements.
15269 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15270                                          TargetLowering::DAGCombinerInfo &DCI) {
15271   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15272   if (NewOp.getNode())
15273     return NewOp;
15274
15275   SDValue InputVector = N->getOperand(0);
15276   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15277   // from mmx to v2i32 has a single usage.
15278   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15279       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15280       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15281     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15282                        N->getValueType(0),
15283                        InputVector.getNode()->getOperand(0));
15284
15285   // Only operate on vectors of 4 elements, where the alternative shuffling
15286   // gets to be more expensive.
15287   if (InputVector.getValueType() != MVT::v4i32)
15288     return SDValue();
15289
15290   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15291   // single use which is a sign-extend or zero-extend, and all elements are
15292   // used.
15293   SmallVector<SDNode *, 4> Uses;
15294   unsigned ExtractedElements = 0;
15295   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15296        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15297     if (UI.getUse().getResNo() != InputVector.getResNo())
15298       return SDValue();
15299
15300     SDNode *Extract = *UI;
15301     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15302       return SDValue();
15303
15304     if (Extract->getValueType(0) != MVT::i32)
15305       return SDValue();
15306     if (!Extract->hasOneUse())
15307       return SDValue();
15308     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15309         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15310       return SDValue();
15311     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15312       return SDValue();
15313
15314     // Record which element was extracted.
15315     ExtractedElements |=
15316       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15317
15318     Uses.push_back(Extract);
15319   }
15320
15321   // If not all the elements were used, this may not be worthwhile.
15322   if (ExtractedElements != 15)
15323     return SDValue();
15324
15325   // Ok, we've now decided to do the transformation.
15326   DebugLoc dl = InputVector.getDebugLoc();
15327
15328   // Store the value to a temporary stack slot.
15329   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15330   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15331                             MachinePointerInfo(), false, false, 0);
15332
15333   // Replace each use (extract) with a load of the appropriate element.
15334   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15335        UE = Uses.end(); UI != UE; ++UI) {
15336     SDNode *Extract = *UI;
15337
15338     // cOMpute the element's address.
15339     SDValue Idx = Extract->getOperand(1);
15340     unsigned EltSize =
15341         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15342     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15343     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15344     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15345
15346     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15347                                      StackPtr, OffsetVal);
15348
15349     // Load the scalar.
15350     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15351                                      ScalarAddr, MachinePointerInfo(),
15352                                      false, false, false, 0);
15353
15354     // Replace the exact with the load.
15355     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15356   }
15357
15358   // The replacement was made in place; don't return anything.
15359   return SDValue();
15360 }
15361
15362 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15363 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15364                                    SDValue RHS, SelectionDAG &DAG,
15365                                    const X86Subtarget *Subtarget) {
15366   if (!VT.isVector())
15367     return 0;
15368
15369   switch (VT.getSimpleVT().SimpleTy) {
15370   default: return 0;
15371   case MVT::v32i8:
15372   case MVT::v16i16:
15373   case MVT::v8i32:
15374     if (!Subtarget->hasAVX2())
15375       return 0;
15376   case MVT::v16i8:
15377   case MVT::v8i16:
15378   case MVT::v4i32:
15379     if (!Subtarget->hasSSE2())
15380       return 0;
15381   }
15382
15383   // SSE2 has only a small subset of the operations.
15384   bool hasUnsigned = Subtarget->hasSSE41() ||
15385                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15386   bool hasSigned = Subtarget->hasSSE41() ||
15387                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15388
15389   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15390
15391   // Check for x CC y ? x : y.
15392   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15393       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15394     switch (CC) {
15395     default: break;
15396     case ISD::SETULT:
15397     case ISD::SETULE:
15398       return hasUnsigned ? X86ISD::UMIN : 0;
15399     case ISD::SETUGT:
15400     case ISD::SETUGE:
15401       return hasUnsigned ? X86ISD::UMAX : 0;
15402     case ISD::SETLT:
15403     case ISD::SETLE:
15404       return hasSigned ? X86ISD::SMIN : 0;
15405     case ISD::SETGT:
15406     case ISD::SETGE:
15407       return hasSigned ? X86ISD::SMAX : 0;
15408     }
15409   // Check for x CC y ? y : x -- a min/max with reversed arms.
15410   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15411              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15412     switch (CC) {
15413     default: break;
15414     case ISD::SETULT:
15415     case ISD::SETULE:
15416       return hasUnsigned ? X86ISD::UMAX : 0;
15417     case ISD::SETUGT:
15418     case ISD::SETUGE:
15419       return hasUnsigned ? X86ISD::UMIN : 0;
15420     case ISD::SETLT:
15421     case ISD::SETLE:
15422       return hasSigned ? X86ISD::SMAX : 0;
15423     case ISD::SETGT:
15424     case ISD::SETGE:
15425       return hasSigned ? X86ISD::SMIN : 0;
15426     }
15427   }
15428
15429   return 0;
15430 }
15431
15432 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15433 /// nodes.
15434 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15435                                     TargetLowering::DAGCombinerInfo &DCI,
15436                                     const X86Subtarget *Subtarget) {
15437   DebugLoc DL = N->getDebugLoc();
15438   SDValue Cond = N->getOperand(0);
15439   // Get the LHS/RHS of the select.
15440   SDValue LHS = N->getOperand(1);
15441   SDValue RHS = N->getOperand(2);
15442   EVT VT = LHS.getValueType();
15443
15444   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15445   // instructions match the semantics of the common C idiom x<y?x:y but not
15446   // x<=y?x:y, because of how they handle negative zero (which can be
15447   // ignored in unsafe-math mode).
15448   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15449       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15450       (Subtarget->hasSSE2() ||
15451        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15452     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15453
15454     unsigned Opcode = 0;
15455     // Check for x CC y ? x : y.
15456     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15457         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15458       switch (CC) {
15459       default: break;
15460       case ISD::SETULT:
15461         // Converting this to a min would handle NaNs incorrectly, and swapping
15462         // the operands would cause it to handle comparisons between positive
15463         // and negative zero incorrectly.
15464         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15465           if (!DAG.getTarget().Options.UnsafeFPMath &&
15466               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15467             break;
15468           std::swap(LHS, RHS);
15469         }
15470         Opcode = X86ISD::FMIN;
15471         break;
15472       case ISD::SETOLE:
15473         // Converting this to a min would handle comparisons between positive
15474         // and negative zero incorrectly.
15475         if (!DAG.getTarget().Options.UnsafeFPMath &&
15476             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15477           break;
15478         Opcode = X86ISD::FMIN;
15479         break;
15480       case ISD::SETULE:
15481         // Converting this to a min would handle both negative zeros and NaNs
15482         // incorrectly, but we can swap the operands to fix both.
15483         std::swap(LHS, RHS);
15484       case ISD::SETOLT:
15485       case ISD::SETLT:
15486       case ISD::SETLE:
15487         Opcode = X86ISD::FMIN;
15488         break;
15489
15490       case ISD::SETOGE:
15491         // Converting this to a max would handle comparisons between positive
15492         // and negative zero incorrectly.
15493         if (!DAG.getTarget().Options.UnsafeFPMath &&
15494             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15495           break;
15496         Opcode = X86ISD::FMAX;
15497         break;
15498       case ISD::SETUGT:
15499         // Converting this to a max would handle NaNs incorrectly, and swapping
15500         // the operands would cause it to handle comparisons between positive
15501         // and negative zero incorrectly.
15502         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15503           if (!DAG.getTarget().Options.UnsafeFPMath &&
15504               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15505             break;
15506           std::swap(LHS, RHS);
15507         }
15508         Opcode = X86ISD::FMAX;
15509         break;
15510       case ISD::SETUGE:
15511         // Converting this to a max would handle both negative zeros and NaNs
15512         // incorrectly, but we can swap the operands to fix both.
15513         std::swap(LHS, RHS);
15514       case ISD::SETOGT:
15515       case ISD::SETGT:
15516       case ISD::SETGE:
15517         Opcode = X86ISD::FMAX;
15518         break;
15519       }
15520     // Check for x CC y ? y : x -- a min/max with reversed arms.
15521     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15522                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15523       switch (CC) {
15524       default: break;
15525       case ISD::SETOGE:
15526         // Converting this to a min would handle comparisons between positive
15527         // and negative zero incorrectly, and swapping the operands would
15528         // cause it to handle NaNs incorrectly.
15529         if (!DAG.getTarget().Options.UnsafeFPMath &&
15530             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15531           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15532             break;
15533           std::swap(LHS, RHS);
15534         }
15535         Opcode = X86ISD::FMIN;
15536         break;
15537       case ISD::SETUGT:
15538         // Converting this to a min would handle NaNs incorrectly.
15539         if (!DAG.getTarget().Options.UnsafeFPMath &&
15540             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15541           break;
15542         Opcode = X86ISD::FMIN;
15543         break;
15544       case ISD::SETUGE:
15545         // Converting this to a min would handle both negative zeros and NaNs
15546         // incorrectly, but we can swap the operands to fix both.
15547         std::swap(LHS, RHS);
15548       case ISD::SETOGT:
15549       case ISD::SETGT:
15550       case ISD::SETGE:
15551         Opcode = X86ISD::FMIN;
15552         break;
15553
15554       case ISD::SETULT:
15555         // Converting this to a max would handle NaNs incorrectly.
15556         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15557           break;
15558         Opcode = X86ISD::FMAX;
15559         break;
15560       case ISD::SETOLE:
15561         // Converting this to a max would handle comparisons between positive
15562         // and negative zero incorrectly, and swapping the operands would
15563         // cause it to handle NaNs incorrectly.
15564         if (!DAG.getTarget().Options.UnsafeFPMath &&
15565             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15566           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15567             break;
15568           std::swap(LHS, RHS);
15569         }
15570         Opcode = X86ISD::FMAX;
15571         break;
15572       case ISD::SETULE:
15573         // Converting this to a max would handle both negative zeros and NaNs
15574         // incorrectly, but we can swap the operands to fix both.
15575         std::swap(LHS, RHS);
15576       case ISD::SETOLT:
15577       case ISD::SETLT:
15578       case ISD::SETLE:
15579         Opcode = X86ISD::FMAX;
15580         break;
15581       }
15582     }
15583
15584     if (Opcode)
15585       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15586   }
15587
15588   // If this is a select between two integer constants, try to do some
15589   // optimizations.
15590   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15591     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15592       // Don't do this for crazy integer types.
15593       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15594         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15595         // so that TrueC (the true value) is larger than FalseC.
15596         bool NeedsCondInvert = false;
15597
15598         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15599             // Efficiently invertible.
15600             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15601              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15602               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15603           NeedsCondInvert = true;
15604           std::swap(TrueC, FalseC);
15605         }
15606
15607         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15608         if (FalseC->getAPIntValue() == 0 &&
15609             TrueC->getAPIntValue().isPowerOf2()) {
15610           if (NeedsCondInvert) // Invert the condition if needed.
15611             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15612                                DAG.getConstant(1, Cond.getValueType()));
15613
15614           // Zero extend the condition if needed.
15615           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15616
15617           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15618           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15619                              DAG.getConstant(ShAmt, MVT::i8));
15620         }
15621
15622         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15623         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15624           if (NeedsCondInvert) // Invert the condition if needed.
15625             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15626                                DAG.getConstant(1, Cond.getValueType()));
15627
15628           // Zero extend the condition if needed.
15629           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15630                              FalseC->getValueType(0), Cond);
15631           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15632                              SDValue(FalseC, 0));
15633         }
15634
15635         // Optimize cases that will turn into an LEA instruction.  This requires
15636         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15637         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15638           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15639           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15640
15641           bool isFastMultiplier = false;
15642           if (Diff < 10) {
15643             switch ((unsigned char)Diff) {
15644               default: break;
15645               case 1:  // result = add base, cond
15646               case 2:  // result = lea base(    , cond*2)
15647               case 3:  // result = lea base(cond, cond*2)
15648               case 4:  // result = lea base(    , cond*4)
15649               case 5:  // result = lea base(cond, cond*4)
15650               case 8:  // result = lea base(    , cond*8)
15651               case 9:  // result = lea base(cond, cond*8)
15652                 isFastMultiplier = true;
15653                 break;
15654             }
15655           }
15656
15657           if (isFastMultiplier) {
15658             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15659             if (NeedsCondInvert) // Invert the condition if needed.
15660               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15661                                  DAG.getConstant(1, Cond.getValueType()));
15662
15663             // Zero extend the condition if needed.
15664             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15665                                Cond);
15666             // Scale the condition by the difference.
15667             if (Diff != 1)
15668               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15669                                  DAG.getConstant(Diff, Cond.getValueType()));
15670
15671             // Add the base if non-zero.
15672             if (FalseC->getAPIntValue() != 0)
15673               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15674                                  SDValue(FalseC, 0));
15675             return Cond;
15676           }
15677         }
15678       }
15679   }
15680
15681   // Canonicalize max and min:
15682   // (x > y) ? x : y -> (x >= y) ? x : y
15683   // (x < y) ? x : y -> (x <= y) ? x : y
15684   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15685   // the need for an extra compare
15686   // against zero. e.g.
15687   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15688   // subl   %esi, %edi
15689   // testl  %edi, %edi
15690   // movl   $0, %eax
15691   // cmovgl %edi, %eax
15692   // =>
15693   // xorl   %eax, %eax
15694   // subl   %esi, $edi
15695   // cmovsl %eax, %edi
15696   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15697       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15698       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15699     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15700     switch (CC) {
15701     default: break;
15702     case ISD::SETLT:
15703     case ISD::SETGT: {
15704       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15705       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15706                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15707       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15708     }
15709     }
15710   }
15711
15712   // Match VSELECTs into subs with unsigned saturation.
15713   if (!DCI.isBeforeLegalize() &&
15714       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15715       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15716       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15717        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15718     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15719
15720     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15721     // left side invert the predicate to simplify logic below.
15722     SDValue Other;
15723     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15724       Other = RHS;
15725       CC = ISD::getSetCCInverse(CC, true);
15726     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15727       Other = LHS;
15728     }
15729
15730     if (Other.getNode() && Other->getNumOperands() == 2 &&
15731         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15732       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15733       SDValue CondRHS = Cond->getOperand(1);
15734
15735       // Look for a general sub with unsigned saturation first.
15736       // x >= y ? x-y : 0 --> subus x, y
15737       // x >  y ? x-y : 0 --> subus x, y
15738       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15739           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15740         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15741
15742       // If the RHS is a constant we have to reverse the const canonicalization.
15743       // x > C-1 ? x+-C : 0 --> subus x, C
15744       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15745           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15746         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15747         if (CondRHS.getConstantOperandVal(0) == -A-1)
15748           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15749                              DAG.getConstant(-A, VT));
15750       }
15751
15752       // Another special case: If C was a sign bit, the sub has been
15753       // canonicalized into a xor.
15754       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15755       //        it's safe to decanonicalize the xor?
15756       // x s< 0 ? x^C : 0 --> subus x, C
15757       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15758           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15759           isSplatVector(OpRHS.getNode())) {
15760         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15761         if (A.isSignBit())
15762           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15763       }
15764     }
15765   }
15766
15767   // Try to match a min/max vector operation.
15768   if (!DCI.isBeforeLegalize() &&
15769       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15770     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15771       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15772
15773   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15774   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15775       Cond.getOpcode() == ISD::SETCC) {
15776
15777     assert(Cond.getValueType().isVector() &&
15778            "vector select expects a vector selector!");
15779
15780     EVT IntVT = Cond.getValueType();
15781     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15782     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15783
15784     if (!TValIsAllOnes && !FValIsAllZeros) {
15785       // Try invert the condition if true value is not all 1s and false value
15786       // is not all 0s.
15787       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15788       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15789
15790       if (TValIsAllZeros || FValIsAllOnes) {
15791         SDValue CC = Cond.getOperand(2);
15792         ISD::CondCode NewCC =
15793           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15794                                Cond.getOperand(0).getValueType().isInteger());
15795         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15796         std::swap(LHS, RHS);
15797         TValIsAllOnes = FValIsAllOnes;
15798         FValIsAllZeros = TValIsAllZeros;
15799       }
15800     }
15801
15802     if (TValIsAllOnes || FValIsAllZeros) {
15803       SDValue Ret;
15804
15805       if (TValIsAllOnes && FValIsAllZeros)
15806         Ret = Cond;
15807       else if (TValIsAllOnes)
15808         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15809                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15810       else if (FValIsAllZeros)
15811         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15812                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15813
15814       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15815     }
15816   }
15817
15818   // If we know that this node is legal then we know that it is going to be
15819   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15820   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15821   // to simplify previous instructions.
15822   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15823   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15824       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15825     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15826
15827     // Don't optimize vector selects that map to mask-registers.
15828     if (BitWidth == 1)
15829       return SDValue();
15830
15831     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15832     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15833
15834     APInt KnownZero, KnownOne;
15835     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15836                                           DCI.isBeforeLegalizeOps());
15837     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15838         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15839       DCI.CommitTargetLoweringOpt(TLO);
15840   }
15841
15842   return SDValue();
15843 }
15844
15845 // Check whether a boolean test is testing a boolean value generated by
15846 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15847 // code.
15848 //
15849 // Simplify the following patterns:
15850 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15851 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15852 // to (Op EFLAGS Cond)
15853 //
15854 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15855 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15856 // to (Op EFLAGS !Cond)
15857 //
15858 // where Op could be BRCOND or CMOV.
15859 //
15860 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15861   // Quit if not CMP and SUB with its value result used.
15862   if (Cmp.getOpcode() != X86ISD::CMP &&
15863       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15864       return SDValue();
15865
15866   // Quit if not used as a boolean value.
15867   if (CC != X86::COND_E && CC != X86::COND_NE)
15868     return SDValue();
15869
15870   // Check CMP operands. One of them should be 0 or 1 and the other should be
15871   // an SetCC or extended from it.
15872   SDValue Op1 = Cmp.getOperand(0);
15873   SDValue Op2 = Cmp.getOperand(1);
15874
15875   SDValue SetCC;
15876   const ConstantSDNode* C = 0;
15877   bool needOppositeCond = (CC == X86::COND_E);
15878   bool checkAgainstTrue = false; // Is it a comparison against 1?
15879
15880   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15881     SetCC = Op2;
15882   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15883     SetCC = Op1;
15884   else // Quit if all operands are not constants.
15885     return SDValue();
15886
15887   if (C->getZExtValue() == 1) {
15888     needOppositeCond = !needOppositeCond;
15889     checkAgainstTrue = true;
15890   } else if (C->getZExtValue() != 0)
15891     // Quit if the constant is neither 0 or 1.
15892     return SDValue();
15893
15894   bool truncatedToBoolWithAnd = false;
15895   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15896   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15897          SetCC.getOpcode() == ISD::TRUNCATE ||
15898          SetCC.getOpcode() == ISD::AND) {
15899     if (SetCC.getOpcode() == ISD::AND) {
15900       int OpIdx = -1;
15901       ConstantSDNode *CS;
15902       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15903           CS->getZExtValue() == 1)
15904         OpIdx = 1;
15905       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15906           CS->getZExtValue() == 1)
15907         OpIdx = 0;
15908       if (OpIdx == -1)
15909         break;
15910       SetCC = SetCC.getOperand(OpIdx);
15911       truncatedToBoolWithAnd = true;
15912     } else
15913       SetCC = SetCC.getOperand(0);
15914   }
15915
15916   switch (SetCC.getOpcode()) {
15917   case X86ISD::SETCC_CARRY:
15918     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15919     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15920     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15921     // truncated to i1 using 'and'.
15922     if (checkAgainstTrue && !truncatedToBoolWithAnd)
15923       break;
15924     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15925            "Invalid use of SETCC_CARRY!");
15926     // FALL THROUGH
15927   case X86ISD::SETCC:
15928     // Set the condition code or opposite one if necessary.
15929     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15930     if (needOppositeCond)
15931       CC = X86::GetOppositeBranchCondition(CC);
15932     return SetCC.getOperand(1);
15933   case X86ISD::CMOV: {
15934     // Check whether false/true value has canonical one, i.e. 0 or 1.
15935     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15936     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15937     // Quit if true value is not a constant.
15938     if (!TVal)
15939       return SDValue();
15940     // Quit if false value is not a constant.
15941     if (!FVal) {
15942       SDValue Op = SetCC.getOperand(0);
15943       // Skip 'zext' or 'trunc' node.
15944       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15945           Op.getOpcode() == ISD::TRUNCATE)
15946         Op = Op.getOperand(0);
15947       // A special case for rdrand/rdseed, where 0 is set if false cond is
15948       // found.
15949       if ((Op.getOpcode() != X86ISD::RDRAND &&
15950            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15951         return SDValue();
15952     }
15953     // Quit if false value is not the constant 0 or 1.
15954     bool FValIsFalse = true;
15955     if (FVal && FVal->getZExtValue() != 0) {
15956       if (FVal->getZExtValue() != 1)
15957         return SDValue();
15958       // If FVal is 1, opposite cond is needed.
15959       needOppositeCond = !needOppositeCond;
15960       FValIsFalse = false;
15961     }
15962     // Quit if TVal is not the constant opposite of FVal.
15963     if (FValIsFalse && TVal->getZExtValue() != 1)
15964       return SDValue();
15965     if (!FValIsFalse && TVal->getZExtValue() != 0)
15966       return SDValue();
15967     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15968     if (needOppositeCond)
15969       CC = X86::GetOppositeBranchCondition(CC);
15970     return SetCC.getOperand(3);
15971   }
15972   }
15973
15974   return SDValue();
15975 }
15976
15977 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15978 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15979                                   TargetLowering::DAGCombinerInfo &DCI,
15980                                   const X86Subtarget *Subtarget) {
15981   DebugLoc DL = N->getDebugLoc();
15982
15983   // If the flag operand isn't dead, don't touch this CMOV.
15984   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15985     return SDValue();
15986
15987   SDValue FalseOp = N->getOperand(0);
15988   SDValue TrueOp = N->getOperand(1);
15989   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15990   SDValue Cond = N->getOperand(3);
15991
15992   if (CC == X86::COND_E || CC == X86::COND_NE) {
15993     switch (Cond.getOpcode()) {
15994     default: break;
15995     case X86ISD::BSR:
15996     case X86ISD::BSF:
15997       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15998       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15999         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16000     }
16001   }
16002
16003   SDValue Flags;
16004
16005   Flags = checkBoolTestSetCCCombine(Cond, CC);
16006   if (Flags.getNode() &&
16007       // Extra check as FCMOV only supports a subset of X86 cond.
16008       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16009     SDValue Ops[] = { FalseOp, TrueOp,
16010                       DAG.getConstant(CC, MVT::i8), Flags };
16011     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16012                        Ops, array_lengthof(Ops));
16013   }
16014
16015   // If this is a select between two integer constants, try to do some
16016   // optimizations.  Note that the operands are ordered the opposite of SELECT
16017   // operands.
16018   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16019     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16020       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16021       // larger than FalseC (the false value).
16022       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16023         CC = X86::GetOppositeBranchCondition(CC);
16024         std::swap(TrueC, FalseC);
16025         std::swap(TrueOp, FalseOp);
16026       }
16027
16028       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16029       // This is efficient for any integer data type (including i8/i16) and
16030       // shift amount.
16031       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16032         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16033                            DAG.getConstant(CC, MVT::i8), Cond);
16034
16035         // Zero extend the condition if needed.
16036         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16037
16038         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16039         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16040                            DAG.getConstant(ShAmt, MVT::i8));
16041         if (N->getNumValues() == 2)  // Dead flag value?
16042           return DCI.CombineTo(N, Cond, SDValue());
16043         return Cond;
16044       }
16045
16046       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16047       // for any integer data type, including i8/i16.
16048       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16049         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16050                            DAG.getConstant(CC, MVT::i8), Cond);
16051
16052         // Zero extend the condition if needed.
16053         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16054                            FalseC->getValueType(0), Cond);
16055         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16056                            SDValue(FalseC, 0));
16057
16058         if (N->getNumValues() == 2)  // Dead flag value?
16059           return DCI.CombineTo(N, Cond, SDValue());
16060         return Cond;
16061       }
16062
16063       // Optimize cases that will turn into an LEA instruction.  This requires
16064       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16065       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16066         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16067         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16068
16069         bool isFastMultiplier = false;
16070         if (Diff < 10) {
16071           switch ((unsigned char)Diff) {
16072           default: break;
16073           case 1:  // result = add base, cond
16074           case 2:  // result = lea base(    , cond*2)
16075           case 3:  // result = lea base(cond, cond*2)
16076           case 4:  // result = lea base(    , cond*4)
16077           case 5:  // result = lea base(cond, cond*4)
16078           case 8:  // result = lea base(    , cond*8)
16079           case 9:  // result = lea base(cond, cond*8)
16080             isFastMultiplier = true;
16081             break;
16082           }
16083         }
16084
16085         if (isFastMultiplier) {
16086           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16087           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16088                              DAG.getConstant(CC, MVT::i8), Cond);
16089           // Zero extend the condition if needed.
16090           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16091                              Cond);
16092           // Scale the condition by the difference.
16093           if (Diff != 1)
16094             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16095                                DAG.getConstant(Diff, Cond.getValueType()));
16096
16097           // Add the base if non-zero.
16098           if (FalseC->getAPIntValue() != 0)
16099             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16100                                SDValue(FalseC, 0));
16101           if (N->getNumValues() == 2)  // Dead flag value?
16102             return DCI.CombineTo(N, Cond, SDValue());
16103           return Cond;
16104         }
16105       }
16106     }
16107   }
16108
16109   // Handle these cases:
16110   //   (select (x != c), e, c) -> select (x != c), e, x),
16111   //   (select (x == c), c, e) -> select (x == c), x, e)
16112   // where the c is an integer constant, and the "select" is the combination
16113   // of CMOV and CMP.
16114   //
16115   // The rationale for this change is that the conditional-move from a constant
16116   // needs two instructions, however, conditional-move from a register needs
16117   // only one instruction.
16118   //
16119   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16120   //  some instruction-combining opportunities. This opt needs to be
16121   //  postponed as late as possible.
16122   //
16123   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16124     // the DCI.xxxx conditions are provided to postpone the optimization as
16125     // late as possible.
16126
16127     ConstantSDNode *CmpAgainst = 0;
16128     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16129         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16130         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16131
16132       if (CC == X86::COND_NE &&
16133           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16134         CC = X86::GetOppositeBranchCondition(CC);
16135         std::swap(TrueOp, FalseOp);
16136       }
16137
16138       if (CC == X86::COND_E &&
16139           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16140         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16141                           DAG.getConstant(CC, MVT::i8), Cond };
16142         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16143                            array_lengthof(Ops));
16144       }
16145     }
16146   }
16147
16148   return SDValue();
16149 }
16150
16151 /// PerformMulCombine - Optimize a single multiply with constant into two
16152 /// in order to implement it with two cheaper instructions, e.g.
16153 /// LEA + SHL, LEA + LEA.
16154 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16155                                  TargetLowering::DAGCombinerInfo &DCI) {
16156   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16157     return SDValue();
16158
16159   EVT VT = N->getValueType(0);
16160   if (VT != MVT::i64)
16161     return SDValue();
16162
16163   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16164   if (!C)
16165     return SDValue();
16166   uint64_t MulAmt = C->getZExtValue();
16167   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16168     return SDValue();
16169
16170   uint64_t MulAmt1 = 0;
16171   uint64_t MulAmt2 = 0;
16172   if ((MulAmt % 9) == 0) {
16173     MulAmt1 = 9;
16174     MulAmt2 = MulAmt / 9;
16175   } else if ((MulAmt % 5) == 0) {
16176     MulAmt1 = 5;
16177     MulAmt2 = MulAmt / 5;
16178   } else if ((MulAmt % 3) == 0) {
16179     MulAmt1 = 3;
16180     MulAmt2 = MulAmt / 3;
16181   }
16182   if (MulAmt2 &&
16183       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16184     DebugLoc DL = N->getDebugLoc();
16185
16186     if (isPowerOf2_64(MulAmt2) &&
16187         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16188       // If second multiplifer is pow2, issue it first. We want the multiply by
16189       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16190       // is an add.
16191       std::swap(MulAmt1, MulAmt2);
16192
16193     SDValue NewMul;
16194     if (isPowerOf2_64(MulAmt1))
16195       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16196                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16197     else
16198       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16199                            DAG.getConstant(MulAmt1, VT));
16200
16201     if (isPowerOf2_64(MulAmt2))
16202       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16203                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16204     else
16205       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16206                            DAG.getConstant(MulAmt2, VT));
16207
16208     // Do not add new nodes to DAG combiner worklist.
16209     DCI.CombineTo(N, NewMul, false);
16210   }
16211   return SDValue();
16212 }
16213
16214 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16215   SDValue N0 = N->getOperand(0);
16216   SDValue N1 = N->getOperand(1);
16217   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16218   EVT VT = N0.getValueType();
16219
16220   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16221   // since the result of setcc_c is all zero's or all ones.
16222   if (VT.isInteger() && !VT.isVector() &&
16223       N1C && N0.getOpcode() == ISD::AND &&
16224       N0.getOperand(1).getOpcode() == ISD::Constant) {
16225     SDValue N00 = N0.getOperand(0);
16226     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16227         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16228           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16229          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16230       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16231       APInt ShAmt = N1C->getAPIntValue();
16232       Mask = Mask.shl(ShAmt);
16233       if (Mask != 0)
16234         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16235                            N00, DAG.getConstant(Mask, VT));
16236     }
16237   }
16238
16239   // Hardware support for vector shifts is sparse which makes us scalarize the
16240   // vector operations in many cases. Also, on sandybridge ADD is faster than
16241   // shl.
16242   // (shl V, 1) -> add V,V
16243   if (isSplatVector(N1.getNode())) {
16244     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16245     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16246     // We shift all of the values by one. In many cases we do not have
16247     // hardware support for this operation. This is better expressed as an ADD
16248     // of two values.
16249     if (N1C && (1 == N1C->getZExtValue())) {
16250       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16251     }
16252   }
16253
16254   return SDValue();
16255 }
16256
16257 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
16258 ///                       when possible.
16259 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16260                                    TargetLowering::DAGCombinerInfo &DCI,
16261                                    const X86Subtarget *Subtarget) {
16262   if (N->getOpcode() == ISD::SHL) {
16263     SDValue V = PerformSHLCombine(N, DAG);
16264     if (V.getNode()) return V;
16265   }
16266
16267   return SDValue();
16268 }
16269
16270 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16271 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16272 // and friends.  Likewise for OR -> CMPNEQSS.
16273 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16274                             TargetLowering::DAGCombinerInfo &DCI,
16275                             const X86Subtarget *Subtarget) {
16276   unsigned opcode;
16277
16278   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16279   // we're requiring SSE2 for both.
16280   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16281     SDValue N0 = N->getOperand(0);
16282     SDValue N1 = N->getOperand(1);
16283     SDValue CMP0 = N0->getOperand(1);
16284     SDValue CMP1 = N1->getOperand(1);
16285     DebugLoc DL = N->getDebugLoc();
16286
16287     // The SETCCs should both refer to the same CMP.
16288     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16289       return SDValue();
16290
16291     SDValue CMP00 = CMP0->getOperand(0);
16292     SDValue CMP01 = CMP0->getOperand(1);
16293     EVT     VT    = CMP00.getValueType();
16294
16295     if (VT == MVT::f32 || VT == MVT::f64) {
16296       bool ExpectingFlags = false;
16297       // Check for any users that want flags:
16298       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16299            !ExpectingFlags && UI != UE; ++UI)
16300         switch (UI->getOpcode()) {
16301         default:
16302         case ISD::BR_CC:
16303         case ISD::BRCOND:
16304         case ISD::SELECT:
16305           ExpectingFlags = true;
16306           break;
16307         case ISD::CopyToReg:
16308         case ISD::SIGN_EXTEND:
16309         case ISD::ZERO_EXTEND:
16310         case ISD::ANY_EXTEND:
16311           break;
16312         }
16313
16314       if (!ExpectingFlags) {
16315         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16316         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16317
16318         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16319           X86::CondCode tmp = cc0;
16320           cc0 = cc1;
16321           cc1 = tmp;
16322         }
16323
16324         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16325             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16326           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16327           X86ISD::NodeType NTOperator = is64BitFP ?
16328             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16329           // FIXME: need symbolic constants for these magic numbers.
16330           // See X86ATTInstPrinter.cpp:printSSECC().
16331           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16332           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16333                                               DAG.getConstant(x86cc, MVT::i8));
16334           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16335                                               OnesOrZeroesF);
16336           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16337                                       DAG.getConstant(1, MVT::i32));
16338           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16339           return OneBitOfTruth;
16340         }
16341       }
16342     }
16343   }
16344   return SDValue();
16345 }
16346
16347 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16348 /// so it can be folded inside ANDNP.
16349 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16350   EVT VT = N->getValueType(0);
16351
16352   // Match direct AllOnes for 128 and 256-bit vectors
16353   if (ISD::isBuildVectorAllOnes(N))
16354     return true;
16355
16356   // Look through a bit convert.
16357   if (N->getOpcode() == ISD::BITCAST)
16358     N = N->getOperand(0).getNode();
16359
16360   // Sometimes the operand may come from a insert_subvector building a 256-bit
16361   // allones vector
16362   if (VT.is256BitVector() &&
16363       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16364     SDValue V1 = N->getOperand(0);
16365     SDValue V2 = N->getOperand(1);
16366
16367     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16368         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16369         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16370         ISD::isBuildVectorAllOnes(V2.getNode()))
16371       return true;
16372   }
16373
16374   return false;
16375 }
16376
16377 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16378 // register. In most cases we actually compare or select YMM-sized registers
16379 // and mixing the two types creates horrible code. This method optimizes
16380 // some of the transition sequences.
16381 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16382                                  TargetLowering::DAGCombinerInfo &DCI,
16383                                  const X86Subtarget *Subtarget) {
16384   EVT VT = N->getValueType(0);
16385   if (!VT.is256BitVector())
16386     return SDValue();
16387
16388   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16389           N->getOpcode() == ISD::ZERO_EXTEND ||
16390           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16391
16392   SDValue Narrow = N->getOperand(0);
16393   EVT NarrowVT = Narrow->getValueType(0);
16394   if (!NarrowVT.is128BitVector())
16395     return SDValue();
16396
16397   if (Narrow->getOpcode() != ISD::XOR &&
16398       Narrow->getOpcode() != ISD::AND &&
16399       Narrow->getOpcode() != ISD::OR)
16400     return SDValue();
16401
16402   SDValue N0  = Narrow->getOperand(0);
16403   SDValue N1  = Narrow->getOperand(1);
16404   DebugLoc DL = Narrow->getDebugLoc();
16405
16406   // The Left side has to be a trunc.
16407   if (N0.getOpcode() != ISD::TRUNCATE)
16408     return SDValue();
16409
16410   // The type of the truncated inputs.
16411   EVT WideVT = N0->getOperand(0)->getValueType(0);
16412   if (WideVT != VT)
16413     return SDValue();
16414
16415   // The right side has to be a 'trunc' or a constant vector.
16416   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16417   bool RHSConst = (isSplatVector(N1.getNode()) &&
16418                    isa<ConstantSDNode>(N1->getOperand(0)));
16419   if (!RHSTrunc && !RHSConst)
16420     return SDValue();
16421
16422   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16423
16424   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16425     return SDValue();
16426
16427   // Set N0 and N1 to hold the inputs to the new wide operation.
16428   N0 = N0->getOperand(0);
16429   if (RHSConst) {
16430     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16431                      N1->getOperand(0));
16432     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16433     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16434   } else if (RHSTrunc) {
16435     N1 = N1->getOperand(0);
16436   }
16437
16438   // Generate the wide operation.
16439   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16440   unsigned Opcode = N->getOpcode();
16441   switch (Opcode) {
16442   case ISD::ANY_EXTEND:
16443     return Op;
16444   case ISD::ZERO_EXTEND: {
16445     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16446     APInt Mask = APInt::getAllOnesValue(InBits);
16447     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16448     return DAG.getNode(ISD::AND, DL, VT,
16449                        Op, DAG.getConstant(Mask, VT));
16450   }
16451   case ISD::SIGN_EXTEND:
16452     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16453                        Op, DAG.getValueType(NarrowVT));
16454   default:
16455     llvm_unreachable("Unexpected opcode");
16456   }
16457 }
16458
16459 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16460                                  TargetLowering::DAGCombinerInfo &DCI,
16461                                  const X86Subtarget *Subtarget) {
16462   EVT VT = N->getValueType(0);
16463   if (DCI.isBeforeLegalizeOps())
16464     return SDValue();
16465
16466   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16467   if (R.getNode())
16468     return R;
16469
16470   // Create BLSI, and BLSR instructions
16471   // BLSI is X & (-X)
16472   // BLSR is X & (X-1)
16473   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16474     SDValue N0 = N->getOperand(0);
16475     SDValue N1 = N->getOperand(1);
16476     DebugLoc DL = N->getDebugLoc();
16477
16478     // Check LHS for neg
16479     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16480         isZero(N0.getOperand(0)))
16481       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16482
16483     // Check RHS for neg
16484     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16485         isZero(N1.getOperand(0)))
16486       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16487
16488     // Check LHS for X-1
16489     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16490         isAllOnes(N0.getOperand(1)))
16491       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16492
16493     // Check RHS for X-1
16494     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16495         isAllOnes(N1.getOperand(1)))
16496       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16497
16498     return SDValue();
16499   }
16500
16501   // Want to form ANDNP nodes:
16502   // 1) In the hopes of then easily combining them with OR and AND nodes
16503   //    to form PBLEND/PSIGN.
16504   // 2) To match ANDN packed intrinsics
16505   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16506     return SDValue();
16507
16508   SDValue N0 = N->getOperand(0);
16509   SDValue N1 = N->getOperand(1);
16510   DebugLoc DL = N->getDebugLoc();
16511
16512   // Check LHS for vnot
16513   if (N0.getOpcode() == ISD::XOR &&
16514       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16515       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16516     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16517
16518   // Check RHS for vnot
16519   if (N1.getOpcode() == ISD::XOR &&
16520       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16521       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16522     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16523
16524   return SDValue();
16525 }
16526
16527 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16528                                 TargetLowering::DAGCombinerInfo &DCI,
16529                                 const X86Subtarget *Subtarget) {
16530   EVT VT = N->getValueType(0);
16531   if (DCI.isBeforeLegalizeOps())
16532     return SDValue();
16533
16534   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16535   if (R.getNode())
16536     return R;
16537
16538   SDValue N0 = N->getOperand(0);
16539   SDValue N1 = N->getOperand(1);
16540
16541   // look for psign/blend
16542   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16543     if (!Subtarget->hasSSSE3() ||
16544         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16545       return SDValue();
16546
16547     // Canonicalize pandn to RHS
16548     if (N0.getOpcode() == X86ISD::ANDNP)
16549       std::swap(N0, N1);
16550     // or (and (m, y), (pandn m, x))
16551     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16552       SDValue Mask = N1.getOperand(0);
16553       SDValue X    = N1.getOperand(1);
16554       SDValue Y;
16555       if (N0.getOperand(0) == Mask)
16556         Y = N0.getOperand(1);
16557       if (N0.getOperand(1) == Mask)
16558         Y = N0.getOperand(0);
16559
16560       // Check to see if the mask appeared in both the AND and ANDNP and
16561       if (!Y.getNode())
16562         return SDValue();
16563
16564       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16565       // Look through mask bitcast.
16566       if (Mask.getOpcode() == ISD::BITCAST)
16567         Mask = Mask.getOperand(0);
16568       if (X.getOpcode() == ISD::BITCAST)
16569         X = X.getOperand(0);
16570       if (Y.getOpcode() == ISD::BITCAST)
16571         Y = Y.getOperand(0);
16572
16573       EVT MaskVT = Mask.getValueType();
16574
16575       // Validate that the Mask operand is a vector sra node.
16576       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16577       // there is no psrai.b
16578       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16579       unsigned SraAmt = ~0;
16580       if (Mask.getOpcode() == ISD::SRA) {
16581         SDValue Amt = Mask.getOperand(1);
16582         if (isSplatVector(Amt.getNode())) {
16583           SDValue SclrAmt = Amt->getOperand(0);
16584           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16585             SraAmt = C->getZExtValue();
16586         }
16587       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16588         SDValue SraC = Mask.getOperand(1);
16589         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16590       }
16591       if ((SraAmt + 1) != EltBits)
16592         return SDValue();
16593
16594       DebugLoc DL = N->getDebugLoc();
16595
16596       // Now we know we at least have a plendvb with the mask val.  See if
16597       // we can form a psignb/w/d.
16598       // psign = x.type == y.type == mask.type && y = sub(0, x);
16599       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16600           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16601           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16602         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16603                "Unsupported VT for PSIGN");
16604         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16605         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16606       }
16607       // PBLENDVB only available on SSE 4.1
16608       if (!Subtarget->hasSSE41())
16609         return SDValue();
16610
16611       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16612
16613       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16614       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16615       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16616       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16617       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16618     }
16619   }
16620
16621   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16622     return SDValue();
16623
16624   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16625   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16626     std::swap(N0, N1);
16627   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16628     return SDValue();
16629   if (!N0.hasOneUse() || !N1.hasOneUse())
16630     return SDValue();
16631
16632   SDValue ShAmt0 = N0.getOperand(1);
16633   if (ShAmt0.getValueType() != MVT::i8)
16634     return SDValue();
16635   SDValue ShAmt1 = N1.getOperand(1);
16636   if (ShAmt1.getValueType() != MVT::i8)
16637     return SDValue();
16638   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16639     ShAmt0 = ShAmt0.getOperand(0);
16640   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16641     ShAmt1 = ShAmt1.getOperand(0);
16642
16643   DebugLoc DL = N->getDebugLoc();
16644   unsigned Opc = X86ISD::SHLD;
16645   SDValue Op0 = N0.getOperand(0);
16646   SDValue Op1 = N1.getOperand(0);
16647   if (ShAmt0.getOpcode() == ISD::SUB) {
16648     Opc = X86ISD::SHRD;
16649     std::swap(Op0, Op1);
16650     std::swap(ShAmt0, ShAmt1);
16651   }
16652
16653   unsigned Bits = VT.getSizeInBits();
16654   if (ShAmt1.getOpcode() == ISD::SUB) {
16655     SDValue Sum = ShAmt1.getOperand(0);
16656     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16657       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16658       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16659         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16660       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16661         return DAG.getNode(Opc, DL, VT,
16662                            Op0, Op1,
16663                            DAG.getNode(ISD::TRUNCATE, DL,
16664                                        MVT::i8, ShAmt0));
16665     }
16666   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16667     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16668     if (ShAmt0C &&
16669         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16670       return DAG.getNode(Opc, DL, VT,
16671                          N0.getOperand(0), N1.getOperand(0),
16672                          DAG.getNode(ISD::TRUNCATE, DL,
16673                                        MVT::i8, ShAmt0));
16674   }
16675
16676   return SDValue();
16677 }
16678
16679 // Generate NEG and CMOV for integer abs.
16680 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16681   EVT VT = N->getValueType(0);
16682
16683   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16684   // 8-bit integer abs to NEG and CMOV.
16685   if (VT.isInteger() && VT.getSizeInBits() == 8)
16686     return SDValue();
16687
16688   SDValue N0 = N->getOperand(0);
16689   SDValue N1 = N->getOperand(1);
16690   DebugLoc DL = N->getDebugLoc();
16691
16692   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16693   // and change it to SUB and CMOV.
16694   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16695       N0.getOpcode() == ISD::ADD &&
16696       N0.getOperand(1) == N1 &&
16697       N1.getOpcode() == ISD::SRA &&
16698       N1.getOperand(0) == N0.getOperand(0))
16699     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16700       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16701         // Generate SUB & CMOV.
16702         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16703                                   DAG.getConstant(0, VT), N0.getOperand(0));
16704
16705         SDValue Ops[] = { N0.getOperand(0), Neg,
16706                           DAG.getConstant(X86::COND_GE, MVT::i8),
16707                           SDValue(Neg.getNode(), 1) };
16708         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16709                            Ops, array_lengthof(Ops));
16710       }
16711   return SDValue();
16712 }
16713
16714 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16715 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16716                                  TargetLowering::DAGCombinerInfo &DCI,
16717                                  const X86Subtarget *Subtarget) {
16718   EVT VT = N->getValueType(0);
16719   if (DCI.isBeforeLegalizeOps())
16720     return SDValue();
16721
16722   if (Subtarget->hasCMov()) {
16723     SDValue RV = performIntegerAbsCombine(N, DAG);
16724     if (RV.getNode())
16725       return RV;
16726   }
16727
16728   // Try forming BMI if it is available.
16729   if (!Subtarget->hasBMI())
16730     return SDValue();
16731
16732   if (VT != MVT::i32 && VT != MVT::i64)
16733     return SDValue();
16734
16735   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16736
16737   // Create BLSMSK instructions by finding X ^ (X-1)
16738   SDValue N0 = N->getOperand(0);
16739   SDValue N1 = N->getOperand(1);
16740   DebugLoc DL = N->getDebugLoc();
16741
16742   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16743       isAllOnes(N0.getOperand(1)))
16744     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16745
16746   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16747       isAllOnes(N1.getOperand(1)))
16748     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16749
16750   return SDValue();
16751 }
16752
16753 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16754 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16755                                   TargetLowering::DAGCombinerInfo &DCI,
16756                                   const X86Subtarget *Subtarget) {
16757   LoadSDNode *Ld = cast<LoadSDNode>(N);
16758   EVT RegVT = Ld->getValueType(0);
16759   EVT MemVT = Ld->getMemoryVT();
16760   DebugLoc dl = Ld->getDebugLoc();
16761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16762   unsigned RegSz = RegVT.getSizeInBits();
16763
16764   // On Sandybridge unaligned 256bit loads are inefficient.
16765   ISD::LoadExtType Ext = Ld->getExtensionType();
16766   unsigned Alignment = Ld->getAlignment();
16767   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16768   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16769       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16770     unsigned NumElems = RegVT.getVectorNumElements();
16771     if (NumElems < 2)
16772       return SDValue();
16773
16774     SDValue Ptr = Ld->getBasePtr();
16775     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16776
16777     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16778                                   NumElems/2);
16779     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16780                                 Ld->getPointerInfo(), Ld->isVolatile(),
16781                                 Ld->isNonTemporal(), Ld->isInvariant(),
16782                                 Alignment);
16783     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16784     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16785                                 Ld->getPointerInfo(), Ld->isVolatile(),
16786                                 Ld->isNonTemporal(), Ld->isInvariant(),
16787                                 std::min(16U, Alignment));
16788     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16789                              Load1.getValue(1),
16790                              Load2.getValue(1));
16791
16792     SDValue NewVec = DAG.getUNDEF(RegVT);
16793     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16794     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16795     return DCI.CombineTo(N, NewVec, TF, true);
16796   }
16797
16798   // If this is a vector EXT Load then attempt to optimize it using a
16799   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16800   // expansion is still better than scalar code.
16801   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16802   // emit a shuffle and a arithmetic shift.
16803   // TODO: It is possible to support ZExt by zeroing the undef values
16804   // during the shuffle phase or after the shuffle.
16805   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16806       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16807     assert(MemVT != RegVT && "Cannot extend to the same type");
16808     assert(MemVT.isVector() && "Must load a vector from memory");
16809
16810     unsigned NumElems = RegVT.getVectorNumElements();
16811     unsigned MemSz = MemVT.getSizeInBits();
16812     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16813
16814     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16815       return SDValue();
16816
16817     // All sizes must be a power of two.
16818     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16819       return SDValue();
16820
16821     // Attempt to load the original value using scalar loads.
16822     // Find the largest scalar type that divides the total loaded size.
16823     MVT SclrLoadTy = MVT::i8;
16824     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16825          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16826       MVT Tp = (MVT::SimpleValueType)tp;
16827       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16828         SclrLoadTy = Tp;
16829       }
16830     }
16831
16832     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16833     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16834         (64 <= MemSz))
16835       SclrLoadTy = MVT::f64;
16836
16837     // Calculate the number of scalar loads that we need to perform
16838     // in order to load our vector from memory.
16839     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16840     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16841       return SDValue();
16842
16843     unsigned loadRegZize = RegSz;
16844     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16845       loadRegZize /= 2;
16846
16847     // Represent our vector as a sequence of elements which are the
16848     // largest scalar that we can load.
16849     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16850       loadRegZize/SclrLoadTy.getSizeInBits());
16851
16852     // Represent the data using the same element type that is stored in
16853     // memory. In practice, we ''widen'' MemVT.
16854     EVT WideVecVT =
16855           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16856                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16857
16858     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16859       "Invalid vector type");
16860
16861     // We can't shuffle using an illegal type.
16862     if (!TLI.isTypeLegal(WideVecVT))
16863       return SDValue();
16864
16865     SmallVector<SDValue, 8> Chains;
16866     SDValue Ptr = Ld->getBasePtr();
16867     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16868                                         TLI.getPointerTy());
16869     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16870
16871     for (unsigned i = 0; i < NumLoads; ++i) {
16872       // Perform a single load.
16873       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16874                                        Ptr, Ld->getPointerInfo(),
16875                                        Ld->isVolatile(), Ld->isNonTemporal(),
16876                                        Ld->isInvariant(), Ld->getAlignment());
16877       Chains.push_back(ScalarLoad.getValue(1));
16878       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16879       // another round of DAGCombining.
16880       if (i == 0)
16881         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16882       else
16883         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16884                           ScalarLoad, DAG.getIntPtrConstant(i));
16885
16886       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16887     }
16888
16889     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16890                                Chains.size());
16891
16892     // Bitcast the loaded value to a vector of the original element type, in
16893     // the size of the target vector type.
16894     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16895     unsigned SizeRatio = RegSz/MemSz;
16896
16897     if (Ext == ISD::SEXTLOAD) {
16898       // If we have SSE4.1 we can directly emit a VSEXT node.
16899       if (Subtarget->hasSSE41()) {
16900         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16901         return DCI.CombineTo(N, Sext, TF, true);
16902       }
16903
16904       // Otherwise we'll shuffle the small elements in the high bits of the
16905       // larger type and perform an arithmetic shift. If the shift is not legal
16906       // it's better to scalarize.
16907       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16908         return SDValue();
16909
16910       // Redistribute the loaded elements into the different locations.
16911       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16912       for (unsigned i = 0; i != NumElems; ++i)
16913         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16914
16915       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16916                                            DAG.getUNDEF(WideVecVT),
16917                                            &ShuffleVec[0]);
16918
16919       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16920
16921       // Build the arithmetic shift.
16922       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16923                      MemVT.getVectorElementType().getSizeInBits();
16924       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16925                           DAG.getConstant(Amt, RegVT));
16926
16927       return DCI.CombineTo(N, Shuff, TF, true);
16928     }
16929
16930     // Redistribute the loaded elements into the different locations.
16931     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16932     for (unsigned i = 0; i != NumElems; ++i)
16933       ShuffleVec[i*SizeRatio] = i;
16934
16935     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16936                                          DAG.getUNDEF(WideVecVT),
16937                                          &ShuffleVec[0]);
16938
16939     // Bitcast to the requested type.
16940     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16941     // Replace the original load with the new sequence
16942     // and return the new chain.
16943     return DCI.CombineTo(N, Shuff, TF, true);
16944   }
16945
16946   return SDValue();
16947 }
16948
16949 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16950 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16951                                    const X86Subtarget *Subtarget) {
16952   StoreSDNode *St = cast<StoreSDNode>(N);
16953   EVT VT = St->getValue().getValueType();
16954   EVT StVT = St->getMemoryVT();
16955   DebugLoc dl = St->getDebugLoc();
16956   SDValue StoredVal = St->getOperand(1);
16957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16958
16959   // If we are saving a concatenation of two XMM registers, perform two stores.
16960   // On Sandy Bridge, 256-bit memory operations are executed by two
16961   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16962   // memory  operation.
16963   unsigned Alignment = St->getAlignment();
16964   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
16965   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16966       StVT == VT && !IsAligned) {
16967     unsigned NumElems = VT.getVectorNumElements();
16968     if (NumElems < 2)
16969       return SDValue();
16970
16971     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16972     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16973
16974     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16975     SDValue Ptr0 = St->getBasePtr();
16976     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16977
16978     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16979                                 St->getPointerInfo(), St->isVolatile(),
16980                                 St->isNonTemporal(), Alignment);
16981     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16982                                 St->getPointerInfo(), St->isVolatile(),
16983                                 St->isNonTemporal(),
16984                                 std::min(16U, Alignment));
16985     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16986   }
16987
16988   // Optimize trunc store (of multiple scalars) to shuffle and store.
16989   // First, pack all of the elements in one place. Next, store to memory
16990   // in fewer chunks.
16991   if (St->isTruncatingStore() && VT.isVector()) {
16992     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16993     unsigned NumElems = VT.getVectorNumElements();
16994     assert(StVT != VT && "Cannot truncate to the same type");
16995     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16996     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16997
16998     // From, To sizes and ElemCount must be pow of two
16999     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17000     // We are going to use the original vector elt for storing.
17001     // Accumulated smaller vector elements must be a multiple of the store size.
17002     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17003
17004     unsigned SizeRatio  = FromSz / ToSz;
17005
17006     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17007
17008     // Create a type on which we perform the shuffle
17009     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17010             StVT.getScalarType(), NumElems*SizeRatio);
17011
17012     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17013
17014     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17015     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17016     for (unsigned i = 0; i != NumElems; ++i)
17017       ShuffleVec[i] = i * SizeRatio;
17018
17019     // Can't shuffle using an illegal type.
17020     if (!TLI.isTypeLegal(WideVecVT))
17021       return SDValue();
17022
17023     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17024                                          DAG.getUNDEF(WideVecVT),
17025                                          &ShuffleVec[0]);
17026     // At this point all of the data is stored at the bottom of the
17027     // register. We now need to save it to mem.
17028
17029     // Find the largest store unit
17030     MVT StoreType = MVT::i8;
17031     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17032          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17033       MVT Tp = (MVT::SimpleValueType)tp;
17034       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17035         StoreType = Tp;
17036     }
17037
17038     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17039     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17040         (64 <= NumElems * ToSz))
17041       StoreType = MVT::f64;
17042
17043     // Bitcast the original vector into a vector of store-size units
17044     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17045             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17046     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17047     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17048     SmallVector<SDValue, 8> Chains;
17049     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17050                                         TLI.getPointerTy());
17051     SDValue Ptr = St->getBasePtr();
17052
17053     // Perform one or more big stores into memory.
17054     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17055       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17056                                    StoreType, ShuffWide,
17057                                    DAG.getIntPtrConstant(i));
17058       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17059                                 St->getPointerInfo(), St->isVolatile(),
17060                                 St->isNonTemporal(), St->getAlignment());
17061       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17062       Chains.push_back(Ch);
17063     }
17064
17065     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17066                                Chains.size());
17067   }
17068
17069   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17070   // the FP state in cases where an emms may be missing.
17071   // A preferable solution to the general problem is to figure out the right
17072   // places to insert EMMS.  This qualifies as a quick hack.
17073
17074   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17075   if (VT.getSizeInBits() != 64)
17076     return SDValue();
17077
17078   const Function *F = DAG.getMachineFunction().getFunction();
17079   bool NoImplicitFloatOps = F->getAttributes().
17080     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17081   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17082                      && Subtarget->hasSSE2();
17083   if ((VT.isVector() ||
17084        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17085       isa<LoadSDNode>(St->getValue()) &&
17086       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17087       St->getChain().hasOneUse() && !St->isVolatile()) {
17088     SDNode* LdVal = St->getValue().getNode();
17089     LoadSDNode *Ld = 0;
17090     int TokenFactorIndex = -1;
17091     SmallVector<SDValue, 8> Ops;
17092     SDNode* ChainVal = St->getChain().getNode();
17093     // Must be a store of a load.  We currently handle two cases:  the load
17094     // is a direct child, and it's under an intervening TokenFactor.  It is
17095     // possible to dig deeper under nested TokenFactors.
17096     if (ChainVal == LdVal)
17097       Ld = cast<LoadSDNode>(St->getChain());
17098     else if (St->getValue().hasOneUse() &&
17099              ChainVal->getOpcode() == ISD::TokenFactor) {
17100       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17101         if (ChainVal->getOperand(i).getNode() == LdVal) {
17102           TokenFactorIndex = i;
17103           Ld = cast<LoadSDNode>(St->getValue());
17104         } else
17105           Ops.push_back(ChainVal->getOperand(i));
17106       }
17107     }
17108
17109     if (!Ld || !ISD::isNormalLoad(Ld))
17110       return SDValue();
17111
17112     // If this is not the MMX case, i.e. we are just turning i64 load/store
17113     // into f64 load/store, avoid the transformation if there are multiple
17114     // uses of the loaded value.
17115     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17116       return SDValue();
17117
17118     DebugLoc LdDL = Ld->getDebugLoc();
17119     DebugLoc StDL = N->getDebugLoc();
17120     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17121     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17122     // pair instead.
17123     if (Subtarget->is64Bit() || F64IsLegal) {
17124       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17125       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17126                                   Ld->getPointerInfo(), Ld->isVolatile(),
17127                                   Ld->isNonTemporal(), Ld->isInvariant(),
17128                                   Ld->getAlignment());
17129       SDValue NewChain = NewLd.getValue(1);
17130       if (TokenFactorIndex != -1) {
17131         Ops.push_back(NewChain);
17132         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17133                                Ops.size());
17134       }
17135       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17136                           St->getPointerInfo(),
17137                           St->isVolatile(), St->isNonTemporal(),
17138                           St->getAlignment());
17139     }
17140
17141     // Otherwise, lower to two pairs of 32-bit loads / stores.
17142     SDValue LoAddr = Ld->getBasePtr();
17143     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17144                                  DAG.getConstant(4, MVT::i32));
17145
17146     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17147                                Ld->getPointerInfo(),
17148                                Ld->isVolatile(), Ld->isNonTemporal(),
17149                                Ld->isInvariant(), Ld->getAlignment());
17150     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17151                                Ld->getPointerInfo().getWithOffset(4),
17152                                Ld->isVolatile(), Ld->isNonTemporal(),
17153                                Ld->isInvariant(),
17154                                MinAlign(Ld->getAlignment(), 4));
17155
17156     SDValue NewChain = LoLd.getValue(1);
17157     if (TokenFactorIndex != -1) {
17158       Ops.push_back(LoLd);
17159       Ops.push_back(HiLd);
17160       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17161                              Ops.size());
17162     }
17163
17164     LoAddr = St->getBasePtr();
17165     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17166                          DAG.getConstant(4, MVT::i32));
17167
17168     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17169                                 St->getPointerInfo(),
17170                                 St->isVolatile(), St->isNonTemporal(),
17171                                 St->getAlignment());
17172     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17173                                 St->getPointerInfo().getWithOffset(4),
17174                                 St->isVolatile(),
17175                                 St->isNonTemporal(),
17176                                 MinAlign(St->getAlignment(), 4));
17177     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17178   }
17179   return SDValue();
17180 }
17181
17182 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17183 /// and return the operands for the horizontal operation in LHS and RHS.  A
17184 /// horizontal operation performs the binary operation on successive elements
17185 /// of its first operand, then on successive elements of its second operand,
17186 /// returning the resulting values in a vector.  For example, if
17187 ///   A = < float a0, float a1, float a2, float a3 >
17188 /// and
17189 ///   B = < float b0, float b1, float b2, float b3 >
17190 /// then the result of doing a horizontal operation on A and B is
17191 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17192 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17193 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17194 /// set to A, RHS to B, and the routine returns 'true'.
17195 /// Note that the binary operation should have the property that if one of the
17196 /// operands is UNDEF then the result is UNDEF.
17197 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17198   // Look for the following pattern: if
17199   //   A = < float a0, float a1, float a2, float a3 >
17200   //   B = < float b0, float b1, float b2, float b3 >
17201   // and
17202   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17203   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17204   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17205   // which is A horizontal-op B.
17206
17207   // At least one of the operands should be a vector shuffle.
17208   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17209       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17210     return false;
17211
17212   EVT VT = LHS.getValueType();
17213
17214   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17215          "Unsupported vector type for horizontal add/sub");
17216
17217   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17218   // operate independently on 128-bit lanes.
17219   unsigned NumElts = VT.getVectorNumElements();
17220   unsigned NumLanes = VT.getSizeInBits()/128;
17221   unsigned NumLaneElts = NumElts / NumLanes;
17222   assert((NumLaneElts % 2 == 0) &&
17223          "Vector type should have an even number of elements in each lane");
17224   unsigned HalfLaneElts = NumLaneElts/2;
17225
17226   // View LHS in the form
17227   //   LHS = VECTOR_SHUFFLE A, B, LMask
17228   // If LHS is not a shuffle then pretend it is the shuffle
17229   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17230   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17231   // type VT.
17232   SDValue A, B;
17233   SmallVector<int, 16> LMask(NumElts);
17234   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17235     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17236       A = LHS.getOperand(0);
17237     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17238       B = LHS.getOperand(1);
17239     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17240     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17241   } else {
17242     if (LHS.getOpcode() != ISD::UNDEF)
17243       A = LHS;
17244     for (unsigned i = 0; i != NumElts; ++i)
17245       LMask[i] = i;
17246   }
17247
17248   // Likewise, view RHS in the form
17249   //   RHS = VECTOR_SHUFFLE C, D, RMask
17250   SDValue C, D;
17251   SmallVector<int, 16> RMask(NumElts);
17252   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17253     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17254       C = RHS.getOperand(0);
17255     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17256       D = RHS.getOperand(1);
17257     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17258     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17259   } else {
17260     if (RHS.getOpcode() != ISD::UNDEF)
17261       C = RHS;
17262     for (unsigned i = 0; i != NumElts; ++i)
17263       RMask[i] = i;
17264   }
17265
17266   // Check that the shuffles are both shuffling the same vectors.
17267   if (!(A == C && B == D) && !(A == D && B == C))
17268     return false;
17269
17270   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17271   if (!A.getNode() && !B.getNode())
17272     return false;
17273
17274   // If A and B occur in reverse order in RHS, then "swap" them (which means
17275   // rewriting the mask).
17276   if (A != C)
17277     CommuteVectorShuffleMask(RMask, NumElts);
17278
17279   // At this point LHS and RHS are equivalent to
17280   //   LHS = VECTOR_SHUFFLE A, B, LMask
17281   //   RHS = VECTOR_SHUFFLE A, B, RMask
17282   // Check that the masks correspond to performing a horizontal operation.
17283   for (unsigned i = 0; i != NumElts; ++i) {
17284     int LIdx = LMask[i], RIdx = RMask[i];
17285
17286     // Ignore any UNDEF components.
17287     if (LIdx < 0 || RIdx < 0 ||
17288         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17289         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17290       continue;
17291
17292     // Check that successive elements are being operated on.  If not, this is
17293     // not a horizontal operation.
17294     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17295     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17296     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17297     if (!(LIdx == Index && RIdx == Index + 1) &&
17298         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17299       return false;
17300   }
17301
17302   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17303   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17304   return true;
17305 }
17306
17307 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17308 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17309                                   const X86Subtarget *Subtarget) {
17310   EVT VT = N->getValueType(0);
17311   SDValue LHS = N->getOperand(0);
17312   SDValue RHS = N->getOperand(1);
17313
17314   // Try to synthesize horizontal adds from adds of shuffles.
17315   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17316        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17317       isHorizontalBinOp(LHS, RHS, true))
17318     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17319   return SDValue();
17320 }
17321
17322 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17323 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17324                                   const X86Subtarget *Subtarget) {
17325   EVT VT = N->getValueType(0);
17326   SDValue LHS = N->getOperand(0);
17327   SDValue RHS = N->getOperand(1);
17328
17329   // Try to synthesize horizontal subs from subs of shuffles.
17330   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17331        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17332       isHorizontalBinOp(LHS, RHS, false))
17333     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17334   return SDValue();
17335 }
17336
17337 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17338 /// X86ISD::FXOR nodes.
17339 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17340   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17341   // F[X]OR(0.0, x) -> x
17342   // F[X]OR(x, 0.0) -> x
17343   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17344     if (C->getValueAPF().isPosZero())
17345       return N->getOperand(1);
17346   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17347     if (C->getValueAPF().isPosZero())
17348       return N->getOperand(0);
17349   return SDValue();
17350 }
17351
17352 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17353 /// X86ISD::FMAX nodes.
17354 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17355   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17356
17357   // Only perform optimizations if UnsafeMath is used.
17358   if (!DAG.getTarget().Options.UnsafeFPMath)
17359     return SDValue();
17360
17361   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17362   // into FMINC and FMAXC, which are Commutative operations.
17363   unsigned NewOp = 0;
17364   switch (N->getOpcode()) {
17365     default: llvm_unreachable("unknown opcode");
17366     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17367     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17368   }
17369
17370   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17371                      N->getOperand(0), N->getOperand(1));
17372 }
17373
17374 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17375 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17376   // FAND(0.0, x) -> 0.0
17377   // FAND(x, 0.0) -> 0.0
17378   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17379     if (C->getValueAPF().isPosZero())
17380       return N->getOperand(0);
17381   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17382     if (C->getValueAPF().isPosZero())
17383       return N->getOperand(1);
17384   return SDValue();
17385 }
17386
17387 static SDValue PerformBTCombine(SDNode *N,
17388                                 SelectionDAG &DAG,
17389                                 TargetLowering::DAGCombinerInfo &DCI) {
17390   // BT ignores high bits in the bit index operand.
17391   SDValue Op1 = N->getOperand(1);
17392   if (Op1.hasOneUse()) {
17393     unsigned BitWidth = Op1.getValueSizeInBits();
17394     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17395     APInt KnownZero, KnownOne;
17396     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17397                                           !DCI.isBeforeLegalizeOps());
17398     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17399     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17400         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17401       DCI.CommitTargetLoweringOpt(TLO);
17402   }
17403   return SDValue();
17404 }
17405
17406 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17407   SDValue Op = N->getOperand(0);
17408   if (Op.getOpcode() == ISD::BITCAST)
17409     Op = Op.getOperand(0);
17410   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17411   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17412       VT.getVectorElementType().getSizeInBits() ==
17413       OpVT.getVectorElementType().getSizeInBits()) {
17414     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17415   }
17416   return SDValue();
17417 }
17418
17419 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 
17420                                                const X86Subtarget *Subtarget) {
17421   EVT VT = N->getValueType(0);
17422   if (!VT.isVector())
17423     return SDValue();
17424
17425   SDValue N0 = N->getOperand(0);
17426   SDValue N1 = N->getOperand(1);
17427   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17428   DebugLoc dl = N->getDebugLoc();
17429
17430   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17431   // both SSE and AVX2 since there is no sign-extended shift right
17432   // operation on a vector with 64-bit elements.
17433   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17434   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17435   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17436       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17437     SDValue N00 = N0.getOperand(0);
17438
17439     // EXTLOAD has a better solution on AVX2, 
17440     // it may be replaced with X86ISD::VSEXT node.
17441     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17442       if (!ISD::isNormalLoad(N00.getNode()))
17443         return SDValue();
17444
17445     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17446         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 
17447                                   N00, N1);
17448       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17449     }
17450   }
17451   return SDValue();
17452 }
17453
17454 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17455                                   TargetLowering::DAGCombinerInfo &DCI,
17456                                   const X86Subtarget *Subtarget) {
17457   if (!DCI.isBeforeLegalizeOps())
17458     return SDValue();
17459
17460   if (!Subtarget->hasFp256())
17461     return SDValue();
17462
17463   EVT VT = N->getValueType(0);
17464   if (VT.isVector() && VT.getSizeInBits() == 256) {
17465     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17466     if (R.getNode())
17467       return R;
17468   }
17469
17470   return SDValue();
17471 }
17472
17473 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17474                                  const X86Subtarget* Subtarget) {
17475   DebugLoc dl = N->getDebugLoc();
17476   EVT VT = N->getValueType(0);
17477
17478   // Let legalize expand this if it isn't a legal type yet.
17479   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17480     return SDValue();
17481
17482   EVT ScalarVT = VT.getScalarType();
17483   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17484       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17485     return SDValue();
17486
17487   SDValue A = N->getOperand(0);
17488   SDValue B = N->getOperand(1);
17489   SDValue C = N->getOperand(2);
17490
17491   bool NegA = (A.getOpcode() == ISD::FNEG);
17492   bool NegB = (B.getOpcode() == ISD::FNEG);
17493   bool NegC = (C.getOpcode() == ISD::FNEG);
17494
17495   // Negative multiplication when NegA xor NegB
17496   bool NegMul = (NegA != NegB);
17497   if (NegA)
17498     A = A.getOperand(0);
17499   if (NegB)
17500     B = B.getOperand(0);
17501   if (NegC)
17502     C = C.getOperand(0);
17503
17504   unsigned Opcode;
17505   if (!NegMul)
17506     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17507   else
17508     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17509
17510   return DAG.getNode(Opcode, dl, VT, A, B, C);
17511 }
17512
17513 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17514                                   TargetLowering::DAGCombinerInfo &DCI,
17515                                   const X86Subtarget *Subtarget) {
17516   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17517   //           (and (i32 x86isd::setcc_carry), 1)
17518   // This eliminates the zext. This transformation is necessary because
17519   // ISD::SETCC is always legalized to i8.
17520   DebugLoc dl = N->getDebugLoc();
17521   SDValue N0 = N->getOperand(0);
17522   EVT VT = N->getValueType(0);
17523
17524   if (N0.getOpcode() == ISD::AND &&
17525       N0.hasOneUse() &&
17526       N0.getOperand(0).hasOneUse()) {
17527     SDValue N00 = N0.getOperand(0);
17528     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17529       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17530       if (!C || C->getZExtValue() != 1)
17531         return SDValue();
17532       return DAG.getNode(ISD::AND, dl, VT,
17533                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17534                                      N00.getOperand(0), N00.getOperand(1)),
17535                          DAG.getConstant(1, VT));
17536     }
17537   }
17538
17539   if (VT.is256BitVector()) {
17540     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17541     if (R.getNode())
17542       return R;
17543   }
17544
17545   return SDValue();
17546 }
17547
17548 // Optimize x == -y --> x+y == 0
17549 //          x != -y --> x+y != 0
17550 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17551   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17552   SDValue LHS = N->getOperand(0);
17553   SDValue RHS = N->getOperand(1);
17554
17555   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17556     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17557       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17558         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17559                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17560         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17561                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17562       }
17563   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17564     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17565       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17566         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17567                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17568         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17569                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17570       }
17571   return SDValue();
17572 }
17573
17574 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17575 // as "sbb reg,reg", since it can be extended without zext and produces
17576 // an all-ones bit which is more useful than 0/1 in some cases.
17577 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17578   return DAG.getNode(ISD::AND, DL, MVT::i8,
17579                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17580                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17581                      DAG.getConstant(1, MVT::i8));
17582 }
17583
17584 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17585 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17586                                    TargetLowering::DAGCombinerInfo &DCI,
17587                                    const X86Subtarget *Subtarget) {
17588   DebugLoc DL = N->getDebugLoc();
17589   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17590   SDValue EFLAGS = N->getOperand(1);
17591
17592   if (CC == X86::COND_A) {
17593     // Try to convert COND_A into COND_B in an attempt to facilitate
17594     // materializing "setb reg".
17595     //
17596     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17597     // cannot take an immediate as its first operand.
17598     //
17599     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17600         EFLAGS.getValueType().isInteger() &&
17601         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17602       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17603                                    EFLAGS.getNode()->getVTList(),
17604                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17605       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17606       return MaterializeSETB(DL, NewEFLAGS, DAG);
17607     }
17608   }
17609
17610   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17611   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17612   // cases.
17613   if (CC == X86::COND_B)
17614     return MaterializeSETB(DL, EFLAGS, DAG);
17615
17616   SDValue Flags;
17617
17618   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17619   if (Flags.getNode()) {
17620     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17621     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17622   }
17623
17624   return SDValue();
17625 }
17626
17627 // Optimize branch condition evaluation.
17628 //
17629 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17630                                     TargetLowering::DAGCombinerInfo &DCI,
17631                                     const X86Subtarget *Subtarget) {
17632   DebugLoc DL = N->getDebugLoc();
17633   SDValue Chain = N->getOperand(0);
17634   SDValue Dest = N->getOperand(1);
17635   SDValue EFLAGS = N->getOperand(3);
17636   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17637
17638   SDValue Flags;
17639
17640   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17641   if (Flags.getNode()) {
17642     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17643     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17644                        Flags);
17645   }
17646
17647   return SDValue();
17648 }
17649
17650 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17651                                         const X86TargetLowering *XTLI) {
17652   SDValue Op0 = N->getOperand(0);
17653   EVT InVT = Op0->getValueType(0);
17654
17655   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17656   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17657     DebugLoc dl = N->getDebugLoc();
17658     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17659     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17660     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17661   }
17662
17663   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17664   // a 32-bit target where SSE doesn't support i64->FP operations.
17665   if (Op0.getOpcode() == ISD::LOAD) {
17666     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17667     EVT VT = Ld->getValueType(0);
17668     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17669         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17670         !XTLI->getSubtarget()->is64Bit() &&
17671         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17672       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17673                                           Ld->getChain(), Op0, DAG);
17674       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17675       return FILDChain;
17676     }
17677   }
17678   return SDValue();
17679 }
17680
17681 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17682 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17683                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17684   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17685   // the result is either zero or one (depending on the input carry bit).
17686   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17687   if (X86::isZeroNode(N->getOperand(0)) &&
17688       X86::isZeroNode(N->getOperand(1)) &&
17689       // We don't have a good way to replace an EFLAGS use, so only do this when
17690       // dead right now.
17691       SDValue(N, 1).use_empty()) {
17692     DebugLoc DL = N->getDebugLoc();
17693     EVT VT = N->getValueType(0);
17694     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17695     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17696                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17697                                            DAG.getConstant(X86::COND_B,MVT::i8),
17698                                            N->getOperand(2)),
17699                                DAG.getConstant(1, VT));
17700     return DCI.CombineTo(N, Res1, CarryOut);
17701   }
17702
17703   return SDValue();
17704 }
17705
17706 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17707 //      (add Y, (setne X, 0)) -> sbb -1, Y
17708 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17709 //      (sub (setne X, 0), Y) -> adc -1, Y
17710 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17711   DebugLoc DL = N->getDebugLoc();
17712
17713   // Look through ZExts.
17714   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17715   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17716     return SDValue();
17717
17718   SDValue SetCC = Ext.getOperand(0);
17719   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17720     return SDValue();
17721
17722   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17723   if (CC != X86::COND_E && CC != X86::COND_NE)
17724     return SDValue();
17725
17726   SDValue Cmp = SetCC.getOperand(1);
17727   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17728       !X86::isZeroNode(Cmp.getOperand(1)) ||
17729       !Cmp.getOperand(0).getValueType().isInteger())
17730     return SDValue();
17731
17732   SDValue CmpOp0 = Cmp.getOperand(0);
17733   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17734                                DAG.getConstant(1, CmpOp0.getValueType()));
17735
17736   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17737   if (CC == X86::COND_NE)
17738     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17739                        DL, OtherVal.getValueType(), OtherVal,
17740                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17741   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17742                      DL, OtherVal.getValueType(), OtherVal,
17743                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17744 }
17745
17746 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17747 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17748                                  const X86Subtarget *Subtarget) {
17749   EVT VT = N->getValueType(0);
17750   SDValue Op0 = N->getOperand(0);
17751   SDValue Op1 = N->getOperand(1);
17752
17753   // Try to synthesize horizontal adds from adds of shuffles.
17754   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17755        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17756       isHorizontalBinOp(Op0, Op1, true))
17757     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17758
17759   return OptimizeConditionalInDecrement(N, DAG);
17760 }
17761
17762 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17763                                  const X86Subtarget *Subtarget) {
17764   SDValue Op0 = N->getOperand(0);
17765   SDValue Op1 = N->getOperand(1);
17766
17767   // X86 can't encode an immediate LHS of a sub. See if we can push the
17768   // negation into a preceding instruction.
17769   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17770     // If the RHS of the sub is a XOR with one use and a constant, invert the
17771     // immediate. Then add one to the LHS of the sub so we can turn
17772     // X-Y -> X+~Y+1, saving one register.
17773     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17774         isa<ConstantSDNode>(Op1.getOperand(1))) {
17775       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17776       EVT VT = Op0.getValueType();
17777       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17778                                    Op1.getOperand(0),
17779                                    DAG.getConstant(~XorC, VT));
17780       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17781                          DAG.getConstant(C->getAPIntValue()+1, VT));
17782     }
17783   }
17784
17785   // Try to synthesize horizontal adds from adds of shuffles.
17786   EVT VT = N->getValueType(0);
17787   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17788        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17789       isHorizontalBinOp(Op0, Op1, true))
17790     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17791
17792   return OptimizeConditionalInDecrement(N, DAG);
17793 }
17794
17795 /// performVZEXTCombine - Performs build vector combines
17796 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17797                                         TargetLowering::DAGCombinerInfo &DCI,
17798                                         const X86Subtarget *Subtarget) {
17799   // (vzext (bitcast (vzext (x)) -> (vzext x)
17800   SDValue In = N->getOperand(0);
17801   while (In.getOpcode() == ISD::BITCAST)
17802     In = In.getOperand(0);
17803
17804   if (In.getOpcode() != X86ISD::VZEXT)
17805     return SDValue();
17806
17807   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17808                      In.getOperand(0));
17809 }
17810
17811 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17812                                              DAGCombinerInfo &DCI) const {
17813   SelectionDAG &DAG = DCI.DAG;
17814   switch (N->getOpcode()) {
17815   default: break;
17816   case ISD::EXTRACT_VECTOR_ELT:
17817     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17818   case ISD::VSELECT:
17819   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17820   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17821   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17822   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17823   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17824   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17825   case ISD::SHL:
17826   case ISD::SRA:
17827   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17828   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17829   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17830   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17831   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17832   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17833   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17834   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17835   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17836   case X86ISD::FXOR:
17837   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17838   case X86ISD::FMIN:
17839   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17840   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17841   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17842   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17843   case ISD::ANY_EXTEND:
17844   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17845   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17846   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17847   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17848   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17849   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17850   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17851   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17852   case X86ISD::SHUFP:       // Handle all target specific shuffles
17853   case X86ISD::PALIGNR:
17854   case X86ISD::UNPCKH:
17855   case X86ISD::UNPCKL:
17856   case X86ISD::MOVHLPS:
17857   case X86ISD::MOVLHPS:
17858   case X86ISD::PSHUFD:
17859   case X86ISD::PSHUFHW:
17860   case X86ISD::PSHUFLW:
17861   case X86ISD::MOVSS:
17862   case X86ISD::MOVSD:
17863   case X86ISD::VPERMILP:
17864   case X86ISD::VPERM2X128:
17865   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17866   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17867   }
17868
17869   return SDValue();
17870 }
17871
17872 /// isTypeDesirableForOp - Return true if the target has native support for
17873 /// the specified value type and it is 'desirable' to use the type for the
17874 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17875 /// instruction encodings are longer and some i16 instructions are slow.
17876 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17877   if (!isTypeLegal(VT))
17878     return false;
17879   if (VT != MVT::i16)
17880     return true;
17881
17882   switch (Opc) {
17883   default:
17884     return true;
17885   case ISD::LOAD:
17886   case ISD::SIGN_EXTEND:
17887   case ISD::ZERO_EXTEND:
17888   case ISD::ANY_EXTEND:
17889   case ISD::SHL:
17890   case ISD::SRL:
17891   case ISD::SUB:
17892   case ISD::ADD:
17893   case ISD::MUL:
17894   case ISD::AND:
17895   case ISD::OR:
17896   case ISD::XOR:
17897     return false;
17898   }
17899 }
17900
17901 /// IsDesirableToPromoteOp - This method query the target whether it is
17902 /// beneficial for dag combiner to promote the specified node. If true, it
17903 /// should return the desired promotion type by reference.
17904 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17905   EVT VT = Op.getValueType();
17906   if (VT != MVT::i16)
17907     return false;
17908
17909   bool Promote = false;
17910   bool Commute = false;
17911   switch (Op.getOpcode()) {
17912   default: break;
17913   case ISD::LOAD: {
17914     LoadSDNode *LD = cast<LoadSDNode>(Op);
17915     // If the non-extending load has a single use and it's not live out, then it
17916     // might be folded.
17917     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17918                                                      Op.hasOneUse()*/) {
17919       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17920              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17921         // The only case where we'd want to promote LOAD (rather then it being
17922         // promoted as an operand is when it's only use is liveout.
17923         if (UI->getOpcode() != ISD::CopyToReg)
17924           return false;
17925       }
17926     }
17927     Promote = true;
17928     break;
17929   }
17930   case ISD::SIGN_EXTEND:
17931   case ISD::ZERO_EXTEND:
17932   case ISD::ANY_EXTEND:
17933     Promote = true;
17934     break;
17935   case ISD::SHL:
17936   case ISD::SRL: {
17937     SDValue N0 = Op.getOperand(0);
17938     // Look out for (store (shl (load), x)).
17939     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17940       return false;
17941     Promote = true;
17942     break;
17943   }
17944   case ISD::ADD:
17945   case ISD::MUL:
17946   case ISD::AND:
17947   case ISD::OR:
17948   case ISD::XOR:
17949     Commute = true;
17950     // fallthrough
17951   case ISD::SUB: {
17952     SDValue N0 = Op.getOperand(0);
17953     SDValue N1 = Op.getOperand(1);
17954     if (!Commute && MayFoldLoad(N1))
17955       return false;
17956     // Avoid disabling potential load folding opportunities.
17957     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17958       return false;
17959     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17960       return false;
17961     Promote = true;
17962   }
17963   }
17964
17965   PVT = MVT::i32;
17966   return Promote;
17967 }
17968
17969 //===----------------------------------------------------------------------===//
17970 //                           X86 Inline Assembly Support
17971 //===----------------------------------------------------------------------===//
17972
17973 namespace {
17974   // Helper to match a string separated by whitespace.
17975   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17976     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17977
17978     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17979       StringRef piece(*args[i]);
17980       if (!s.startswith(piece)) // Check if the piece matches.
17981         return false;
17982
17983       s = s.substr(piece.size());
17984       StringRef::size_type pos = s.find_first_not_of(" \t");
17985       if (pos == 0) // We matched a prefix.
17986         return false;
17987
17988       s = s.substr(pos);
17989     }
17990
17991     return s.empty();
17992   }
17993   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17994 }
17995
17996 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17997   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17998
17999   std::string AsmStr = IA->getAsmString();
18000
18001   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18002   if (!Ty || Ty->getBitWidth() % 16 != 0)
18003     return false;
18004
18005   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18006   SmallVector<StringRef, 4> AsmPieces;
18007   SplitString(AsmStr, AsmPieces, ";\n");
18008
18009   switch (AsmPieces.size()) {
18010   default: return false;
18011   case 1:
18012     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18013     // we will turn this bswap into something that will be lowered to logical
18014     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18015     // lower so don't worry about this.
18016     // bswap $0
18017     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18018         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18019         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18020         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18021         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18022         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18023       // No need to check constraints, nothing other than the equivalent of
18024       // "=r,0" would be valid here.
18025       return IntrinsicLowering::LowerToByteSwap(CI);
18026     }
18027
18028     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18029     if (CI->getType()->isIntegerTy(16) &&
18030         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18031         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18032          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18033       AsmPieces.clear();
18034       const std::string &ConstraintsStr = IA->getConstraintString();
18035       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18036       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18037       if (AsmPieces.size() == 4 &&
18038           AsmPieces[0] == "~{cc}" &&
18039           AsmPieces[1] == "~{dirflag}" &&
18040           AsmPieces[2] == "~{flags}" &&
18041           AsmPieces[3] == "~{fpsr}")
18042       return IntrinsicLowering::LowerToByteSwap(CI);
18043     }
18044     break;
18045   case 3:
18046     if (CI->getType()->isIntegerTy(32) &&
18047         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18048         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18049         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18050         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18051       AsmPieces.clear();
18052       const std::string &ConstraintsStr = IA->getConstraintString();
18053       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18054       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18055       if (AsmPieces.size() == 4 &&
18056           AsmPieces[0] == "~{cc}" &&
18057           AsmPieces[1] == "~{dirflag}" &&
18058           AsmPieces[2] == "~{flags}" &&
18059           AsmPieces[3] == "~{fpsr}")
18060         return IntrinsicLowering::LowerToByteSwap(CI);
18061     }
18062
18063     if (CI->getType()->isIntegerTy(64)) {
18064       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18065       if (Constraints.size() >= 2 &&
18066           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18067           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18068         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18069         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18070             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18071             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18072           return IntrinsicLowering::LowerToByteSwap(CI);
18073       }
18074     }
18075     break;
18076   }
18077   return false;
18078 }
18079
18080 /// getConstraintType - Given a constraint letter, return the type of
18081 /// constraint it is for this target.
18082 X86TargetLowering::ConstraintType
18083 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18084   if (Constraint.size() == 1) {
18085     switch (Constraint[0]) {
18086     case 'R':
18087     case 'q':
18088     case 'Q':
18089     case 'f':
18090     case 't':
18091     case 'u':
18092     case 'y':
18093     case 'x':
18094     case 'Y':
18095     case 'l':
18096       return C_RegisterClass;
18097     case 'a':
18098     case 'b':
18099     case 'c':
18100     case 'd':
18101     case 'S':
18102     case 'D':
18103     case 'A':
18104       return C_Register;
18105     case 'I':
18106     case 'J':
18107     case 'K':
18108     case 'L':
18109     case 'M':
18110     case 'N':
18111     case 'G':
18112     case 'C':
18113     case 'e':
18114     case 'Z':
18115       return C_Other;
18116     default:
18117       break;
18118     }
18119   }
18120   return TargetLowering::getConstraintType(Constraint);
18121 }
18122
18123 /// Examine constraint type and operand type and determine a weight value.
18124 /// This object must already have been set up with the operand type
18125 /// and the current alternative constraint selected.
18126 TargetLowering::ConstraintWeight
18127   X86TargetLowering::getSingleConstraintMatchWeight(
18128     AsmOperandInfo &info, const char *constraint) const {
18129   ConstraintWeight weight = CW_Invalid;
18130   Value *CallOperandVal = info.CallOperandVal;
18131     // If we don't have a value, we can't do a match,
18132     // but allow it at the lowest weight.
18133   if (CallOperandVal == NULL)
18134     return CW_Default;
18135   Type *type = CallOperandVal->getType();
18136   // Look at the constraint type.
18137   switch (*constraint) {
18138   default:
18139     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18140   case 'R':
18141   case 'q':
18142   case 'Q':
18143   case 'a':
18144   case 'b':
18145   case 'c':
18146   case 'd':
18147   case 'S':
18148   case 'D':
18149   case 'A':
18150     if (CallOperandVal->getType()->isIntegerTy())
18151       weight = CW_SpecificReg;
18152     break;
18153   case 'f':
18154   case 't':
18155   case 'u':
18156     if (type->isFloatingPointTy())
18157       weight = CW_SpecificReg;
18158     break;
18159   case 'y':
18160     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18161       weight = CW_SpecificReg;
18162     break;
18163   case 'x':
18164   case 'Y':
18165     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18166         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18167       weight = CW_Register;
18168     break;
18169   case 'I':
18170     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18171       if (C->getZExtValue() <= 31)
18172         weight = CW_Constant;
18173     }
18174     break;
18175   case 'J':
18176     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18177       if (C->getZExtValue() <= 63)
18178         weight = CW_Constant;
18179     }
18180     break;
18181   case 'K':
18182     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18183       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18184         weight = CW_Constant;
18185     }
18186     break;
18187   case 'L':
18188     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18189       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18190         weight = CW_Constant;
18191     }
18192     break;
18193   case 'M':
18194     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18195       if (C->getZExtValue() <= 3)
18196         weight = CW_Constant;
18197     }
18198     break;
18199   case 'N':
18200     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18201       if (C->getZExtValue() <= 0xff)
18202         weight = CW_Constant;
18203     }
18204     break;
18205   case 'G':
18206   case 'C':
18207     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18208       weight = CW_Constant;
18209     }
18210     break;
18211   case 'e':
18212     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18213       if ((C->getSExtValue() >= -0x80000000LL) &&
18214           (C->getSExtValue() <= 0x7fffffffLL))
18215         weight = CW_Constant;
18216     }
18217     break;
18218   case 'Z':
18219     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18220       if (C->getZExtValue() <= 0xffffffff)
18221         weight = CW_Constant;
18222     }
18223     break;
18224   }
18225   return weight;
18226 }
18227
18228 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18229 /// with another that has more specific requirements based on the type of the
18230 /// corresponding operand.
18231 const char *X86TargetLowering::
18232 LowerXConstraint(EVT ConstraintVT) const {
18233   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18234   // 'f' like normal targets.
18235   if (ConstraintVT.isFloatingPoint()) {
18236     if (Subtarget->hasSSE2())
18237       return "Y";
18238     if (Subtarget->hasSSE1())
18239       return "x";
18240   }
18241
18242   return TargetLowering::LowerXConstraint(ConstraintVT);
18243 }
18244
18245 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18246 /// vector.  If it is invalid, don't add anything to Ops.
18247 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18248                                                      std::string &Constraint,
18249                                                      std::vector<SDValue>&Ops,
18250                                                      SelectionDAG &DAG) const {
18251   SDValue Result(0, 0);
18252
18253   // Only support length 1 constraints for now.
18254   if (Constraint.length() > 1) return;
18255
18256   char ConstraintLetter = Constraint[0];
18257   switch (ConstraintLetter) {
18258   default: break;
18259   case 'I':
18260     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18261       if (C->getZExtValue() <= 31) {
18262         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18263         break;
18264       }
18265     }
18266     return;
18267   case 'J':
18268     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18269       if (C->getZExtValue() <= 63) {
18270         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18271         break;
18272       }
18273     }
18274     return;
18275   case 'K':
18276     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18277       if (isInt<8>(C->getSExtValue())) {
18278         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18279         break;
18280       }
18281     }
18282     return;
18283   case 'N':
18284     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18285       if (C->getZExtValue() <= 255) {
18286         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18287         break;
18288       }
18289     }
18290     return;
18291   case 'e': {
18292     // 32-bit signed value
18293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18294       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18295                                            C->getSExtValue())) {
18296         // Widen to 64 bits here to get it sign extended.
18297         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18298         break;
18299       }
18300     // FIXME gcc accepts some relocatable values here too, but only in certain
18301     // memory models; it's complicated.
18302     }
18303     return;
18304   }
18305   case 'Z': {
18306     // 32-bit unsigned value
18307     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18308       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18309                                            C->getZExtValue())) {
18310         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18311         break;
18312       }
18313     }
18314     // FIXME gcc accepts some relocatable values here too, but only in certain
18315     // memory models; it's complicated.
18316     return;
18317   }
18318   case 'i': {
18319     // Literal immediates are always ok.
18320     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18321       // Widen to 64 bits here to get it sign extended.
18322       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18323       break;
18324     }
18325
18326     // In any sort of PIC mode addresses need to be computed at runtime by
18327     // adding in a register or some sort of table lookup.  These can't
18328     // be used as immediates.
18329     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18330       return;
18331
18332     // If we are in non-pic codegen mode, we allow the address of a global (with
18333     // an optional displacement) to be used with 'i'.
18334     GlobalAddressSDNode *GA = 0;
18335     int64_t Offset = 0;
18336
18337     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18338     while (1) {
18339       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18340         Offset += GA->getOffset();
18341         break;
18342       } else if (Op.getOpcode() == ISD::ADD) {
18343         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18344           Offset += C->getZExtValue();
18345           Op = Op.getOperand(0);
18346           continue;
18347         }
18348       } else if (Op.getOpcode() == ISD::SUB) {
18349         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18350           Offset += -C->getZExtValue();
18351           Op = Op.getOperand(0);
18352           continue;
18353         }
18354       }
18355
18356       // Otherwise, this isn't something we can handle, reject it.
18357       return;
18358     }
18359
18360     const GlobalValue *GV = GA->getGlobal();
18361     // If we require an extra load to get this address, as in PIC mode, we
18362     // can't accept it.
18363     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18364                                                         getTargetMachine())))
18365       return;
18366
18367     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18368                                         GA->getValueType(0), Offset);
18369     break;
18370   }
18371   }
18372
18373   if (Result.getNode()) {
18374     Ops.push_back(Result);
18375     return;
18376   }
18377   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18378 }
18379
18380 std::pair<unsigned, const TargetRegisterClass*>
18381 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18382                                                 EVT VT) const {
18383   // First, see if this is a constraint that directly corresponds to an LLVM
18384   // register class.
18385   if (Constraint.size() == 1) {
18386     // GCC Constraint Letters
18387     switch (Constraint[0]) {
18388     default: break;
18389       // TODO: Slight differences here in allocation order and leaving
18390       // RIP in the class. Do they matter any more here than they do
18391       // in the normal allocation?
18392     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18393       if (Subtarget->is64Bit()) {
18394         if (VT == MVT::i32 || VT == MVT::f32)
18395           return std::make_pair(0U, &X86::GR32RegClass);
18396         if (VT == MVT::i16)
18397           return std::make_pair(0U, &X86::GR16RegClass);
18398         if (VT == MVT::i8 || VT == MVT::i1)
18399           return std::make_pair(0U, &X86::GR8RegClass);
18400         if (VT == MVT::i64 || VT == MVT::f64)
18401           return std::make_pair(0U, &X86::GR64RegClass);
18402         break;
18403       }
18404       // 32-bit fallthrough
18405     case 'Q':   // Q_REGS
18406       if (VT == MVT::i32 || VT == MVT::f32)
18407         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18408       if (VT == MVT::i16)
18409         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18410       if (VT == MVT::i8 || VT == MVT::i1)
18411         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18412       if (VT == MVT::i64)
18413         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18414       break;
18415     case 'r':   // GENERAL_REGS
18416     case 'l':   // INDEX_REGS
18417       if (VT == MVT::i8 || VT == MVT::i1)
18418         return std::make_pair(0U, &X86::GR8RegClass);
18419       if (VT == MVT::i16)
18420         return std::make_pair(0U, &X86::GR16RegClass);
18421       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18422         return std::make_pair(0U, &X86::GR32RegClass);
18423       return std::make_pair(0U, &X86::GR64RegClass);
18424     case 'R':   // LEGACY_REGS
18425       if (VT == MVT::i8 || VT == MVT::i1)
18426         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18427       if (VT == MVT::i16)
18428         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18429       if (VT == MVT::i32 || !Subtarget->is64Bit())
18430         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18431       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18432     case 'f':  // FP Stack registers.
18433       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18434       // value to the correct fpstack register class.
18435       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18436         return std::make_pair(0U, &X86::RFP32RegClass);
18437       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18438         return std::make_pair(0U, &X86::RFP64RegClass);
18439       return std::make_pair(0U, &X86::RFP80RegClass);
18440     case 'y':   // MMX_REGS if MMX allowed.
18441       if (!Subtarget->hasMMX()) break;
18442       return std::make_pair(0U, &X86::VR64RegClass);
18443     case 'Y':   // SSE_REGS if SSE2 allowed
18444       if (!Subtarget->hasSSE2()) break;
18445       // FALL THROUGH.
18446     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18447       if (!Subtarget->hasSSE1()) break;
18448
18449       switch (VT.getSimpleVT().SimpleTy) {
18450       default: break;
18451       // Scalar SSE types.
18452       case MVT::f32:
18453       case MVT::i32:
18454         return std::make_pair(0U, &X86::FR32RegClass);
18455       case MVT::f64:
18456       case MVT::i64:
18457         return std::make_pair(0U, &X86::FR64RegClass);
18458       // Vector types.
18459       case MVT::v16i8:
18460       case MVT::v8i16:
18461       case MVT::v4i32:
18462       case MVT::v2i64:
18463       case MVT::v4f32:
18464       case MVT::v2f64:
18465         return std::make_pair(0U, &X86::VR128RegClass);
18466       // AVX types.
18467       case MVT::v32i8:
18468       case MVT::v16i16:
18469       case MVT::v8i32:
18470       case MVT::v4i64:
18471       case MVT::v8f32:
18472       case MVT::v4f64:
18473         return std::make_pair(0U, &X86::VR256RegClass);
18474       }
18475       break;
18476     }
18477   }
18478
18479   // Use the default implementation in TargetLowering to convert the register
18480   // constraint into a member of a register class.
18481   std::pair<unsigned, const TargetRegisterClass*> Res;
18482   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18483
18484   // Not found as a standard register?
18485   if (Res.second == 0) {
18486     // Map st(0) -> st(7) -> ST0
18487     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18488         tolower(Constraint[1]) == 's' &&
18489         tolower(Constraint[2]) == 't' &&
18490         Constraint[3] == '(' &&
18491         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18492         Constraint[5] == ')' &&
18493         Constraint[6] == '}') {
18494
18495       Res.first = X86::ST0+Constraint[4]-'0';
18496       Res.second = &X86::RFP80RegClass;
18497       return Res;
18498     }
18499
18500     // GCC allows "st(0)" to be called just plain "st".
18501     if (StringRef("{st}").equals_lower(Constraint)) {
18502       Res.first = X86::ST0;
18503       Res.second = &X86::RFP80RegClass;
18504       return Res;
18505     }
18506
18507     // flags -> EFLAGS
18508     if (StringRef("{flags}").equals_lower(Constraint)) {
18509       Res.first = X86::EFLAGS;
18510       Res.second = &X86::CCRRegClass;
18511       return Res;
18512     }
18513
18514     // 'A' means EAX + EDX.
18515     if (Constraint == "A") {
18516       Res.first = X86::EAX;
18517       Res.second = &X86::GR32_ADRegClass;
18518       return Res;
18519     }
18520     return Res;
18521   }
18522
18523   // Otherwise, check to see if this is a register class of the wrong value
18524   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18525   // turn into {ax},{dx}.
18526   if (Res.second->hasType(VT))
18527     return Res;   // Correct type already, nothing to do.
18528
18529   // All of the single-register GCC register classes map their values onto
18530   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18531   // really want an 8-bit or 32-bit register, map to the appropriate register
18532   // class and return the appropriate register.
18533   if (Res.second == &X86::GR16RegClass) {
18534     if (VT == MVT::i8 || VT == MVT::i1) {
18535       unsigned DestReg = 0;
18536       switch (Res.first) {
18537       default: break;
18538       case X86::AX: DestReg = X86::AL; break;
18539       case X86::DX: DestReg = X86::DL; break;
18540       case X86::CX: DestReg = X86::CL; break;
18541       case X86::BX: DestReg = X86::BL; break;
18542       }
18543       if (DestReg) {
18544         Res.first = DestReg;
18545         Res.second = &X86::GR8RegClass;
18546       }
18547     } else if (VT == MVT::i32 || VT == MVT::f32) {
18548       unsigned DestReg = 0;
18549       switch (Res.first) {
18550       default: break;
18551       case X86::AX: DestReg = X86::EAX; break;
18552       case X86::DX: DestReg = X86::EDX; break;
18553       case X86::CX: DestReg = X86::ECX; break;
18554       case X86::BX: DestReg = X86::EBX; break;
18555       case X86::SI: DestReg = X86::ESI; break;
18556       case X86::DI: DestReg = X86::EDI; break;
18557       case X86::BP: DestReg = X86::EBP; break;
18558       case X86::SP: DestReg = X86::ESP; break;
18559       }
18560       if (DestReg) {
18561         Res.first = DestReg;
18562         Res.second = &X86::GR32RegClass;
18563       }
18564     } else if (VT == MVT::i64 || VT == MVT::f64) {
18565       unsigned DestReg = 0;
18566       switch (Res.first) {
18567       default: break;
18568       case X86::AX: DestReg = X86::RAX; break;
18569       case X86::DX: DestReg = X86::RDX; break;
18570       case X86::CX: DestReg = X86::RCX; break;
18571       case X86::BX: DestReg = X86::RBX; break;
18572       case X86::SI: DestReg = X86::RSI; break;
18573       case X86::DI: DestReg = X86::RDI; break;
18574       case X86::BP: DestReg = X86::RBP; break;
18575       case X86::SP: DestReg = X86::RSP; break;
18576       }
18577       if (DestReg) {
18578         Res.first = DestReg;
18579         Res.second = &X86::GR64RegClass;
18580       }
18581     }
18582   } else if (Res.second == &X86::FR32RegClass ||
18583              Res.second == &X86::FR64RegClass ||
18584              Res.second == &X86::VR128RegClass) {
18585     // Handle references to XMM physical registers that got mapped into the
18586     // wrong class.  This can happen with constraints like {xmm0} where the
18587     // target independent register mapper will just pick the first match it can
18588     // find, ignoring the required type.
18589
18590     if (VT == MVT::f32 || VT == MVT::i32)
18591       Res.second = &X86::FR32RegClass;
18592     else if (VT == MVT::f64 || VT == MVT::i64)
18593       Res.second = &X86::FR64RegClass;
18594     else if (X86::VR128RegClass.hasType(VT))
18595       Res.second = &X86::VR128RegClass;
18596     else if (X86::VR256RegClass.hasType(VT))
18597       Res.second = &X86::VR256RegClass;
18598   }
18599
18600   return Res;
18601 }