Replace EVT with MVT in isHorizontalBinOp as it is only called with legal types.
[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, SDLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62                                 SelectionDAG &DAG, SDLoc dl,
63                                 unsigned vectorWidth) {
64   assert((vectorWidth == 128 || vectorWidth == 256) &&
65          "Unsupported vector width");
66   EVT VT = Vec.getValueType();
67   EVT ElVT = VT.getVectorElementType();
68   unsigned Factor = VT.getSizeInBits()/vectorWidth;
69   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70                                   VT.getVectorNumElements()/Factor);
71
72   // Extract from UNDEF is UNDEF.
73   if (Vec.getOpcode() == ISD::UNDEF)
74     return DAG.getUNDEF(ResultVT);
75
76   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
77   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
78
79   // This is the index of the first element of the vectorWidth-bit chunk
80   // we want.
81   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
82                                * ElemsPerChunk);
83
84   // If the input is a buildvector just emit a smaller one.
85   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
88
89   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
91                                VecIdx);
92
93   return Result;
94   
95 }
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103                                    SelectionDAG &DAG, SDLoc dl) {
104   assert((Vec.getValueType().is256BitVector() ||
105           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
107 }
108
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111                                    SelectionDAG &DAG, SDLoc dl) {
112   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
114 }
115
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117                                unsigned IdxVal, SelectionDAG &DAG,
118                                SDLoc dl, unsigned vectorWidth) {
119   assert((vectorWidth == 128 || vectorWidth == 256) &&
120          "Unsupported vector width");
121   // Inserting UNDEF is Result
122   if (Vec.getOpcode() == ISD::UNDEF)
123     return Result;
124   EVT VT = Vec.getValueType();
125   EVT ElVT = VT.getVectorElementType();
126   EVT ResultVT = Result.getValueType();
127
128   // Insert the relevant vectorWidth bits.
129   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
130
131   // This is the index of the first element of the vectorWidth-bit chunk
132   // we want.
133   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
134                                * ElemsPerChunk);
135
136   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
138                      VecIdx);
139 }
140 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference.  Idx is an index in the 128 bits
144 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147                                   unsigned IdxVal, SelectionDAG &DAG,
148                                   SDLoc dl) {
149   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
151 }
152
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154                                   unsigned IdxVal, SelectionDAG &DAG,
155                                   SDLoc dl) {
156   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
158 }
159
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165                                    unsigned NumElems, SelectionDAG &DAG,
166                                    SDLoc dl) {
167   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
169 }
170
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172                                    unsigned NumElems, SelectionDAG &DAG,
173                                    SDLoc dl) {
174   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
176 }
177
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180   bool is64Bit = Subtarget->is64Bit();
181
182   if (Subtarget->isTargetEnvMacho()) {
183     if (is64Bit)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (Subtarget->isTargetLinux())
189     return new X86LinuxTargetObjectFile();
190   if (Subtarget->isTargetELF())
191     return new TargetLoweringObjectFileELF();
192   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
193     return new TargetLoweringObjectFileCOFF();
194   llvm_unreachable("unknown subtarget type");
195 }
196
197 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
198   : TargetLowering(TM, createTLOF(TM)) {
199   Subtarget = &TM.getSubtarget<X86Subtarget>();
200   X86ScalarSSEf64 = Subtarget->hasSSE2();
201   X86ScalarSSEf32 = Subtarget->hasSSE1();
202   TD = getDataLayout();
203
204   resetOperationActions();
205 }
206
207 void X86TargetLowering::resetOperationActions() {
208   const TargetMachine &TM = getTargetMachine();
209   static bool FirstTimeThrough = true;
210
211   // If none of the target options have changed, then we don't need to reset the
212   // operation actions.
213   if (!FirstTimeThrough && TO == TM.Options) return;
214
215   if (!FirstTimeThrough) {
216     // Reinitialize the actions.
217     initActions();
218     FirstTimeThrough = false;
219   }
220
221   TO = TM.Options;
222
223   // Set up the TargetLowering object.
224   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
225
226   // X86 is weird, it always uses i8 for shift amounts and setcc results.
227   setBooleanContents(ZeroOrOneBooleanContent);
228   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
229   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
230
231   // For 64-bit since we have so many registers use the ILP scheduler, for
232   // 32-bit code use the register pressure specific scheduling.
233   // For Atom, always use ILP scheduling.
234   if (Subtarget->isAtom())
235     setSchedulingPreference(Sched::ILP);
236   else if (Subtarget->is64Bit())
237     setSchedulingPreference(Sched::ILP);
238   else
239     setSchedulingPreference(Sched::RegPressure);
240   const X86RegisterInfo *RegInfo =
241     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
242   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
243
244   // Bypass expensive divides on Atom when compiling with O2
245   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
246     addBypassSlowDiv(32, 8);
247     if (Subtarget->is64Bit())
248       addBypassSlowDiv(64, 16);
249   }
250
251   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
252     // Setup Windows compiler runtime calls.
253     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
254     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
255     setLibcallName(RTLIB::SREM_I64, "_allrem");
256     setLibcallName(RTLIB::UREM_I64, "_aullrem");
257     setLibcallName(RTLIB::MUL_I64, "_allmul");
258     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
259     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
260     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
263
264     // The _ftol2 runtime function has an unusual calling conv, which
265     // is modeled by a special pseudo-instruction.
266     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
267     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
268     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
269     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
270   }
271
272   if (Subtarget->isTargetDarwin()) {
273     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
274     setUseUnderscoreSetJmp(false);
275     setUseUnderscoreLongJmp(false);
276   } else if (Subtarget->isTargetMingw()) {
277     // MS runtime is weird: it exports _setjmp, but longjmp!
278     setUseUnderscoreSetJmp(true);
279     setUseUnderscoreLongJmp(false);
280   } else {
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(true);
283   }
284
285   // Set up the register classes.
286   addRegisterClass(MVT::i8, &X86::GR8RegClass);
287   addRegisterClass(MVT::i16, &X86::GR16RegClass);
288   addRegisterClass(MVT::i32, &X86::GR32RegClass);
289   if (Subtarget->is64Bit())
290     addRegisterClass(MVT::i64, &X86::GR64RegClass);
291
292   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
293
294   // We don't accept any truncstore of integer registers.
295   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
296   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
297   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
298   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
301
302   // SETOEQ and SETUNE require checking two conditions.
303   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
304   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
305   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
306   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
309
310   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
311   // operation.
312   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
313   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
315
316   if (Subtarget->is64Bit()) {
317     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
318     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
319   } else if (!TM.Options.UseSoftFloat) {
320     // We have an algorithm for SSE2->double, and we turn this into a
321     // 64-bit FILD followed by conditional FADD for other targets.
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
323     // We have an algorithm for SSE2, and we turn this into a 64-bit
324     // FILD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
326   }
327
328   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
329   // this operation.
330   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
331   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
332
333   if (!TM.Options.UseSoftFloat) {
334     // SSE has no i16 to fp conversion, only i32
335     if (X86ScalarSSEf32) {
336       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
337       // f32 and f64 cases are Legal, f80 case is not
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
339     } else {
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     }
343   } else {
344     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
345     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
346   }
347
348   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
349   // are Legal, f80 is custom lowered.
350   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
351   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
352
353   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
354   // this operation.
355   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
356   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
357
358   if (X86ScalarSSEf32) {
359     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
360     // f32 and f64 cases are Legal, f80 case is not
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
362   } else {
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   }
366
367   // Handle FP_TO_UINT by promoting the destination to a larger signed
368   // conversion.
369   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
370   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
372
373   if (Subtarget->is64Bit()) {
374     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
375     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
376   } else if (!TM.Options.UseSoftFloat) {
377     // Since AVX is a superset of SSE3, only check for SSE here.
378     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
379       // Expand FP_TO_UINT into a select.
380       // FIXME: We would like to use a Custom expander here eventually to do
381       // the optimal thing for SSE vs. the default expansion in the legalizer.
382       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
383     else
384       // With SSE3 we can use fisttpll to convert to a signed i64; without
385       // SSE, we're stuck with a fistpll.
386       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
387   }
388
389   if (isTargetFTOL()) {
390     // Use the _ftol2 runtime function, which has a pseudo-instruction
391     // to handle its weird calling convention.
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
393   }
394
395   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
396   if (!X86ScalarSSEf64) {
397     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
398     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
399     if (Subtarget->is64Bit()) {
400       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
401       // Without SSE, i64->f64 goes through memory.
402       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
403     }
404   }
405
406   // Scalar integer divide and remainder are lowered to use operations that
407   // produce two results, to match the available instructions. This exposes
408   // the two-result form to trivial CSE, which is able to combine x/y and x%y
409   // into a single instruction.
410   //
411   // Scalar integer multiply-high is also lowered to use two-result
412   // operations, to match the available instructions. However, plain multiply
413   // (low) operations are left as Legal, as there are single-result
414   // instructions for this in x86. Using the two-result multiply instructions
415   // when both high and low results are needed must be arranged by dagcombine.
416   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
417     MVT VT = IntVTs[i];
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::SDIV, VT, Expand);
421     setOperationAction(ISD::UDIV, VT, Expand);
422     setOperationAction(ISD::SREM, VT, Expand);
423     setOperationAction(ISD::UREM, VT, Expand);
424
425     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
426     setOperationAction(ISD::ADDC, VT, Custom);
427     setOperationAction(ISD::ADDE, VT, Custom);
428     setOperationAction(ISD::SUBC, VT, Custom);
429     setOperationAction(ISD::SUBE, VT, Custom);
430   }
431
432   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
433   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
434   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
435   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
436   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
438   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
441   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
442   if (Subtarget->is64Bit())
443     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
444   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
445   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
447   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
448   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
449   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
451   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
452
453   // Promote the i8 variants and force them on up to i32 which has a shorter
454   // encoding.
455   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
456   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
457   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
459   if (Subtarget->hasBMI()) {
460     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
461     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
462     if (Subtarget->is64Bit())
463       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
464   } else {
465     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
466     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
467     if (Subtarget->is64Bit())
468       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
469   }
470
471   if (Subtarget->hasLZCNT()) {
472     // When promoting the i8 variants, force them to i32 for a shorter
473     // encoding.
474     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
475     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
476     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
480     if (Subtarget->is64Bit())
481       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
482   } else {
483     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
484     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
485     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
489     if (Subtarget->is64Bit()) {
490       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
491       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
492     }
493   }
494
495   if (Subtarget->hasPOPCNT()) {
496     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
497   } else {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
499     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
500     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
501     if (Subtarget->is64Bit())
502       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
503   }
504
505   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
506   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
507
508   // These should be promoted to a larger select which is supported.
509   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
510   // X86 wants to expand cmov itself.
511   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
512   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
513   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
514   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
516   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
517   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
518   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
519   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
520   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
523   if (Subtarget->is64Bit()) {
524     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
525     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
526   }
527   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
528   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
529   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
530   // support continuation, user-level threading, and etc.. As a result, no
531   // other SjLj exception interfaces are implemented and please don't build
532   // your own exception handling based on them.
533   // LLVM/Clang supports zero-cost DWARF exception handling.
534   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
535   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
536
537   // Darwin ABI issue.
538   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
539   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
540   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
541   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
542   if (Subtarget->is64Bit())
543     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
544   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
545   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
546   if (Subtarget->is64Bit()) {
547     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
548     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
549     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
550     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
551     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
552   }
553   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
554   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
555   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
556   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
557   if (Subtarget->is64Bit()) {
558     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
559     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
560     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
561   }
562
563   if (Subtarget->hasSSE1())
564     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
565
566   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
567
568   // Expand certain atomics
569   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
570     MVT VT = IntVTs[i];
571     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
572     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
573     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
574   }
575
576   if (!Subtarget->is64Bit()) {
577     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
578     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
589   }
590
591   if (Subtarget->hasCmpxchg16b()) {
592     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
593   }
594
595   // FIXME - use subtarget debug flags
596   if (!Subtarget->isTargetDarwin() &&
597       !Subtarget->isTargetELF() &&
598       !Subtarget->isTargetCygMing()) {
599     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
600   }
601
602   if (Subtarget->is64Bit()) {
603     setExceptionPointerRegister(X86::RAX);
604     setExceptionSelectorRegister(X86::RDX);
605   } else {
606     setExceptionPointerRegister(X86::EAX);
607     setExceptionSelectorRegister(X86::EDX);
608   }
609   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
610   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
611
612   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
613   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
614
615   setOperationAction(ISD::TRAP, MVT::Other, Legal);
616   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
617
618   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
619   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
620   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
621   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
622     // TargetInfo::X86_64ABIBuiltinVaList
623     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
624     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
625   } else {
626     // TargetInfo::CharPtrBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
629   }
630
631   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
632   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
633
634   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
635     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
636                        MVT::i64 : MVT::i32, Custom);
637   else if (TM.Options.EnableSegmentedStacks)
638     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639                        MVT::i64 : MVT::i32, Custom);
640   else
641     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642                        MVT::i64 : MVT::i32, Expand);
643
644   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645     // f32 and f64 use SSE.
646     // Set up the FP register classes.
647     addRegisterClass(MVT::f32, &X86::FR32RegClass);
648     addRegisterClass(MVT::f64, &X86::FR64RegClass);
649
650     // Use ANDPD to simulate FABS.
651     setOperationAction(ISD::FABS , MVT::f64, Custom);
652     setOperationAction(ISD::FABS , MVT::f32, Custom);
653
654     // Use XORP to simulate FNEG.
655     setOperationAction(ISD::FNEG , MVT::f64, Custom);
656     setOperationAction(ISD::FNEG , MVT::f32, Custom);
657
658     // Use ANDPD and ORPD to simulate FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661
662     // Lower this to FGETSIGNx86 plus an AND.
663     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665
666     // We don't support sin/cos/fmod
667     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Expand FP immediates into loads from the stack, except for the special
675     // cases we handle.
676     addLegalFPImmediate(APFloat(+0.0)); // xorpd
677     addLegalFPImmediate(APFloat(+0.0f)); // xorps
678   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679     // Use SSE for f32, x87 for f64.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f32, &X86::FR32RegClass);
682     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683
684     // Use ANDPS to simulate FABS.
685     setOperationAction(ISD::FABS , MVT::f32, Custom);
686
687     // Use XORP to simulate FNEG.
688     setOperationAction(ISD::FNEG , MVT::f32, Custom);
689
690     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
691
692     // Use ANDPS and ORPS to simulate FCOPYSIGN.
693     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695
696     // We don't support sin/cos/fmod
697     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
698     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700
701     // Special cases we handle for FP constants.
702     addLegalFPImmediate(APFloat(+0.0f)); // xorps
703     addLegalFPImmediate(APFloat(+0.0)); // FLD0
704     addLegalFPImmediate(APFloat(+1.0)); // FLD1
705     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
711       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712     }
713   } else if (!TM.Options.UseSoftFloat) {
714     // f32 and f64 in x87.
715     // Set up the FP register classes.
716     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718
719     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
720     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723
724     if (!TM.Options.UnsafeFPMath) {
725       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
726       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731     }
732     addLegalFPImmediate(APFloat(+0.0)); // FLD0
733     addLegalFPImmediate(APFloat(+1.0)); // FLD1
734     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740   }
741
742   // We don't support FMA.
743   setOperationAction(ISD::FMA, MVT::f64, Expand);
744   setOperationAction(ISD::FMA, MVT::f32, Expand);
745
746   // Long double always uses X87.
747   if (!TM.Options.UseSoftFloat) {
748     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
750     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751     {
752       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753       addLegalFPImmediate(TmpFlt);  // FLD0
754       TmpFlt.changeSign();
755       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
756
757       bool ignored;
758       APFloat TmpFlt2(+1.0);
759       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760                       &ignored);
761       addLegalFPImmediate(TmpFlt2);  // FLD1
762       TmpFlt2.changeSign();
763       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
764     }
765
766     if (!TM.Options.UnsafeFPMath) {
767       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
768       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
769       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770     }
771
772     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
774     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
776     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777     setOperationAction(ISD::FMA, MVT::f80, Expand);
778   }
779
780   // Always use a library call for pow.
781   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
784
785   setOperationAction(ISD::FLOG, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790
791   // First set operation action for all vector types to either promote
792   // (for widening) or expand (for scalarization). Then we will selectively
793   // turn on ones that can be effectively codegen'd.
794   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796     MVT VT = (MVT::SimpleValueType)i;
797     setOperationAction(ISD::ADD , VT, Expand);
798     setOperationAction(ISD::SUB , VT, Expand);
799     setOperationAction(ISD::FADD, VT, Expand);
800     setOperationAction(ISD::FNEG, VT, Expand);
801     setOperationAction(ISD::FSUB, VT, Expand);
802     setOperationAction(ISD::MUL , VT, Expand);
803     setOperationAction(ISD::FMUL, VT, Expand);
804     setOperationAction(ISD::SDIV, VT, Expand);
805     setOperationAction(ISD::UDIV, VT, Expand);
806     setOperationAction(ISD::FDIV, VT, Expand);
807     setOperationAction(ISD::SREM, VT, Expand);
808     setOperationAction(ISD::UREM, VT, Expand);
809     setOperationAction(ISD::LOAD, VT, Expand);
810     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::FABS, VT, Expand);
816     setOperationAction(ISD::FSIN, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FCOS, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FREM, VT, Expand);
821     setOperationAction(ISD::FMA,  VT, Expand);
822     setOperationAction(ISD::FPOWI, VT, Expand);
823     setOperationAction(ISD::FSQRT, VT, Expand);
824     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825     setOperationAction(ISD::FFLOOR, VT, Expand);
826     setOperationAction(ISD::FCEIL, VT, Expand);
827     setOperationAction(ISD::FTRUNC, VT, Expand);
828     setOperationAction(ISD::FRINT, VT, Expand);
829     setOperationAction(ISD::FNEARBYINT, VT, Expand);
830     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
832     setOperationAction(ISD::SDIVREM, VT, Expand);
833     setOperationAction(ISD::UDIVREM, VT, Expand);
834     setOperationAction(ISD::FPOW, VT, Expand);
835     setOperationAction(ISD::CTPOP, VT, Expand);
836     setOperationAction(ISD::CTTZ, VT, Expand);
837     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::CTLZ, VT, Expand);
839     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::SHL, VT, Expand);
841     setOperationAction(ISD::SRA, VT, Expand);
842     setOperationAction(ISD::SRL, VT, Expand);
843     setOperationAction(ISD::ROTL, VT, Expand);
844     setOperationAction(ISD::ROTR, VT, Expand);
845     setOperationAction(ISD::BSWAP, VT, Expand);
846     setOperationAction(ISD::SETCC, VT, Expand);
847     setOperationAction(ISD::FLOG, VT, Expand);
848     setOperationAction(ISD::FLOG2, VT, Expand);
849     setOperationAction(ISD::FLOG10, VT, Expand);
850     setOperationAction(ISD::FEXP, VT, Expand);
851     setOperationAction(ISD::FEXP2, VT, Expand);
852     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857     setOperationAction(ISD::TRUNCATE, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861     setOperationAction(ISD::VSELECT, VT, Expand);
862     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864       setTruncStoreAction(VT,
865                           (MVT::SimpleValueType)InnerVT, Expand);
866     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869   }
870
871   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872   // with -msoft-float, disable use of MMX as well.
873   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875     // No operations on x86mmx supported, everything uses intrinsics.
876   }
877
878   // MMX-sized vectors (other than x86mmx) are expected to be expanded
879   // into smaller operations.
880   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
881   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
884   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
885   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
886   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
887   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
888   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
889   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
890   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
891   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
892   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
893   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
894   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
895   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
900   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
902   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
909
910   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912
913     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
919     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
920     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
921     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
922     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
923     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
925   }
926
927   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929
930     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931     // registers cannot be used even for integer operations.
932     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936
937     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
938     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
939     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
940     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
941     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
942     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
943     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
944     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
945     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
946     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
947     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
948     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
953     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
954     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
955
956     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
960
961     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
966
967     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
968     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
969       MVT VT = (MVT::SimpleValueType)i;
970       // Do not attempt to custom lower non-power-of-2 vectors
971       if (!isPowerOf2_32(VT.getVectorNumElements()))
972         continue;
973       // Do not attempt to custom lower non-128-bit vectors
974       if (!VT.is128BitVector())
975         continue;
976       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
977       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
978       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979     }
980
981     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
982     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
983     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
984     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
987
988     if (Subtarget->is64Bit()) {
989       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991     }
992
993     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
994     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
995       MVT VT = (MVT::SimpleValueType)i;
996
997       // Do not attempt to promote non-128-bit vectors
998       if (!VT.is128BitVector())
999         continue;
1000
1001       setOperationAction(ISD::AND,    VT, Promote);
1002       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1003       setOperationAction(ISD::OR,     VT, Promote);
1004       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1005       setOperationAction(ISD::XOR,    VT, Promote);
1006       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1007       setOperationAction(ISD::LOAD,   VT, Promote);
1008       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1009       setOperationAction(ISD::SELECT, VT, Promote);
1010       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1011     }
1012
1013     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1014
1015     // Custom lower v2i64 and v2f64 selects.
1016     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1017     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1018     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1019     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1020
1021     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1022     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1023
1024     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1025     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1026     // As there is no 64-bit GPR available, we need build a special custom
1027     // sequence to convert from v2i32 to v2f32.
1028     if (!Subtarget->is64Bit())
1029       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1030
1031     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1032     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1033
1034     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1035   }
1036
1037   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1038     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1039     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1040     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1041     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1042     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1043     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1044     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1045     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1046     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1047     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1048
1049     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1050     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1051     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1052     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1053     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1054     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1055     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1056     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1057     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1058     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1059
1060     // FIXME: Do we need to handle scalar-to-vector here?
1061     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1062
1063     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1068
1069     // i8 and i16 vectors are custom , because the source register and source
1070     // source memory operand types are not the same width.  f32 vectors are
1071     // custom since the immediate controlling the insert encodes additional
1072     // information.
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1077
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1082
1083     // FIXME: these should be Legal but thats only for the case where
1084     // the index is constant.  For now custom expand to deal with that.
1085     if (Subtarget->is64Bit()) {
1086       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1087       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1088     }
1089   }
1090
1091   if (Subtarget->hasSSE2()) {
1092     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1093     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1094
1095     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1096     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1097
1098     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1099     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1100
1101     // In the customized shift lowering, the legal cases in AVX2 will be
1102     // recognized.
1103     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1104     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1105
1106     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1107     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1108
1109     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1110
1111     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1112     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1113   }
1114
1115   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1116     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1117     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1118     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1122
1123     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1124     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1125     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1126
1127     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1132     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1133     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1135     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1137     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1138     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1139
1140     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1145     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1146     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1148     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1150     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1151     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1152
1153     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1154     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1155
1156     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1157
1158     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1160     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1161     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1162
1163     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1164     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1165     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1166
1167     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1168
1169     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1179
1180     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1182     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1183     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1184
1185     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1186     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1187     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1188
1189     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1191     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1192     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1193
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1200
1201     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1202       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1203       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1204       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1205       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1206       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1208     }
1209
1210     if (Subtarget->hasInt256()) {
1211       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1212       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1213       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1214       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1215
1216       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1217       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1218       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1219       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1220
1221       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1222       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1223       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1224       // Don't lower v32i8 because there is no 128-bit byte mul
1225
1226       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1227
1228       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1229     } else {
1230       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1231       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1232       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1233       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1234
1235       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1236       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1237       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1238       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1239
1240       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1241       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1242       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1243       // Don't lower v32i8 because there is no 128-bit byte mul
1244     }
1245
1246     // In the customized shift lowering, the legal cases in AVX2 will be
1247     // recognized.
1248     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1249     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1250
1251     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1255
1256     // Custom lower several nodes for 256-bit types.
1257     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1258              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1259       MVT VT = (MVT::SimpleValueType)i;
1260
1261       // Extract subvector is special because the value type
1262       // (result) is 128-bit but the source is 256-bit wide.
1263       if (VT.is128BitVector())
1264         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1265
1266       // Do not attempt to custom lower other non-256-bit vectors
1267       if (!VT.is256BitVector())
1268         continue;
1269
1270       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1271       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1272       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1273       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1275       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1276       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1277     }
1278
1279     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1280     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1281       MVT VT = (MVT::SimpleValueType)i;
1282
1283       // Do not attempt to promote non-256-bit vectors
1284       if (!VT.is256BitVector())
1285         continue;
1286
1287       setOperationAction(ISD::AND,    VT, Promote);
1288       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1289       setOperationAction(ISD::OR,     VT, Promote);
1290       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1291       setOperationAction(ISD::XOR,    VT, Promote);
1292       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1293       setOperationAction(ISD::LOAD,   VT, Promote);
1294       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1295       setOperationAction(ISD::SELECT, VT, Promote);
1296       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1297     }
1298   }
1299
1300   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1301     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1302     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1303     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1304     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1305
1306     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1307     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1308
1309     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1310     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1312     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1314     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1315
1316     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1317     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1321     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1322
1323     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1329     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1330     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1331     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1332
1333
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1338     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1340     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1341     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1342
1343     setOperationAction(ISD::TRUNCATE,           MVT::i1, Legal);
1344     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1345     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1346     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1347     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1348     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1349     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1350     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1351     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1352     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1353     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1354     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1355
1356     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1357     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1358     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1359     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1360     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1361
1362     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1363     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1364
1365     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1366
1367     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1368     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1370     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1371     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1372
1373     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1374     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1375
1376     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1377     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1380
1381     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1382     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1383
1384     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1385     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1386
1387     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1388     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1389
1390     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1392     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1393
1394     // Custom lower several nodes.
1395     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1396              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1397       MVT VT = (MVT::SimpleValueType)i;
1398
1399       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1400       // Extract subvector is special because the value type
1401       // (result) is 256/128-bit but the source is 512-bit wide.
1402       if (VT.is128BitVector() || VT.is256BitVector())
1403         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1404
1405       if (VT.getVectorElementType() == MVT::i1)
1406         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1407
1408       // Do not attempt to custom lower other non-512-bit vectors
1409       if (!VT.is512BitVector())
1410         continue;
1411
1412       if (VT != MVT::v8i64) {
1413         setOperationAction(ISD::XOR,   VT, Promote);
1414         AddPromotedToType (ISD::XOR,   VT, MVT::v8i64);
1415         setOperationAction(ISD::OR,    VT, Promote);
1416         AddPromotedToType (ISD::OR,    VT, MVT::v8i64);
1417         setOperationAction(ISD::AND,   VT, Promote);
1418         AddPromotedToType (ISD::AND,   VT, MVT::v8i64);
1419       }
1420       if ( EltSize >= 32) {
1421         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1422         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1423         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1424         setOperationAction(ISD::VSELECT,             VT, Legal);
1425         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1426         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1427         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1428       }
1429     }
1430     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1431       MVT VT = (MVT::SimpleValueType)i;
1432
1433       // Do not attempt to promote non-256-bit vectors
1434       if (!VT.is512BitVector())
1435         continue;
1436
1437       setOperationAction(ISD::LOAD,   VT, Promote);
1438       AddPromotedToType (ISD::LOAD,   VT, MVT::v8i64);
1439       setOperationAction(ISD::SELECT, VT, Promote);
1440       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1441     }
1442   }// has  AVX-512
1443
1444   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1445   // of this type with custom code.
1446   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1447            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1448     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1449                        Custom);
1450   }
1451
1452   // We want to custom lower some of our intrinsics.
1453   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1454   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1455
1456   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1457   // handle type legalization for these operations here.
1458   //
1459   // FIXME: We really should do custom legalization for addition and
1460   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1461   // than generic legalization for 64-bit multiplication-with-overflow, though.
1462   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1463     // Add/Sub/Mul with overflow operations are custom lowered.
1464     MVT VT = IntVTs[i];
1465     setOperationAction(ISD::SADDO, VT, Custom);
1466     setOperationAction(ISD::UADDO, VT, Custom);
1467     setOperationAction(ISD::SSUBO, VT, Custom);
1468     setOperationAction(ISD::USUBO, VT, Custom);
1469     setOperationAction(ISD::SMULO, VT, Custom);
1470     setOperationAction(ISD::UMULO, VT, Custom);
1471   }
1472
1473   // There are no 8-bit 3-address imul/mul instructions
1474   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1475   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1476
1477   if (!Subtarget->is64Bit()) {
1478     // These libcalls are not available in 32-bit.
1479     setLibcallName(RTLIB::SHL_I128, 0);
1480     setLibcallName(RTLIB::SRL_I128, 0);
1481     setLibcallName(RTLIB::SRA_I128, 0);
1482   }
1483
1484   // Combine sin / cos into one node or libcall if possible.
1485   if (Subtarget->hasSinCos()) {
1486     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1487     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1488     if (Subtarget->isTargetDarwin()) {
1489       // For MacOSX, we don't want to the normal expansion of a libcall to
1490       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1491       // traffic.
1492       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1493       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1494     }
1495   }
1496
1497   // We have target-specific dag combine patterns for the following nodes:
1498   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1499   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1500   setTargetDAGCombine(ISD::VSELECT);
1501   setTargetDAGCombine(ISD::SELECT);
1502   setTargetDAGCombine(ISD::SHL);
1503   setTargetDAGCombine(ISD::SRA);
1504   setTargetDAGCombine(ISD::SRL);
1505   setTargetDAGCombine(ISD::OR);
1506   setTargetDAGCombine(ISD::AND);
1507   setTargetDAGCombine(ISD::ADD);
1508   setTargetDAGCombine(ISD::FADD);
1509   setTargetDAGCombine(ISD::FSUB);
1510   setTargetDAGCombine(ISD::FMA);
1511   setTargetDAGCombine(ISD::SUB);
1512   setTargetDAGCombine(ISD::LOAD);
1513   setTargetDAGCombine(ISD::STORE);
1514   setTargetDAGCombine(ISD::ZERO_EXTEND);
1515   setTargetDAGCombine(ISD::ANY_EXTEND);
1516   setTargetDAGCombine(ISD::SIGN_EXTEND);
1517   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1518   setTargetDAGCombine(ISD::TRUNCATE);
1519   setTargetDAGCombine(ISD::SINT_TO_FP);
1520   setTargetDAGCombine(ISD::SETCC);
1521   if (Subtarget->is64Bit())
1522     setTargetDAGCombine(ISD::MUL);
1523   setTargetDAGCombine(ISD::XOR);
1524
1525   computeRegisterProperties();
1526
1527   // On Darwin, -Os means optimize for size without hurting performance,
1528   // do not reduce the limit.
1529   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1530   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1531   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1532   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1533   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1534   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1535   setPrefLoopAlignment(4); // 2^4 bytes.
1536
1537   // Predictable cmov don't hurt on atom because it's in-order.
1538   PredictableSelectIsExpensive = !Subtarget->isAtom();
1539
1540   setPrefFunctionAlignment(4); // 2^4 bytes.
1541 }
1542
1543 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1544   if (!VT.isVector()) return MVT::i8;
1545   return VT.changeVectorElementTypeToInteger();
1546 }
1547
1548 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1549 /// the desired ByVal argument alignment.
1550 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1551   if (MaxAlign == 16)
1552     return;
1553   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1554     if (VTy->getBitWidth() == 128)
1555       MaxAlign = 16;
1556   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1557     unsigned EltAlign = 0;
1558     getMaxByValAlign(ATy->getElementType(), EltAlign);
1559     if (EltAlign > MaxAlign)
1560       MaxAlign = EltAlign;
1561   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1562     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1563       unsigned EltAlign = 0;
1564       getMaxByValAlign(STy->getElementType(i), EltAlign);
1565       if (EltAlign > MaxAlign)
1566         MaxAlign = EltAlign;
1567       if (MaxAlign == 16)
1568         break;
1569     }
1570   }
1571 }
1572
1573 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1574 /// function arguments in the caller parameter area. For X86, aggregates
1575 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1576 /// are at 4-byte boundaries.
1577 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1578   if (Subtarget->is64Bit()) {
1579     // Max of 8 and alignment of type.
1580     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1581     if (TyAlign > 8)
1582       return TyAlign;
1583     return 8;
1584   }
1585
1586   unsigned Align = 4;
1587   if (Subtarget->hasSSE1())
1588     getMaxByValAlign(Ty, Align);
1589   return Align;
1590 }
1591
1592 /// getOptimalMemOpType - Returns the target specific optimal type for load
1593 /// and store operations as a result of memset, memcpy, and memmove
1594 /// lowering. If DstAlign is zero that means it's safe to destination
1595 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1596 /// means there isn't a need to check it against alignment requirement,
1597 /// probably because the source does not need to be loaded. If 'IsMemset' is
1598 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1599 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1600 /// source is constant so it does not need to be loaded.
1601 /// It returns EVT::Other if the type should be determined using generic
1602 /// target-independent logic.
1603 EVT
1604 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1605                                        unsigned DstAlign, unsigned SrcAlign,
1606                                        bool IsMemset, bool ZeroMemset,
1607                                        bool MemcpyStrSrc,
1608                                        MachineFunction &MF) const {
1609   const Function *F = MF.getFunction();
1610   if ((!IsMemset || ZeroMemset) &&
1611       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1612                                        Attribute::NoImplicitFloat)) {
1613     if (Size >= 16 &&
1614         (Subtarget->isUnalignedMemAccessFast() ||
1615          ((DstAlign == 0 || DstAlign >= 16) &&
1616           (SrcAlign == 0 || SrcAlign >= 16)))) {
1617       if (Size >= 32) {
1618         if (Subtarget->hasInt256())
1619           return MVT::v8i32;
1620         if (Subtarget->hasFp256())
1621           return MVT::v8f32;
1622       }
1623       if (Subtarget->hasSSE2())
1624         return MVT::v4i32;
1625       if (Subtarget->hasSSE1())
1626         return MVT::v4f32;
1627     } else if (!MemcpyStrSrc && Size >= 8 &&
1628                !Subtarget->is64Bit() &&
1629                Subtarget->hasSSE2()) {
1630       // Do not use f64 to lower memcpy if source is string constant. It's
1631       // better to use i32 to avoid the loads.
1632       return MVT::f64;
1633     }
1634   }
1635   if (Subtarget->is64Bit() && Size >= 8)
1636     return MVT::i64;
1637   return MVT::i32;
1638 }
1639
1640 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1641   if (VT == MVT::f32)
1642     return X86ScalarSSEf32;
1643   else if (VT == MVT::f64)
1644     return X86ScalarSSEf64;
1645   return true;
1646 }
1647
1648 bool
1649 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1650   if (Fast)
1651     *Fast = Subtarget->isUnalignedMemAccessFast();
1652   return true;
1653 }
1654
1655 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1656 /// current function.  The returned value is a member of the
1657 /// MachineJumpTableInfo::JTEntryKind enum.
1658 unsigned X86TargetLowering::getJumpTableEncoding() const {
1659   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1660   // symbol.
1661   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1662       Subtarget->isPICStyleGOT())
1663     return MachineJumpTableInfo::EK_Custom32;
1664
1665   // Otherwise, use the normal jump table encoding heuristics.
1666   return TargetLowering::getJumpTableEncoding();
1667 }
1668
1669 const MCExpr *
1670 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1671                                              const MachineBasicBlock *MBB,
1672                                              unsigned uid,MCContext &Ctx) const{
1673   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1674          Subtarget->isPICStyleGOT());
1675   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1676   // entries.
1677   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1678                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1679 }
1680
1681 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1682 /// jumptable.
1683 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1684                                                     SelectionDAG &DAG) const {
1685   if (!Subtarget->is64Bit())
1686     // This doesn't have SDLoc associated with it, but is not really the
1687     // same as a Register.
1688     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1689   return Table;
1690 }
1691
1692 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1693 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1694 /// MCExpr.
1695 const MCExpr *X86TargetLowering::
1696 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1697                              MCContext &Ctx) const {
1698   // X86-64 uses RIP relative addressing based on the jump table label.
1699   if (Subtarget->isPICStyleRIPRel())
1700     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1701
1702   // Otherwise, the reference is relative to the PIC base.
1703   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1704 }
1705
1706 // FIXME: Why this routine is here? Move to RegInfo!
1707 std::pair<const TargetRegisterClass*, uint8_t>
1708 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1709   const TargetRegisterClass *RRC = 0;
1710   uint8_t Cost = 1;
1711   switch (VT.SimpleTy) {
1712   default:
1713     return TargetLowering::findRepresentativeClass(VT);
1714   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1715     RRC = Subtarget->is64Bit() ?
1716       (const TargetRegisterClass*)&X86::GR64RegClass :
1717       (const TargetRegisterClass*)&X86::GR32RegClass;
1718     break;
1719   case MVT::x86mmx:
1720     RRC = &X86::VR64RegClass;
1721     break;
1722   case MVT::f32: case MVT::f64:
1723   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1724   case MVT::v4f32: case MVT::v2f64:
1725   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1726   case MVT::v4f64:
1727     RRC = &X86::VR128RegClass;
1728     break;
1729   }
1730   return std::make_pair(RRC, Cost);
1731 }
1732
1733 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1734                                                unsigned &Offset) const {
1735   if (!Subtarget->isTargetLinux())
1736     return false;
1737
1738   if (Subtarget->is64Bit()) {
1739     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1740     Offset = 0x28;
1741     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1742       AddressSpace = 256;
1743     else
1744       AddressSpace = 257;
1745   } else {
1746     // %gs:0x14 on i386
1747     Offset = 0x14;
1748     AddressSpace = 256;
1749   }
1750   return true;
1751 }
1752
1753 //===----------------------------------------------------------------------===//
1754 //               Return Value Calling Convention Implementation
1755 //===----------------------------------------------------------------------===//
1756
1757 #include "X86GenCallingConv.inc"
1758
1759 bool
1760 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1761                                   MachineFunction &MF, bool isVarArg,
1762                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1763                         LLVMContext &Context) const {
1764   SmallVector<CCValAssign, 16> RVLocs;
1765   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1766                  RVLocs, Context);
1767   return CCInfo.CheckReturn(Outs, RetCC_X86);
1768 }
1769
1770 SDValue
1771 X86TargetLowering::LowerReturn(SDValue Chain,
1772                                CallingConv::ID CallConv, bool isVarArg,
1773                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1774                                const SmallVectorImpl<SDValue> &OutVals,
1775                                SDLoc dl, SelectionDAG &DAG) const {
1776   MachineFunction &MF = DAG.getMachineFunction();
1777   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1778
1779   SmallVector<CCValAssign, 16> RVLocs;
1780   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1781                  RVLocs, *DAG.getContext());
1782   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1783
1784   SDValue Flag;
1785   SmallVector<SDValue, 6> RetOps;
1786   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1787   // Operand #1 = Bytes To Pop
1788   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1789                    MVT::i16));
1790
1791   // Copy the result values into the output registers.
1792   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1793     CCValAssign &VA = RVLocs[i];
1794     assert(VA.isRegLoc() && "Can only return in registers!");
1795     SDValue ValToCopy = OutVals[i];
1796     EVT ValVT = ValToCopy.getValueType();
1797
1798     // Promote values to the appropriate types
1799     if (VA.getLocInfo() == CCValAssign::SExt)
1800       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801     else if (VA.getLocInfo() == CCValAssign::ZExt)
1802       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1803     else if (VA.getLocInfo() == CCValAssign::AExt)
1804       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1805     else if (VA.getLocInfo() == CCValAssign::BCvt)
1806       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1807
1808     // If this is x86-64, and we disabled SSE, we can't return FP values,
1809     // or SSE or MMX vectors.
1810     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1811          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1812           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1813       report_fatal_error("SSE register return with SSE disabled");
1814     }
1815     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1816     // llvm-gcc has never done it right and no one has noticed, so this
1817     // should be OK for now.
1818     if (ValVT == MVT::f64 &&
1819         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1820       report_fatal_error("SSE2 register return with SSE2 disabled");
1821
1822     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1823     // the RET instruction and handled by the FP Stackifier.
1824     if (VA.getLocReg() == X86::ST0 ||
1825         VA.getLocReg() == X86::ST1) {
1826       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1827       // change the value to the FP stack register class.
1828       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1829         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1830       RetOps.push_back(ValToCopy);
1831       // Don't emit a copytoreg.
1832       continue;
1833     }
1834
1835     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1836     // which is returned in RAX / RDX.
1837     if (Subtarget->is64Bit()) {
1838       if (ValVT == MVT::x86mmx) {
1839         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1840           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1841           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1842                                   ValToCopy);
1843           // If we don't have SSE2 available, convert to v4f32 so the generated
1844           // register is legal.
1845           if (!Subtarget->hasSSE2())
1846             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1847         }
1848       }
1849     }
1850
1851     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1852     Flag = Chain.getValue(1);
1853     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1854   }
1855
1856   // The x86-64 ABIs require that for returning structs by value we copy
1857   // the sret argument into %rax/%eax (depending on ABI) for the return.
1858   // Win32 requires us to put the sret argument to %eax as well.
1859   // We saved the argument into a virtual register in the entry block,
1860   // so now we copy the value out and into %rax/%eax.
1861   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1862       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1863     MachineFunction &MF = DAG.getMachineFunction();
1864     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865     unsigned Reg = FuncInfo->getSRetReturnReg();
1866     assert(Reg &&
1867            "SRetReturnReg should have been set in LowerFormalArguments().");
1868     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1869
1870     unsigned RetValReg
1871         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1872           X86::RAX : X86::EAX;
1873     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1874     Flag = Chain.getValue(1);
1875
1876     // RAX/EAX now acts like a return value.
1877     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1878   }
1879
1880   RetOps[0] = Chain;  // Update chain.
1881
1882   // Add the flag if we have it.
1883   if (Flag.getNode())
1884     RetOps.push_back(Flag);
1885
1886   return DAG.getNode(X86ISD::RET_FLAG, dl,
1887                      MVT::Other, &RetOps[0], RetOps.size());
1888 }
1889
1890 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1891   if (N->getNumValues() != 1)
1892     return false;
1893   if (!N->hasNUsesOfValue(1, 0))
1894     return false;
1895
1896   SDValue TCChain = Chain;
1897   SDNode *Copy = *N->use_begin();
1898   if (Copy->getOpcode() == ISD::CopyToReg) {
1899     // If the copy has a glue operand, we conservatively assume it isn't safe to
1900     // perform a tail call.
1901     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1902       return false;
1903     TCChain = Copy->getOperand(0);
1904   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1905     return false;
1906
1907   bool HasRet = false;
1908   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1909        UI != UE; ++UI) {
1910     if (UI->getOpcode() != X86ISD::RET_FLAG)
1911       return false;
1912     HasRet = true;
1913   }
1914
1915   if (!HasRet)
1916     return false;
1917
1918   Chain = TCChain;
1919   return true;
1920 }
1921
1922 MVT
1923 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1924                                             ISD::NodeType ExtendKind) const {
1925   MVT ReturnMVT;
1926   // TODO: Is this also valid on 32-bit?
1927   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1928     ReturnMVT = MVT::i8;
1929   else
1930     ReturnMVT = MVT::i32;
1931
1932   MVT MinVT = getRegisterType(ReturnMVT);
1933   return VT.bitsLT(MinVT) ? MinVT : VT;
1934 }
1935
1936 /// LowerCallResult - Lower the result values of a call into the
1937 /// appropriate copies out of appropriate physical registers.
1938 ///
1939 SDValue
1940 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1941                                    CallingConv::ID CallConv, bool isVarArg,
1942                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1943                                    SDLoc dl, SelectionDAG &DAG,
1944                                    SmallVectorImpl<SDValue> &InVals) const {
1945
1946   // Assign locations to each value returned by this call.
1947   SmallVector<CCValAssign, 16> RVLocs;
1948   bool Is64Bit = Subtarget->is64Bit();
1949   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1950                  getTargetMachine(), RVLocs, *DAG.getContext());
1951   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1952
1953   // Copy all of the result registers out of their specified physreg.
1954   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1955     CCValAssign &VA = RVLocs[i];
1956     EVT CopyVT = VA.getValVT();
1957
1958     // If this is x86-64, and we disabled SSE, we can't return FP values
1959     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1960         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1961       report_fatal_error("SSE register return with SSE disabled");
1962     }
1963
1964     SDValue Val;
1965
1966     // If this is a call to a function that returns an fp value on the floating
1967     // point stack, we must guarantee the value is popped from the stack, so
1968     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1969     // if the return value is not used. We use the FpPOP_RETVAL instruction
1970     // instead.
1971     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1972       // If we prefer to use the value in xmm registers, copy it out as f80 and
1973       // use a truncate to move it from fp stack reg to xmm reg.
1974       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1975       SDValue Ops[] = { Chain, InFlag };
1976       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1977                                          MVT::Other, MVT::Glue, Ops), 1);
1978       Val = Chain.getValue(0);
1979
1980       // Round the f80 to the right size, which also moves it to the appropriate
1981       // xmm register.
1982       if (CopyVT != VA.getValVT())
1983         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1984                           // This truncation won't change the value.
1985                           DAG.getIntPtrConstant(1));
1986     } else {
1987       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1988                                  CopyVT, InFlag).getValue(1);
1989       Val = Chain.getValue(0);
1990     }
1991     InFlag = Chain.getValue(2);
1992     InVals.push_back(Val);
1993   }
1994
1995   return Chain;
1996 }
1997
1998 //===----------------------------------------------------------------------===//
1999 //                C & StdCall & Fast Calling Convention implementation
2000 //===----------------------------------------------------------------------===//
2001 //  StdCall calling convention seems to be standard for many Windows' API
2002 //  routines and around. It differs from C calling convention just a little:
2003 //  callee should clean up the stack, not caller. Symbols should be also
2004 //  decorated in some fancy way :) It doesn't support any vector arguments.
2005 //  For info on fast calling convention see Fast Calling Convention (tail call)
2006 //  implementation LowerX86_32FastCCCallTo.
2007
2008 /// CallIsStructReturn - Determines whether a call uses struct return
2009 /// semantics.
2010 enum StructReturnType {
2011   NotStructReturn,
2012   RegStructReturn,
2013   StackStructReturn
2014 };
2015 static StructReturnType
2016 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2017   if (Outs.empty())
2018     return NotStructReturn;
2019
2020   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2021   if (!Flags.isSRet())
2022     return NotStructReturn;
2023   if (Flags.isInReg())
2024     return RegStructReturn;
2025   return StackStructReturn;
2026 }
2027
2028 /// ArgsAreStructReturn - Determines whether a function uses struct
2029 /// return semantics.
2030 static StructReturnType
2031 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2032   if (Ins.empty())
2033     return NotStructReturn;
2034
2035   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2036   if (!Flags.isSRet())
2037     return NotStructReturn;
2038   if (Flags.isInReg())
2039     return RegStructReturn;
2040   return StackStructReturn;
2041 }
2042
2043 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2044 /// by "Src" to address "Dst" with size and alignment information specified by
2045 /// the specific parameter attribute. The copy will be passed as a byval
2046 /// function parameter.
2047 static SDValue
2048 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2049                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2050                           SDLoc dl) {
2051   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2052
2053   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2054                        /*isVolatile*/false, /*AlwaysInline=*/true,
2055                        MachinePointerInfo(), MachinePointerInfo());
2056 }
2057
2058 /// IsTailCallConvention - Return true if the calling convention is one that
2059 /// supports tail call optimization.
2060 static bool IsTailCallConvention(CallingConv::ID CC) {
2061   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2062           CC == CallingConv::HiPE);
2063 }
2064
2065 /// \brief Return true if the calling convention is a C calling convention.
2066 static bool IsCCallConvention(CallingConv::ID CC) {
2067   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2068           CC == CallingConv::X86_64_SysV);
2069 }
2070
2071 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2072   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2073     return false;
2074
2075   CallSite CS(CI);
2076   CallingConv::ID CalleeCC = CS.getCallingConv();
2077   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2078     return false;
2079
2080   return true;
2081 }
2082
2083 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2084 /// a tailcall target by changing its ABI.
2085 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2086                                    bool GuaranteedTailCallOpt) {
2087   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2088 }
2089
2090 SDValue
2091 X86TargetLowering::LowerMemArgument(SDValue Chain,
2092                                     CallingConv::ID CallConv,
2093                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2094                                     SDLoc dl, SelectionDAG &DAG,
2095                                     const CCValAssign &VA,
2096                                     MachineFrameInfo *MFI,
2097                                     unsigned i) const {
2098   // Create the nodes corresponding to a load from this parameter slot.
2099   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2100   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2101                               getTargetMachine().Options.GuaranteedTailCallOpt);
2102   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2103   EVT ValVT;
2104
2105   // If value is passed by pointer we have address passed instead of the value
2106   // itself.
2107   if (VA.getLocInfo() == CCValAssign::Indirect)
2108     ValVT = VA.getLocVT();
2109   else
2110     ValVT = VA.getValVT();
2111
2112   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2113   // changed with more analysis.
2114   // In case of tail call optimization mark all arguments mutable. Since they
2115   // could be overwritten by lowering of arguments in case of a tail call.
2116   if (Flags.isByVal()) {
2117     unsigned Bytes = Flags.getByValSize();
2118     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2119     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2120     return DAG.getFrameIndex(FI, getPointerTy());
2121   } else {
2122     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2123                                     VA.getLocMemOffset(), isImmutable);
2124     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2125     return DAG.getLoad(ValVT, dl, Chain, FIN,
2126                        MachinePointerInfo::getFixedStack(FI),
2127                        false, false, false, 0);
2128   }
2129 }
2130
2131 SDValue
2132 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2133                                         CallingConv::ID CallConv,
2134                                         bool isVarArg,
2135                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2136                                         SDLoc dl,
2137                                         SelectionDAG &DAG,
2138                                         SmallVectorImpl<SDValue> &InVals)
2139                                           const {
2140   MachineFunction &MF = DAG.getMachineFunction();
2141   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2142
2143   const Function* Fn = MF.getFunction();
2144   if (Fn->hasExternalLinkage() &&
2145       Subtarget->isTargetCygMing() &&
2146       Fn->getName() == "main")
2147     FuncInfo->setForceFramePointer(true);
2148
2149   MachineFrameInfo *MFI = MF.getFrameInfo();
2150   bool Is64Bit = Subtarget->is64Bit();
2151   bool IsWindows = Subtarget->isTargetWindows();
2152   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2153
2154   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2155          "Var args not supported with calling convention fastcc, ghc or hipe");
2156
2157   // Assign locations to all of the incoming arguments.
2158   SmallVector<CCValAssign, 16> ArgLocs;
2159   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2160                  ArgLocs, *DAG.getContext());
2161
2162   // Allocate shadow area for Win64
2163   if (IsWin64)
2164     CCInfo.AllocateStack(32, 8);
2165
2166   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2167
2168   unsigned LastVal = ~0U;
2169   SDValue ArgValue;
2170   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2171     CCValAssign &VA = ArgLocs[i];
2172     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2173     // places.
2174     assert(VA.getValNo() != LastVal &&
2175            "Don't support value assigned to multiple locs yet");
2176     (void)LastVal;
2177     LastVal = VA.getValNo();
2178
2179     if (VA.isRegLoc()) {
2180       EVT RegVT = VA.getLocVT();
2181       const TargetRegisterClass *RC;
2182       if (RegVT == MVT::i32)
2183         RC = &X86::GR32RegClass;
2184       else if (Is64Bit && RegVT == MVT::i64)
2185         RC = &X86::GR64RegClass;
2186       else if (RegVT == MVT::f32)
2187         RC = &X86::FR32RegClass;
2188       else if (RegVT == MVT::f64)
2189         RC = &X86::FR64RegClass;
2190       else if (RegVT.is512BitVector())
2191         RC = &X86::VR512RegClass;
2192       else if (RegVT.is256BitVector())
2193         RC = &X86::VR256RegClass;
2194       else if (RegVT.is128BitVector())
2195         RC = &X86::VR128RegClass;
2196       else if (RegVT == MVT::x86mmx)
2197         RC = &X86::VR64RegClass;
2198       else if (RegVT == MVT::v8i1)
2199         RC = &X86::VK8RegClass;
2200       else if (RegVT == MVT::v16i1)
2201         RC = &X86::VK16RegClass;
2202       else
2203         llvm_unreachable("Unknown argument type!");
2204
2205       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2206       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2207
2208       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2209       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2210       // right size.
2211       if (VA.getLocInfo() == CCValAssign::SExt)
2212         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2213                                DAG.getValueType(VA.getValVT()));
2214       else if (VA.getLocInfo() == CCValAssign::ZExt)
2215         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2216                                DAG.getValueType(VA.getValVT()));
2217       else if (VA.getLocInfo() == CCValAssign::BCvt)
2218         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2219
2220       if (VA.isExtInLoc()) {
2221         // Handle MMX values passed in XMM regs.
2222         if (RegVT.isVector())
2223           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2224         else
2225           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2226       }
2227     } else {
2228       assert(VA.isMemLoc());
2229       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2230     }
2231
2232     // If value is passed via pointer - do a load.
2233     if (VA.getLocInfo() == CCValAssign::Indirect)
2234       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2235                              MachinePointerInfo(), false, false, false, 0);
2236
2237     InVals.push_back(ArgValue);
2238   }
2239
2240   // The x86-64 ABIs require that for returning structs by value we copy
2241   // the sret argument into %rax/%eax (depending on ABI) for the return.
2242   // Win32 requires us to put the sret argument to %eax as well.
2243   // Save the argument into a virtual register so that we can access it
2244   // from the return points.
2245   if (MF.getFunction()->hasStructRetAttr() &&
2246       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2247     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2248     unsigned Reg = FuncInfo->getSRetReturnReg();
2249     if (!Reg) {
2250       MVT PtrTy = getPointerTy();
2251       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2252       FuncInfo->setSRetReturnReg(Reg);
2253     }
2254     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2255     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2256   }
2257
2258   unsigned StackSize = CCInfo.getNextStackOffset();
2259   // Align stack specially for tail calls.
2260   if (FuncIsMadeTailCallSafe(CallConv,
2261                              MF.getTarget().Options.GuaranteedTailCallOpt))
2262     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2263
2264   // If the function takes variable number of arguments, make a frame index for
2265   // the start of the first vararg value... for expansion of llvm.va_start.
2266   if (isVarArg) {
2267     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2268                     CallConv != CallingConv::X86_ThisCall)) {
2269       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2270     }
2271     if (Is64Bit) {
2272       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2273
2274       // FIXME: We should really autogenerate these arrays
2275       static const uint16_t GPR64ArgRegsWin64[] = {
2276         X86::RCX, X86::RDX, X86::R8,  X86::R9
2277       };
2278       static const uint16_t GPR64ArgRegs64Bit[] = {
2279         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2280       };
2281       static const uint16_t XMMArgRegs64Bit[] = {
2282         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2283         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2284       };
2285       const uint16_t *GPR64ArgRegs;
2286       unsigned NumXMMRegs = 0;
2287
2288       if (IsWin64) {
2289         // The XMM registers which might contain var arg parameters are shadowed
2290         // in their paired GPR.  So we only need to save the GPR to their home
2291         // slots.
2292         TotalNumIntRegs = 4;
2293         GPR64ArgRegs = GPR64ArgRegsWin64;
2294       } else {
2295         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2296         GPR64ArgRegs = GPR64ArgRegs64Bit;
2297
2298         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2299                                                 TotalNumXMMRegs);
2300       }
2301       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2302                                                        TotalNumIntRegs);
2303
2304       bool NoImplicitFloatOps = Fn->getAttributes().
2305         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2306       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2307              "SSE register cannot be used when SSE is disabled!");
2308       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2309                NoImplicitFloatOps) &&
2310              "SSE register cannot be used when SSE is disabled!");
2311       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2312           !Subtarget->hasSSE1())
2313         // Kernel mode asks for SSE to be disabled, so don't push them
2314         // on the stack.
2315         TotalNumXMMRegs = 0;
2316
2317       if (IsWin64) {
2318         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2319         // Get to the caller-allocated home save location.  Add 8 to account
2320         // for the return address.
2321         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2322         FuncInfo->setRegSaveFrameIndex(
2323           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2324         // Fixup to set vararg frame on shadow area (4 x i64).
2325         if (NumIntRegs < 4)
2326           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2327       } else {
2328         // For X86-64, if there are vararg parameters that are passed via
2329         // registers, then we must store them to their spots on the stack so
2330         // they may be loaded by deferencing the result of va_next.
2331         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2332         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2333         FuncInfo->setRegSaveFrameIndex(
2334           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2335                                false));
2336       }
2337
2338       // Store the integer parameter registers.
2339       SmallVector<SDValue, 8> MemOps;
2340       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2341                                         getPointerTy());
2342       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2343       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2344         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2345                                   DAG.getIntPtrConstant(Offset));
2346         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2347                                      &X86::GR64RegClass);
2348         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2349         SDValue Store =
2350           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2351                        MachinePointerInfo::getFixedStack(
2352                          FuncInfo->getRegSaveFrameIndex(), Offset),
2353                        false, false, 0);
2354         MemOps.push_back(Store);
2355         Offset += 8;
2356       }
2357
2358       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2359         // Now store the XMM (fp + vector) parameter registers.
2360         SmallVector<SDValue, 11> SaveXMMOps;
2361         SaveXMMOps.push_back(Chain);
2362
2363         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2364         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2365         SaveXMMOps.push_back(ALVal);
2366
2367         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2368                                FuncInfo->getRegSaveFrameIndex()));
2369         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2370                                FuncInfo->getVarArgsFPOffset()));
2371
2372         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2373           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2374                                        &X86::VR128RegClass);
2375           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2376           SaveXMMOps.push_back(Val);
2377         }
2378         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2379                                      MVT::Other,
2380                                      &SaveXMMOps[0], SaveXMMOps.size()));
2381       }
2382
2383       if (!MemOps.empty())
2384         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2385                             &MemOps[0], MemOps.size());
2386     }
2387   }
2388
2389   // Some CCs need callee pop.
2390   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2391                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2392     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2393   } else {
2394     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2395     // If this is an sret function, the return should pop the hidden pointer.
2396     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2397         argsAreStructReturn(Ins) == StackStructReturn)
2398       FuncInfo->setBytesToPopOnReturn(4);
2399   }
2400
2401   if (!Is64Bit) {
2402     // RegSaveFrameIndex is X86-64 only.
2403     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2404     if (CallConv == CallingConv::X86_FastCall ||
2405         CallConv == CallingConv::X86_ThisCall)
2406       // fastcc functions can't have varargs.
2407       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2408   }
2409
2410   FuncInfo->setArgumentStackSize(StackSize);
2411
2412   return Chain;
2413 }
2414
2415 SDValue
2416 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2417                                     SDValue StackPtr, SDValue Arg,
2418                                     SDLoc dl, SelectionDAG &DAG,
2419                                     const CCValAssign &VA,
2420                                     ISD::ArgFlagsTy Flags) const {
2421   unsigned LocMemOffset = VA.getLocMemOffset();
2422   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2423   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2424   if (Flags.isByVal())
2425     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2426
2427   return DAG.getStore(Chain, dl, Arg, PtrOff,
2428                       MachinePointerInfo::getStack(LocMemOffset),
2429                       false, false, 0);
2430 }
2431
2432 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2433 /// optimization is performed and it is required.
2434 SDValue
2435 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2436                                            SDValue &OutRetAddr, SDValue Chain,
2437                                            bool IsTailCall, bool Is64Bit,
2438                                            int FPDiff, SDLoc dl) const {
2439   // Adjust the Return address stack slot.
2440   EVT VT = getPointerTy();
2441   OutRetAddr = getReturnAddressFrameIndex(DAG);
2442
2443   // Load the "old" Return address.
2444   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2445                            false, false, false, 0);
2446   return SDValue(OutRetAddr.getNode(), 1);
2447 }
2448
2449 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2450 /// optimization is performed and it is required (FPDiff!=0).
2451 static SDValue
2452 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2453                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2454                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2455   // Store the return address to the appropriate stack slot.
2456   if (!FPDiff) return Chain;
2457   // Calculate the new stack slot for the return address.
2458   int NewReturnAddrFI =
2459     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2460                                          false);
2461   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2462   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2463                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2464                        false, false, 0);
2465   return Chain;
2466 }
2467
2468 SDValue
2469 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2470                              SmallVectorImpl<SDValue> &InVals) const {
2471   SelectionDAG &DAG                     = CLI.DAG;
2472   SDLoc &dl                             = CLI.DL;
2473   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2474   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2475   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2476   SDValue Chain                         = CLI.Chain;
2477   SDValue Callee                        = CLI.Callee;
2478   CallingConv::ID CallConv              = CLI.CallConv;
2479   bool &isTailCall                      = CLI.IsTailCall;
2480   bool isVarArg                         = CLI.IsVarArg;
2481
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   bool Is64Bit        = Subtarget->is64Bit();
2484   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2485   bool IsWindows      = Subtarget->isTargetWindows();
2486   StructReturnType SR = callIsStructReturn(Outs);
2487   bool IsSibcall      = false;
2488
2489   if (MF.getTarget().Options.DisableTailCalls)
2490     isTailCall = false;
2491
2492   if (isTailCall) {
2493     // Check if it's really possible to do a tail call.
2494     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2495                     isVarArg, SR != NotStructReturn,
2496                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2497                     Outs, OutVals, Ins, DAG);
2498
2499     // Sibcalls are automatically detected tailcalls which do not require
2500     // ABI changes.
2501     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2502       IsSibcall = true;
2503
2504     if (isTailCall)
2505       ++NumTailCalls;
2506   }
2507
2508   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509          "Var args not supported with calling convention fastcc, ghc or hipe");
2510
2511   // Analyze operands of the call, assigning locations to each operand.
2512   SmallVector<CCValAssign, 16> ArgLocs;
2513   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2514                  ArgLocs, *DAG.getContext());
2515
2516   // Allocate shadow area for Win64
2517   if (IsWin64)
2518     CCInfo.AllocateStack(32, 8);
2519
2520   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2521
2522   // Get a count of how many bytes are to be pushed on the stack.
2523   unsigned NumBytes = CCInfo.getNextStackOffset();
2524   if (IsSibcall)
2525     // This is a sibcall. The memory operands are available in caller's
2526     // own caller's stack.
2527     NumBytes = 0;
2528   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2529            IsTailCallConvention(CallConv))
2530     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2531
2532   int FPDiff = 0;
2533   if (isTailCall && !IsSibcall) {
2534     // Lower arguments at fp - stackoffset + fpdiff.
2535     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2536     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2537
2538     FPDiff = NumBytesCallerPushed - NumBytes;
2539
2540     // Set the delta of movement of the returnaddr stackslot.
2541     // But only set if delta is greater than previous delta.
2542     if (FPDiff < X86Info->getTCReturnAddrDelta())
2543       X86Info->setTCReturnAddrDelta(FPDiff);
2544   }
2545
2546   if (!IsSibcall)
2547     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2548                                  dl);
2549
2550   SDValue RetAddrFrIdx;
2551   // Load return address for tail calls.
2552   if (isTailCall && FPDiff)
2553     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2554                                     Is64Bit, FPDiff, dl);
2555
2556   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2557   SmallVector<SDValue, 8> MemOpChains;
2558   SDValue StackPtr;
2559
2560   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2561   // of tail call optimization arguments are handle later.
2562   const X86RegisterInfo *RegInfo =
2563     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2564   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2565     CCValAssign &VA = ArgLocs[i];
2566     EVT RegVT = VA.getLocVT();
2567     SDValue Arg = OutVals[i];
2568     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2569     bool isByVal = Flags.isByVal();
2570
2571     // Promote the value if needed.
2572     switch (VA.getLocInfo()) {
2573     default: llvm_unreachable("Unknown loc info!");
2574     case CCValAssign::Full: break;
2575     case CCValAssign::SExt:
2576       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2577       break;
2578     case CCValAssign::ZExt:
2579       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2580       break;
2581     case CCValAssign::AExt:
2582       if (RegVT.is128BitVector()) {
2583         // Special case: passing MMX values in XMM registers.
2584         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2585         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2586         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2587       } else
2588         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2589       break;
2590     case CCValAssign::BCvt:
2591       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2592       break;
2593     case CCValAssign::Indirect: {
2594       // Store the argument.
2595       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2596       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2597       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2598                            MachinePointerInfo::getFixedStack(FI),
2599                            false, false, 0);
2600       Arg = SpillSlot;
2601       break;
2602     }
2603     }
2604
2605     if (VA.isRegLoc()) {
2606       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2607       if (isVarArg && IsWin64) {
2608         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2609         // shadow reg if callee is a varargs function.
2610         unsigned ShadowReg = 0;
2611         switch (VA.getLocReg()) {
2612         case X86::XMM0: ShadowReg = X86::RCX; break;
2613         case X86::XMM1: ShadowReg = X86::RDX; break;
2614         case X86::XMM2: ShadowReg = X86::R8; break;
2615         case X86::XMM3: ShadowReg = X86::R9; break;
2616         }
2617         if (ShadowReg)
2618           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2619       }
2620     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2621       assert(VA.isMemLoc());
2622       if (StackPtr.getNode() == 0)
2623         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2624                                       getPointerTy());
2625       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2626                                              dl, DAG, VA, Flags));
2627     }
2628   }
2629
2630   if (!MemOpChains.empty())
2631     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2632                         &MemOpChains[0], MemOpChains.size());
2633
2634   if (Subtarget->isPICStyleGOT()) {
2635     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2636     // GOT pointer.
2637     if (!isTailCall) {
2638       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2639                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2640     } else {
2641       // If we are tail calling and generating PIC/GOT style code load the
2642       // address of the callee into ECX. The value in ecx is used as target of
2643       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2644       // for tail calls on PIC/GOT architectures. Normally we would just put the
2645       // address of GOT into ebx and then call target@PLT. But for tail calls
2646       // ebx would be restored (since ebx is callee saved) before jumping to the
2647       // target@PLT.
2648
2649       // Note: The actual moving to ECX is done further down.
2650       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2651       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2652           !G->getGlobal()->hasProtectedVisibility())
2653         Callee = LowerGlobalAddress(Callee, DAG);
2654       else if (isa<ExternalSymbolSDNode>(Callee))
2655         Callee = LowerExternalSymbol(Callee, DAG);
2656     }
2657   }
2658
2659   if (Is64Bit && isVarArg && !IsWin64) {
2660     // From AMD64 ABI document:
2661     // For calls that may call functions that use varargs or stdargs
2662     // (prototype-less calls or calls to functions containing ellipsis (...) in
2663     // the declaration) %al is used as hidden argument to specify the number
2664     // of SSE registers used. The contents of %al do not need to match exactly
2665     // the number of registers, but must be an ubound on the number of SSE
2666     // registers used and is in the range 0 - 8 inclusive.
2667
2668     // Count the number of XMM registers allocated.
2669     static const uint16_t XMMArgRegs[] = {
2670       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2671       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2672     };
2673     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2674     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2675            && "SSE registers cannot be used when SSE is disabled");
2676
2677     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2678                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2679   }
2680
2681   // For tail calls lower the arguments to the 'real' stack slot.
2682   if (isTailCall) {
2683     // Force all the incoming stack arguments to be loaded from the stack
2684     // before any new outgoing arguments are stored to the stack, because the
2685     // outgoing stack slots may alias the incoming argument stack slots, and
2686     // the alias isn't otherwise explicit. This is slightly more conservative
2687     // than necessary, because it means that each store effectively depends
2688     // on every argument instead of just those arguments it would clobber.
2689     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2690
2691     SmallVector<SDValue, 8> MemOpChains2;
2692     SDValue FIN;
2693     int FI = 0;
2694     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2695       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696         CCValAssign &VA = ArgLocs[i];
2697         if (VA.isRegLoc())
2698           continue;
2699         assert(VA.isMemLoc());
2700         SDValue Arg = OutVals[i];
2701         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2702         // Create frame index.
2703         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2704         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2705         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2706         FIN = DAG.getFrameIndex(FI, getPointerTy());
2707
2708         if (Flags.isByVal()) {
2709           // Copy relative to framepointer.
2710           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2711           if (StackPtr.getNode() == 0)
2712             StackPtr = DAG.getCopyFromReg(Chain, dl,
2713                                           RegInfo->getStackRegister(),
2714                                           getPointerTy());
2715           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2716
2717           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2718                                                            ArgChain,
2719                                                            Flags, DAG, dl));
2720         } else {
2721           // Store relative to framepointer.
2722           MemOpChains2.push_back(
2723             DAG.getStore(ArgChain, dl, Arg, FIN,
2724                          MachinePointerInfo::getFixedStack(FI),
2725                          false, false, 0));
2726         }
2727       }
2728     }
2729
2730     if (!MemOpChains2.empty())
2731       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2732                           &MemOpChains2[0], MemOpChains2.size());
2733
2734     // Store the return address to the appropriate stack slot.
2735     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2736                                      getPointerTy(), RegInfo->getSlotSize(),
2737                                      FPDiff, dl);
2738   }
2739
2740   // Build a sequence of copy-to-reg nodes chained together with token chain
2741   // and flag operands which copy the outgoing args into registers.
2742   SDValue InFlag;
2743   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2744     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2745                              RegsToPass[i].second, InFlag);
2746     InFlag = Chain.getValue(1);
2747   }
2748
2749   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2750     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2751     // In the 64-bit large code model, we have to make all calls
2752     // through a register, since the call instruction's 32-bit
2753     // pc-relative offset may not be large enough to hold the whole
2754     // address.
2755   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2756     // If the callee is a GlobalAddress node (quite common, every direct call
2757     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2758     // it.
2759
2760     // We should use extra load for direct calls to dllimported functions in
2761     // non-JIT mode.
2762     const GlobalValue *GV = G->getGlobal();
2763     if (!GV->hasDLLImportLinkage()) {
2764       unsigned char OpFlags = 0;
2765       bool ExtraLoad = false;
2766       unsigned WrapperKind = ISD::DELETED_NODE;
2767
2768       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2769       // external symbols most go through the PLT in PIC mode.  If the symbol
2770       // has hidden or protected visibility, or if it is static or local, then
2771       // we don't need to use the PLT - we can directly call it.
2772       if (Subtarget->isTargetELF() &&
2773           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2774           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2775         OpFlags = X86II::MO_PLT;
2776       } else if (Subtarget->isPICStyleStubAny() &&
2777                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2778                  (!Subtarget->getTargetTriple().isMacOSX() ||
2779                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2780         // PC-relative references to external symbols should go through $stub,
2781         // unless we're building with the leopard linker or later, which
2782         // automatically synthesizes these stubs.
2783         OpFlags = X86II::MO_DARWIN_STUB;
2784       } else if (Subtarget->isPICStyleRIPRel() &&
2785                  isa<Function>(GV) &&
2786                  cast<Function>(GV)->getAttributes().
2787                    hasAttribute(AttributeSet::FunctionIndex,
2788                                 Attribute::NonLazyBind)) {
2789         // If the function is marked as non-lazy, generate an indirect call
2790         // which loads from the GOT directly. This avoids runtime overhead
2791         // at the cost of eager binding (and one extra byte of encoding).
2792         OpFlags = X86II::MO_GOTPCREL;
2793         WrapperKind = X86ISD::WrapperRIP;
2794         ExtraLoad = true;
2795       }
2796
2797       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2798                                           G->getOffset(), OpFlags);
2799
2800       // Add a wrapper if needed.
2801       if (WrapperKind != ISD::DELETED_NODE)
2802         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2803       // Add extra indirection if needed.
2804       if (ExtraLoad)
2805         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2806                              MachinePointerInfo::getGOT(),
2807                              false, false, false, 0);
2808     }
2809   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2810     unsigned char OpFlags = 0;
2811
2812     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2813     // external symbols should go through the PLT.
2814     if (Subtarget->isTargetELF() &&
2815         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2816       OpFlags = X86II::MO_PLT;
2817     } else if (Subtarget->isPICStyleStubAny() &&
2818                (!Subtarget->getTargetTriple().isMacOSX() ||
2819                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2820       // PC-relative references to external symbols should go through $stub,
2821       // unless we're building with the leopard linker or later, which
2822       // automatically synthesizes these stubs.
2823       OpFlags = X86II::MO_DARWIN_STUB;
2824     }
2825
2826     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2827                                          OpFlags);
2828   }
2829
2830   // Returns a chain & a flag for retval copy to use.
2831   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2832   SmallVector<SDValue, 8> Ops;
2833
2834   if (!IsSibcall && isTailCall) {
2835     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2836                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2837     InFlag = Chain.getValue(1);
2838   }
2839
2840   Ops.push_back(Chain);
2841   Ops.push_back(Callee);
2842
2843   if (isTailCall)
2844     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2845
2846   // Add argument registers to the end of the list so that they are known live
2847   // into the call.
2848   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2849     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2850                                   RegsToPass[i].second.getValueType()));
2851
2852   // Add a register mask operand representing the call-preserved registers.
2853   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2854   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2855   assert(Mask && "Missing call preserved mask for calling convention");
2856   Ops.push_back(DAG.getRegisterMask(Mask));
2857
2858   if (InFlag.getNode())
2859     Ops.push_back(InFlag);
2860
2861   if (isTailCall) {
2862     // We used to do:
2863     //// If this is the first return lowered for this function, add the regs
2864     //// to the liveout set for the function.
2865     // This isn't right, although it's probably harmless on x86; liveouts
2866     // should be computed from returns not tail calls.  Consider a void
2867     // function making a tail call to a function returning int.
2868     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2869   }
2870
2871   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2872   InFlag = Chain.getValue(1);
2873
2874   // Create the CALLSEQ_END node.
2875   unsigned NumBytesForCalleeToPush;
2876   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2877                        getTargetMachine().Options.GuaranteedTailCallOpt))
2878     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2879   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2880            SR == StackStructReturn)
2881     // If this is a call to a struct-return function, the callee
2882     // pops the hidden struct pointer, so we have to push it back.
2883     // This is common for Darwin/X86, Linux & Mingw32 targets.
2884     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2885     NumBytesForCalleeToPush = 4;
2886   else
2887     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2888
2889   // Returns a flag for retval copy to use.
2890   if (!IsSibcall) {
2891     Chain = DAG.getCALLSEQ_END(Chain,
2892                                DAG.getIntPtrConstant(NumBytes, true),
2893                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2894                                                      true),
2895                                InFlag, dl);
2896     InFlag = Chain.getValue(1);
2897   }
2898
2899   // Handle result values, copying them out of physregs into vregs that we
2900   // return.
2901   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2902                          Ins, dl, DAG, InVals);
2903 }
2904
2905 //===----------------------------------------------------------------------===//
2906 //                Fast Calling Convention (tail call) implementation
2907 //===----------------------------------------------------------------------===//
2908
2909 //  Like std call, callee cleans arguments, convention except that ECX is
2910 //  reserved for storing the tail called function address. Only 2 registers are
2911 //  free for argument passing (inreg). Tail call optimization is performed
2912 //  provided:
2913 //                * tailcallopt is enabled
2914 //                * caller/callee are fastcc
2915 //  On X86_64 architecture with GOT-style position independent code only local
2916 //  (within module) calls are supported at the moment.
2917 //  To keep the stack aligned according to platform abi the function
2918 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2919 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2920 //  If a tail called function callee has more arguments than the caller the
2921 //  caller needs to make sure that there is room to move the RETADDR to. This is
2922 //  achieved by reserving an area the size of the argument delta right after the
2923 //  original REtADDR, but before the saved framepointer or the spilled registers
2924 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2925 //  stack layout:
2926 //    arg1
2927 //    arg2
2928 //    RETADDR
2929 //    [ new RETADDR
2930 //      move area ]
2931 //    (possible EBP)
2932 //    ESI
2933 //    EDI
2934 //    local1 ..
2935
2936 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2937 /// for a 16 byte align requirement.
2938 unsigned
2939 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2940                                                SelectionDAG& DAG) const {
2941   MachineFunction &MF = DAG.getMachineFunction();
2942   const TargetMachine &TM = MF.getTarget();
2943   const X86RegisterInfo *RegInfo =
2944     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2945   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2946   unsigned StackAlignment = TFI.getStackAlignment();
2947   uint64_t AlignMask = StackAlignment - 1;
2948   int64_t Offset = StackSize;
2949   unsigned SlotSize = RegInfo->getSlotSize();
2950   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2951     // Number smaller than 12 so just add the difference.
2952     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2953   } else {
2954     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2955     Offset = ((~AlignMask) & Offset) + StackAlignment +
2956       (StackAlignment-SlotSize);
2957   }
2958   return Offset;
2959 }
2960
2961 /// MatchingStackOffset - Return true if the given stack call argument is
2962 /// already available in the same position (relatively) of the caller's
2963 /// incoming argument stack.
2964 static
2965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2966                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2967                          const X86InstrInfo *TII) {
2968   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2969   int FI = INT_MAX;
2970   if (Arg.getOpcode() == ISD::CopyFromReg) {
2971     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2972     if (!TargetRegisterInfo::isVirtualRegister(VR))
2973       return false;
2974     MachineInstr *Def = MRI->getVRegDef(VR);
2975     if (!Def)
2976       return false;
2977     if (!Flags.isByVal()) {
2978       if (!TII->isLoadFromStackSlot(Def, FI))
2979         return false;
2980     } else {
2981       unsigned Opcode = Def->getOpcode();
2982       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2983           Def->getOperand(1).isFI()) {
2984         FI = Def->getOperand(1).getIndex();
2985         Bytes = Flags.getByValSize();
2986       } else
2987         return false;
2988     }
2989   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2990     if (Flags.isByVal())
2991       // ByVal argument is passed in as a pointer but it's now being
2992       // dereferenced. e.g.
2993       // define @foo(%struct.X* %A) {
2994       //   tail call @bar(%struct.X* byval %A)
2995       // }
2996       return false;
2997     SDValue Ptr = Ld->getBasePtr();
2998     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2999     if (!FINode)
3000       return false;
3001     FI = FINode->getIndex();
3002   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3003     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3004     FI = FINode->getIndex();
3005     Bytes = Flags.getByValSize();
3006   } else
3007     return false;
3008
3009   assert(FI != INT_MAX);
3010   if (!MFI->isFixedObjectIndex(FI))
3011     return false;
3012   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3013 }
3014
3015 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3016 /// for tail call optimization. Targets which want to do tail call
3017 /// optimization should implement this function.
3018 bool
3019 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3020                                                      CallingConv::ID CalleeCC,
3021                                                      bool isVarArg,
3022                                                      bool isCalleeStructRet,
3023                                                      bool isCallerStructRet,
3024                                                      Type *RetTy,
3025                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3026                                     const SmallVectorImpl<SDValue> &OutVals,
3027                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3028                                                      SelectionDAG &DAG) const {
3029   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3030     return false;
3031
3032   // If -tailcallopt is specified, make fastcc functions tail-callable.
3033   const MachineFunction &MF = DAG.getMachineFunction();
3034   const Function *CallerF = MF.getFunction();
3035
3036   // If the function return type is x86_fp80 and the callee return type is not,
3037   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3038   // perform a tailcall optimization here.
3039   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3040     return false;
3041
3042   CallingConv::ID CallerCC = CallerF->getCallingConv();
3043   bool CCMatch = CallerCC == CalleeCC;
3044   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3045   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3046
3047   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3048     if (IsTailCallConvention(CalleeCC) && CCMatch)
3049       return true;
3050     return false;
3051   }
3052
3053   // Look for obvious safe cases to perform tail call optimization that do not
3054   // require ABI changes. This is what gcc calls sibcall.
3055
3056   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3057   // emit a special epilogue.
3058   const X86RegisterInfo *RegInfo =
3059     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3060   if (RegInfo->needsStackRealignment(MF))
3061     return false;
3062
3063   // Also avoid sibcall optimization if either caller or callee uses struct
3064   // return semantics.
3065   if (isCalleeStructRet || isCallerStructRet)
3066     return false;
3067
3068   // An stdcall caller is expected to clean up its arguments; the callee
3069   // isn't going to do that.
3070   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3071     return false;
3072
3073   // Do not sibcall optimize vararg calls unless all arguments are passed via
3074   // registers.
3075   if (isVarArg && !Outs.empty()) {
3076
3077     // Optimizing for varargs on Win64 is unlikely to be safe without
3078     // additional testing.
3079     if (IsCalleeWin64 || IsCallerWin64)
3080       return false;
3081
3082     SmallVector<CCValAssign, 16> ArgLocs;
3083     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3084                    getTargetMachine(), ArgLocs, *DAG.getContext());
3085
3086     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3087     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3088       if (!ArgLocs[i].isRegLoc())
3089         return false;
3090   }
3091
3092   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3093   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3094   // this into a sibcall.
3095   bool Unused = false;
3096   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3097     if (!Ins[i].Used) {
3098       Unused = true;
3099       break;
3100     }
3101   }
3102   if (Unused) {
3103     SmallVector<CCValAssign, 16> RVLocs;
3104     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3105                    getTargetMachine(), RVLocs, *DAG.getContext());
3106     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3107     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3108       CCValAssign &VA = RVLocs[i];
3109       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3110         return false;
3111     }
3112   }
3113
3114   // If the calling conventions do not match, then we'd better make sure the
3115   // results are returned in the same way as what the caller expects.
3116   if (!CCMatch) {
3117     SmallVector<CCValAssign, 16> RVLocs1;
3118     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3119                     getTargetMachine(), RVLocs1, *DAG.getContext());
3120     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3121
3122     SmallVector<CCValAssign, 16> RVLocs2;
3123     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3124                     getTargetMachine(), RVLocs2, *DAG.getContext());
3125     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3126
3127     if (RVLocs1.size() != RVLocs2.size())
3128       return false;
3129     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3130       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3131         return false;
3132       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3133         return false;
3134       if (RVLocs1[i].isRegLoc()) {
3135         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3136           return false;
3137       } else {
3138         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3139           return false;
3140       }
3141     }
3142   }
3143
3144   // If the callee takes no arguments then go on to check the results of the
3145   // call.
3146   if (!Outs.empty()) {
3147     // Check if stack adjustment is needed. For now, do not do this if any
3148     // argument is passed on the stack.
3149     SmallVector<CCValAssign, 16> ArgLocs;
3150     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151                    getTargetMachine(), ArgLocs, *DAG.getContext());
3152
3153     // Allocate shadow area for Win64
3154     if (IsCalleeWin64)
3155       CCInfo.AllocateStack(32, 8);
3156
3157     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3158     if (CCInfo.getNextStackOffset()) {
3159       MachineFunction &MF = DAG.getMachineFunction();
3160       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3161         return false;
3162
3163       // Check if the arguments are already laid out in the right way as
3164       // the caller's fixed stack objects.
3165       MachineFrameInfo *MFI = MF.getFrameInfo();
3166       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3167       const X86InstrInfo *TII =
3168         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3169       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3170         CCValAssign &VA = ArgLocs[i];
3171         SDValue Arg = OutVals[i];
3172         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3173         if (VA.getLocInfo() == CCValAssign::Indirect)
3174           return false;
3175         if (!VA.isRegLoc()) {
3176           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3177                                    MFI, MRI, TII))
3178             return false;
3179         }
3180       }
3181     }
3182
3183     // If the tailcall address may be in a register, then make sure it's
3184     // possible to register allocate for it. In 32-bit, the call address can
3185     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3186     // callee-saved registers are restored. These happen to be the same
3187     // registers used to pass 'inreg' arguments so watch out for those.
3188     if (!Subtarget->is64Bit() &&
3189         ((!isa<GlobalAddressSDNode>(Callee) &&
3190           !isa<ExternalSymbolSDNode>(Callee)) ||
3191          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3192       unsigned NumInRegs = 0;
3193       // In PIC we need an extra register to formulate the address computation
3194       // for the callee.
3195       unsigned MaxInRegs =
3196           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3197
3198       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199         CCValAssign &VA = ArgLocs[i];
3200         if (!VA.isRegLoc())
3201           continue;
3202         unsigned Reg = VA.getLocReg();
3203         switch (Reg) {
3204         default: break;
3205         case X86::EAX: case X86::EDX: case X86::ECX:
3206           if (++NumInRegs == MaxInRegs)
3207             return false;
3208           break;
3209         }
3210       }
3211     }
3212   }
3213
3214   return true;
3215 }
3216
3217 FastISel *
3218 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3219                                   const TargetLibraryInfo *libInfo) const {
3220   return X86::createFastISel(funcInfo, libInfo);
3221 }
3222
3223 //===----------------------------------------------------------------------===//
3224 //                           Other Lowering Hooks
3225 //===----------------------------------------------------------------------===//
3226
3227 static bool MayFoldLoad(SDValue Op) {
3228   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3229 }
3230
3231 static bool MayFoldIntoStore(SDValue Op) {
3232   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3233 }
3234
3235 static bool isTargetShuffle(unsigned Opcode) {
3236   switch(Opcode) {
3237   default: return false;
3238   case X86ISD::PSHUFD:
3239   case X86ISD::PSHUFHW:
3240   case X86ISD::PSHUFLW:
3241   case X86ISD::SHUFP:
3242   case X86ISD::PALIGNR:
3243   case X86ISD::MOVLHPS:
3244   case X86ISD::MOVLHPD:
3245   case X86ISD::MOVHLPS:
3246   case X86ISD::MOVLPS:
3247   case X86ISD::MOVLPD:
3248   case X86ISD::MOVSHDUP:
3249   case X86ISD::MOVSLDUP:
3250   case X86ISD::MOVDDUP:
3251   case X86ISD::MOVSS:
3252   case X86ISD::MOVSD:
3253   case X86ISD::UNPCKL:
3254   case X86ISD::UNPCKH:
3255   case X86ISD::VPERMILP:
3256   case X86ISD::VPERM2X128:
3257   case X86ISD::VPERMI:
3258     return true;
3259   }
3260 }
3261
3262 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3263                                     SDValue V1, SelectionDAG &DAG) {
3264   switch(Opc) {
3265   default: llvm_unreachable("Unknown x86 shuffle node");
3266   case X86ISD::MOVSHDUP:
3267   case X86ISD::MOVSLDUP:
3268   case X86ISD::MOVDDUP:
3269     return DAG.getNode(Opc, dl, VT, V1);
3270   }
3271 }
3272
3273 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3274                                     SDValue V1, unsigned TargetMask,
3275                                     SelectionDAG &DAG) {
3276   switch(Opc) {
3277   default: llvm_unreachable("Unknown x86 shuffle node");
3278   case X86ISD::PSHUFD:
3279   case X86ISD::PSHUFHW:
3280   case X86ISD::PSHUFLW:
3281   case X86ISD::VPERMILP:
3282   case X86ISD::VPERMI:
3283     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3284   }
3285 }
3286
3287 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3288                                     SDValue V1, SDValue V2, unsigned TargetMask,
3289                                     SelectionDAG &DAG) {
3290   switch(Opc) {
3291   default: llvm_unreachable("Unknown x86 shuffle node");
3292   case X86ISD::PALIGNR:
3293   case X86ISD::SHUFP:
3294   case X86ISD::VPERM2X128:
3295     return DAG.getNode(Opc, dl, VT, V1, V2,
3296                        DAG.getConstant(TargetMask, MVT::i8));
3297   }
3298 }
3299
3300 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3301                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3302   switch(Opc) {
3303   default: llvm_unreachable("Unknown x86 shuffle node");
3304   case X86ISD::MOVLHPS:
3305   case X86ISD::MOVLHPD:
3306   case X86ISD::MOVHLPS:
3307   case X86ISD::MOVLPS:
3308   case X86ISD::MOVLPD:
3309   case X86ISD::MOVSS:
3310   case X86ISD::MOVSD:
3311   case X86ISD::UNPCKL:
3312   case X86ISD::UNPCKH:
3313     return DAG.getNode(Opc, dl, VT, V1, V2);
3314   }
3315 }
3316
3317 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3318   MachineFunction &MF = DAG.getMachineFunction();
3319   const X86RegisterInfo *RegInfo =
3320     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3321   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3322   int ReturnAddrIndex = FuncInfo->getRAIndex();
3323
3324   if (ReturnAddrIndex == 0) {
3325     // Set up a frame object for the return address.
3326     unsigned SlotSize = RegInfo->getSlotSize();
3327     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3328                                                            -(int64_t)SlotSize,
3329                                                            false);
3330     FuncInfo->setRAIndex(ReturnAddrIndex);
3331   }
3332
3333   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3334 }
3335
3336 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3337                                        bool hasSymbolicDisplacement) {
3338   // Offset should fit into 32 bit immediate field.
3339   if (!isInt<32>(Offset))
3340     return false;
3341
3342   // If we don't have a symbolic displacement - we don't have any extra
3343   // restrictions.
3344   if (!hasSymbolicDisplacement)
3345     return true;
3346
3347   // FIXME: Some tweaks might be needed for medium code model.
3348   if (M != CodeModel::Small && M != CodeModel::Kernel)
3349     return false;
3350
3351   // For small code model we assume that latest object is 16MB before end of 31
3352   // bits boundary. We may also accept pretty large negative constants knowing
3353   // that all objects are in the positive half of address space.
3354   if (M == CodeModel::Small && Offset < 16*1024*1024)
3355     return true;
3356
3357   // For kernel code model we know that all object resist in the negative half
3358   // of 32bits address space. We may not accept negative offsets, since they may
3359   // be just off and we may accept pretty large positive ones.
3360   if (M == CodeModel::Kernel && Offset > 0)
3361     return true;
3362
3363   return false;
3364 }
3365
3366 /// isCalleePop - Determines whether the callee is required to pop its
3367 /// own arguments. Callee pop is necessary to support tail calls.
3368 bool X86::isCalleePop(CallingConv::ID CallingConv,
3369                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3370   if (IsVarArg)
3371     return false;
3372
3373   switch (CallingConv) {
3374   default:
3375     return false;
3376   case CallingConv::X86_StdCall:
3377     return !is64Bit;
3378   case CallingConv::X86_FastCall:
3379     return !is64Bit;
3380   case CallingConv::X86_ThisCall:
3381     return !is64Bit;
3382   case CallingConv::Fast:
3383     return TailCallOpt;
3384   case CallingConv::GHC:
3385     return TailCallOpt;
3386   case CallingConv::HiPE:
3387     return TailCallOpt;
3388   }
3389 }
3390
3391 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3392 /// specific condition code, returning the condition code and the LHS/RHS of the
3393 /// comparison to make.
3394 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3395                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3396   if (!isFP) {
3397     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3398       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3399         // X > -1   -> X == 0, jump !sign.
3400         RHS = DAG.getConstant(0, RHS.getValueType());
3401         return X86::COND_NS;
3402       }
3403       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3404         // X < 0   -> X == 0, jump on sign.
3405         return X86::COND_S;
3406       }
3407       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3408         // X < 1   -> X <= 0
3409         RHS = DAG.getConstant(0, RHS.getValueType());
3410         return X86::COND_LE;
3411       }
3412     }
3413
3414     switch (SetCCOpcode) {
3415     default: llvm_unreachable("Invalid integer condition!");
3416     case ISD::SETEQ:  return X86::COND_E;
3417     case ISD::SETGT:  return X86::COND_G;
3418     case ISD::SETGE:  return X86::COND_GE;
3419     case ISD::SETLT:  return X86::COND_L;
3420     case ISD::SETLE:  return X86::COND_LE;
3421     case ISD::SETNE:  return X86::COND_NE;
3422     case ISD::SETULT: return X86::COND_B;
3423     case ISD::SETUGT: return X86::COND_A;
3424     case ISD::SETULE: return X86::COND_BE;
3425     case ISD::SETUGE: return X86::COND_AE;
3426     }
3427   }
3428
3429   // First determine if it is required or is profitable to flip the operands.
3430
3431   // If LHS is a foldable load, but RHS is not, flip the condition.
3432   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3433       !ISD::isNON_EXTLoad(RHS.getNode())) {
3434     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3435     std::swap(LHS, RHS);
3436   }
3437
3438   switch (SetCCOpcode) {
3439   default: break;
3440   case ISD::SETOLT:
3441   case ISD::SETOLE:
3442   case ISD::SETUGT:
3443   case ISD::SETUGE:
3444     std::swap(LHS, RHS);
3445     break;
3446   }
3447
3448   // On a floating point condition, the flags are set as follows:
3449   // ZF  PF  CF   op
3450   //  0 | 0 | 0 | X > Y
3451   //  0 | 0 | 1 | X < Y
3452   //  1 | 0 | 0 | X == Y
3453   //  1 | 1 | 1 | unordered
3454   switch (SetCCOpcode) {
3455   default: llvm_unreachable("Condcode should be pre-legalized away");
3456   case ISD::SETUEQ:
3457   case ISD::SETEQ:   return X86::COND_E;
3458   case ISD::SETOLT:              // flipped
3459   case ISD::SETOGT:
3460   case ISD::SETGT:   return X86::COND_A;
3461   case ISD::SETOLE:              // flipped
3462   case ISD::SETOGE:
3463   case ISD::SETGE:   return X86::COND_AE;
3464   case ISD::SETUGT:              // flipped
3465   case ISD::SETULT:
3466   case ISD::SETLT:   return X86::COND_B;
3467   case ISD::SETUGE:              // flipped
3468   case ISD::SETULE:
3469   case ISD::SETLE:   return X86::COND_BE;
3470   case ISD::SETONE:
3471   case ISD::SETNE:   return X86::COND_NE;
3472   case ISD::SETUO:   return X86::COND_P;
3473   case ISD::SETO:    return X86::COND_NP;
3474   case ISD::SETOEQ:
3475   case ISD::SETUNE:  return X86::COND_INVALID;
3476   }
3477 }
3478
3479 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3480 /// code. Current x86 isa includes the following FP cmov instructions:
3481 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3482 static bool hasFPCMov(unsigned X86CC) {
3483   switch (X86CC) {
3484   default:
3485     return false;
3486   case X86::COND_B:
3487   case X86::COND_BE:
3488   case X86::COND_E:
3489   case X86::COND_P:
3490   case X86::COND_A:
3491   case X86::COND_AE:
3492   case X86::COND_NE:
3493   case X86::COND_NP:
3494     return true;
3495   }
3496 }
3497
3498 /// isFPImmLegal - Returns true if the target can instruction select the
3499 /// specified FP immediate natively. If false, the legalizer will
3500 /// materialize the FP immediate as a load from a constant pool.
3501 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3502   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3503     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3504       return true;
3505   }
3506   return false;
3507 }
3508
3509 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3510 /// the specified range (L, H].
3511 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3512   return (Val < 0) || (Val >= Low && Val < Hi);
3513 }
3514
3515 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3516 /// specified value.
3517 static bool isUndefOrEqual(int Val, int CmpVal) {
3518   return (Val < 0 || Val == CmpVal);
3519 }
3520
3521 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3522 /// from position Pos and ending in Pos+Size, falls within the specified
3523 /// sequential range (L, L+Pos]. or is undef.
3524 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3525                                        unsigned Pos, unsigned Size, int Low) {
3526   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3527     if (!isUndefOrEqual(Mask[i], Low))
3528       return false;
3529   return true;
3530 }
3531
3532 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3533 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3534 /// the second operand.
3535 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3536   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3537     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3538   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3539     return (Mask[0] < 2 && Mask[1] < 2);
3540   return false;
3541 }
3542
3543 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3544 /// is suitable for input to PSHUFHW.
3545 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3546   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3547     return false;
3548
3549   // Lower quadword copied in order or undef.
3550   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3551     return false;
3552
3553   // Upper quadword shuffled.
3554   for (unsigned i = 4; i != 8; ++i)
3555     if (!isUndefOrInRange(Mask[i], 4, 8))
3556       return false;
3557
3558   if (VT == MVT::v16i16) {
3559     // Lower quadword copied in order or undef.
3560     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3561       return false;
3562
3563     // Upper quadword shuffled.
3564     for (unsigned i = 12; i != 16; ++i)
3565       if (!isUndefOrInRange(Mask[i], 12, 16))
3566         return false;
3567   }
3568
3569   return true;
3570 }
3571
3572 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3573 /// is suitable for input to PSHUFLW.
3574 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3575   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3576     return false;
3577
3578   // Upper quadword copied in order.
3579   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3580     return false;
3581
3582   // Lower quadword shuffled.
3583   for (unsigned i = 0; i != 4; ++i)
3584     if (!isUndefOrInRange(Mask[i], 0, 4))
3585       return false;
3586
3587   if (VT == MVT::v16i16) {
3588     // Upper quadword copied in order.
3589     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3590       return false;
3591
3592     // Lower quadword shuffled.
3593     for (unsigned i = 8; i != 12; ++i)
3594       if (!isUndefOrInRange(Mask[i], 8, 12))
3595         return false;
3596   }
3597
3598   return true;
3599 }
3600
3601 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PALIGNR.
3603 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3604                           const X86Subtarget *Subtarget) {
3605   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3606       (VT.is256BitVector() && !Subtarget->hasInt256()))
3607     return false;
3608
3609   unsigned NumElts = VT.getVectorNumElements();
3610   unsigned NumLanes = VT.getSizeInBits()/128;
3611   unsigned NumLaneElts = NumElts/NumLanes;
3612
3613   // Do not handle 64-bit element shuffles with palignr.
3614   if (NumLaneElts == 2)
3615     return false;
3616
3617   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3618     unsigned i;
3619     for (i = 0; i != NumLaneElts; ++i) {
3620       if (Mask[i+l] >= 0)
3621         break;
3622     }
3623
3624     // Lane is all undef, go to next lane
3625     if (i == NumLaneElts)
3626       continue;
3627
3628     int Start = Mask[i+l];
3629
3630     // Make sure its in this lane in one of the sources
3631     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3632         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3633       return false;
3634
3635     // If not lane 0, then we must match lane 0
3636     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3637       return false;
3638
3639     // Correct second source to be contiguous with first source
3640     if (Start >= (int)NumElts)
3641       Start -= NumElts - NumLaneElts;
3642
3643     // Make sure we're shifting in the right direction.
3644     if (Start <= (int)(i+l))
3645       return false;
3646
3647     Start -= i;
3648
3649     // Check the rest of the elements to see if they are consecutive.
3650     for (++i; i != NumLaneElts; ++i) {
3651       int Idx = Mask[i+l];
3652
3653       // Make sure its in this lane
3654       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3655           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3656         return false;
3657
3658       // If not lane 0, then we must match lane 0
3659       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3660         return false;
3661
3662       if (Idx >= (int)NumElts)
3663         Idx -= NumElts - NumLaneElts;
3664
3665       if (!isUndefOrEqual(Idx, Start+i))
3666         return false;
3667
3668     }
3669   }
3670
3671   return true;
3672 }
3673
3674 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3675 /// the two vector operands have swapped position.
3676 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3677                                      unsigned NumElems) {
3678   for (unsigned i = 0; i != NumElems; ++i) {
3679     int idx = Mask[i];
3680     if (idx < 0)
3681       continue;
3682     else if (idx < (int)NumElems)
3683       Mask[i] = idx + NumElems;
3684     else
3685       Mask[i] = idx - NumElems;
3686   }
3687 }
3688
3689 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3690 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3691 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3692 /// reverse of what x86 shuffles want.
3693 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3694                         bool Commuted = false) {
3695   if (!HasFp256 && VT.is256BitVector())
3696     return false;
3697
3698   unsigned NumElems = VT.getVectorNumElements();
3699   unsigned NumLanes = VT.getSizeInBits()/128;
3700   unsigned NumLaneElems = NumElems/NumLanes;
3701
3702   if (NumLaneElems != 2 && NumLaneElems != 4)
3703     return false;
3704
3705   // VSHUFPSY divides the resulting vector into 4 chunks.
3706   // The sources are also splitted into 4 chunks, and each destination
3707   // chunk must come from a different source chunk.
3708   //
3709   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3710   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3711   //
3712   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3713   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3714   //
3715   // VSHUFPDY divides the resulting vector into 4 chunks.
3716   // The sources are also splitted into 4 chunks, and each destination
3717   // chunk must come from a different source chunk.
3718   //
3719   //  SRC1 =>      X3       X2       X1       X0
3720   //  SRC2 =>      Y3       Y2       Y1       Y0
3721   //
3722   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3723   //
3724   unsigned HalfLaneElems = NumLaneElems/2;
3725   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3726     for (unsigned i = 0; i != NumLaneElems; ++i) {
3727       int Idx = Mask[i+l];
3728       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3729       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3730         return false;
3731       // For VSHUFPSY, the mask of the second half must be the same as the
3732       // first but with the appropriate offsets. This works in the same way as
3733       // VPERMILPS works with masks.
3734       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3735         continue;
3736       if (!isUndefOrEqual(Idx, Mask[i]+l))
3737         return false;
3738     }
3739   }
3740
3741   return true;
3742 }
3743
3744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3746 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3747   if (!VT.is128BitVector())
3748     return false;
3749
3750   unsigned NumElems = VT.getVectorNumElements();
3751
3752   if (NumElems != 4)
3753     return false;
3754
3755   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3756   return isUndefOrEqual(Mask[0], 6) &&
3757          isUndefOrEqual(Mask[1], 7) &&
3758          isUndefOrEqual(Mask[2], 2) &&
3759          isUndefOrEqual(Mask[3], 3);
3760 }
3761
3762 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3763 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3764 /// <2, 3, 2, 3>
3765 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3766   if (!VT.is128BitVector())
3767     return false;
3768
3769   unsigned NumElems = VT.getVectorNumElements();
3770
3771   if (NumElems != 4)
3772     return false;
3773
3774   return isUndefOrEqual(Mask[0], 2) &&
3775          isUndefOrEqual(Mask[1], 3) &&
3776          isUndefOrEqual(Mask[2], 2) &&
3777          isUndefOrEqual(Mask[3], 3);
3778 }
3779
3780 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3782 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3783   if (!VT.is128BitVector())
3784     return false;
3785
3786   unsigned NumElems = VT.getVectorNumElements();
3787
3788   if (NumElems != 2 && NumElems != 4)
3789     return false;
3790
3791   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3792     if (!isUndefOrEqual(Mask[i], i + NumElems))
3793       return false;
3794
3795   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3796     if (!isUndefOrEqual(Mask[i], i))
3797       return false;
3798
3799   return true;
3800 }
3801
3802 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3803 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3804 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3805   if (!VT.is128BitVector())
3806     return false;
3807
3808   unsigned NumElems = VT.getVectorNumElements();
3809
3810   if (NumElems != 2 && NumElems != 4)
3811     return false;
3812
3813   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3814     if (!isUndefOrEqual(Mask[i], i))
3815       return false;
3816
3817   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3818     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3819       return false;
3820
3821   return true;
3822 }
3823
3824 //
3825 // Some special combinations that can be optimized.
3826 //
3827 static
3828 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3829                                SelectionDAG &DAG) {
3830   MVT VT = SVOp->getValueType(0).getSimpleVT();
3831   SDLoc dl(SVOp);
3832
3833   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3834     return SDValue();
3835
3836   ArrayRef<int> Mask = SVOp->getMask();
3837
3838   // These are the special masks that may be optimized.
3839   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3840   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3841   bool MatchEvenMask = true;
3842   bool MatchOddMask  = true;
3843   for (int i=0; i<8; ++i) {
3844     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3845       MatchEvenMask = false;
3846     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3847       MatchOddMask = false;
3848   }
3849
3850   if (!MatchEvenMask && !MatchOddMask)
3851     return SDValue();
3852
3853   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3854
3855   SDValue Op0 = SVOp->getOperand(0);
3856   SDValue Op1 = SVOp->getOperand(1);
3857
3858   if (MatchEvenMask) {
3859     // Shift the second operand right to 32 bits.
3860     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3861     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3862   } else {
3863     // Shift the first operand left to 32 bits.
3864     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3865     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3866   }
3867   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3868   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3869 }
3870
3871 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3873 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3874                          bool HasInt256, bool V2IsSplat = false) {
3875   unsigned NumElts = VT.getVectorNumElements();
3876
3877   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3878          "Unsupported vector type for unpckh");
3879
3880   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3881       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3882     return false;
3883
3884   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3885   // independently on 128-bit lanes.
3886   unsigned NumLanes = VT.getSizeInBits()/128;
3887   unsigned NumLaneElts = NumElts/NumLanes;
3888
3889   for (unsigned l = 0; l != NumLanes; ++l) {
3890     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3891          i != (l+1)*NumLaneElts;
3892          i += 2, ++j) {
3893       int BitI  = Mask[i];
3894       int BitI1 = Mask[i+1];
3895       if (!isUndefOrEqual(BitI, j))
3896         return false;
3897       if (V2IsSplat) {
3898         if (!isUndefOrEqual(BitI1, NumElts))
3899           return false;
3900       } else {
3901         if (!isUndefOrEqual(BitI1, j + NumElts))
3902           return false;
3903       }
3904     }
3905   }
3906
3907   return true;
3908 }
3909
3910 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3912 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3913                          bool HasInt256, bool V2IsSplat = false) {
3914   unsigned NumElts = VT.getVectorNumElements();
3915
3916   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3917          "Unsupported vector type for unpckh");
3918
3919   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3920       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3921     return false;
3922
3923   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3924   // independently on 128-bit lanes.
3925   unsigned NumLanes = VT.getSizeInBits()/128;
3926   unsigned NumLaneElts = NumElts/NumLanes;
3927
3928   for (unsigned l = 0; l != NumLanes; ++l) {
3929     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3930          i != (l+1)*NumLaneElts; i += 2, ++j) {
3931       int BitI  = Mask[i];
3932       int BitI1 = Mask[i+1];
3933       if (!isUndefOrEqual(BitI, j))
3934         return false;
3935       if (V2IsSplat) {
3936         if (isUndefOrEqual(BitI1, NumElts))
3937           return false;
3938       } else {
3939         if (!isUndefOrEqual(BitI1, j+NumElts))
3940           return false;
3941       }
3942     }
3943   }
3944   return true;
3945 }
3946
3947 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3948 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3949 /// <0, 0, 1, 1>
3950 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3951   unsigned NumElts = VT.getVectorNumElements();
3952   bool Is256BitVec = VT.is256BitVector();
3953
3954   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3955          "Unsupported vector type for unpckh");
3956
3957   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3958       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3959     return false;
3960
3961   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3962   // FIXME: Need a better way to get rid of this, there's no latency difference
3963   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3964   // the former later. We should also remove the "_undef" special mask.
3965   if (NumElts == 4 && Is256BitVec)
3966     return false;
3967
3968   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3969   // independently on 128-bit lanes.
3970   unsigned NumLanes = VT.getSizeInBits()/128;
3971   unsigned NumLaneElts = NumElts/NumLanes;
3972
3973   for (unsigned l = 0; l != NumLanes; ++l) {
3974     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3975          i != (l+1)*NumLaneElts;
3976          i += 2, ++j) {
3977       int BitI  = Mask[i];
3978       int BitI1 = Mask[i+1];
3979
3980       if (!isUndefOrEqual(BitI, j))
3981         return false;
3982       if (!isUndefOrEqual(BitI1, j))
3983         return false;
3984     }
3985   }
3986
3987   return true;
3988 }
3989
3990 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3991 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3992 /// <2, 2, 3, 3>
3993 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3994   unsigned NumElts = VT.getVectorNumElements();
3995
3996   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3997          "Unsupported vector type for unpckh");
3998
3999   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4000       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4001     return false;
4002
4003   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4004   // independently on 128-bit lanes.
4005   unsigned NumLanes = VT.getSizeInBits()/128;
4006   unsigned NumLaneElts = NumElts/NumLanes;
4007
4008   for (unsigned l = 0; l != NumLanes; ++l) {
4009     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
4010          i != (l+1)*NumLaneElts; i += 2, ++j) {
4011       int BitI  = Mask[i];
4012       int BitI1 = Mask[i+1];
4013       if (!isUndefOrEqual(BitI, j))
4014         return false;
4015       if (!isUndefOrEqual(BitI1, j))
4016         return false;
4017     }
4018   }
4019   return true;
4020 }
4021
4022 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4023 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4024 /// MOVSD, and MOVD, i.e. setting the lowest element.
4025 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4026   if (VT.getVectorElementType().getSizeInBits() < 32)
4027     return false;
4028   if (!VT.is128BitVector())
4029     return false;
4030
4031   unsigned NumElts = VT.getVectorNumElements();
4032
4033   if (!isUndefOrEqual(Mask[0], NumElts))
4034     return false;
4035
4036   for (unsigned i = 1; i != NumElts; ++i)
4037     if (!isUndefOrEqual(Mask[i], i))
4038       return false;
4039
4040   return true;
4041 }
4042
4043 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4044 /// as permutations between 128-bit chunks or halves. As an example: this
4045 /// shuffle bellow:
4046 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4047 /// The first half comes from the second half of V1 and the second half from the
4048 /// the second half of V2.
4049 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4050   if (!HasFp256 || !VT.is256BitVector())
4051     return false;
4052
4053   // The shuffle result is divided into half A and half B. In total the two
4054   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4055   // B must come from C, D, E or F.
4056   unsigned HalfSize = VT.getVectorNumElements()/2;
4057   bool MatchA = false, MatchB = false;
4058
4059   // Check if A comes from one of C, D, E, F.
4060   for (unsigned Half = 0; Half != 4; ++Half) {
4061     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4062       MatchA = true;
4063       break;
4064     }
4065   }
4066
4067   // Check if B comes from one of C, D, E, F.
4068   for (unsigned Half = 0; Half != 4; ++Half) {
4069     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4070       MatchB = true;
4071       break;
4072     }
4073   }
4074
4075   return MatchA && MatchB;
4076 }
4077
4078 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4079 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4080 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4081   MVT VT = SVOp->getValueType(0).getSimpleVT();
4082
4083   unsigned HalfSize = VT.getVectorNumElements()/2;
4084
4085   unsigned FstHalf = 0, SndHalf = 0;
4086   for (unsigned i = 0; i < HalfSize; ++i) {
4087     if (SVOp->getMaskElt(i) > 0) {
4088       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4089       break;
4090     }
4091   }
4092   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4093     if (SVOp->getMaskElt(i) > 0) {
4094       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4095       break;
4096     }
4097   }
4098
4099   return (FstHalf | (SndHalf << 4));
4100 }
4101
4102 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4103 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4104 /// Note that VPERMIL mask matching is different depending whether theunderlying
4105 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4106 /// to the same elements of the low, but to the higher half of the source.
4107 /// In VPERMILPD the two lanes could be shuffled independently of each other
4108 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4109 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4110   if (!HasFp256)
4111     return false;
4112
4113   unsigned NumElts = VT.getVectorNumElements();
4114   // Only match 256-bit with 32/64-bit types
4115   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4116     return false;
4117
4118   unsigned NumLanes = VT.getSizeInBits()/128;
4119   unsigned LaneSize = NumElts/NumLanes;
4120   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4121     for (unsigned i = 0; i != LaneSize; ++i) {
4122       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4123         return false;
4124       if (NumElts != 8 || l == 0)
4125         continue;
4126       // VPERMILPS handling
4127       if (Mask[i] < 0)
4128         continue;
4129       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4130         return false;
4131     }
4132   }
4133
4134   return true;
4135 }
4136
4137 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4138 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4139 /// element of vector 2 and the other elements to come from vector 1 in order.
4140 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
4141                                bool V2IsSplat = false, bool V2IsUndef = false) {
4142   if (!VT.is128BitVector())
4143     return false;
4144
4145   unsigned NumOps = VT.getVectorNumElements();
4146   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4147     return false;
4148
4149   if (!isUndefOrEqual(Mask[0], 0))
4150     return false;
4151
4152   for (unsigned i = 1; i != NumOps; ++i)
4153     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4154           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4155           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4156       return false;
4157
4158   return true;
4159 }
4160
4161 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4162 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4163 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4164 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
4165                            const X86Subtarget *Subtarget) {
4166   if (!Subtarget->hasSSE3())
4167     return false;
4168
4169   unsigned NumElems = VT.getVectorNumElements();
4170
4171   if ((VT.is128BitVector() && NumElems != 4) ||
4172       (VT.is256BitVector() && NumElems != 8))
4173     return false;
4174
4175   // "i+1" is the value the indexed mask element must have
4176   for (unsigned i = 0; i != NumElems; i += 2)
4177     if (!isUndefOrEqual(Mask[i], i+1) ||
4178         !isUndefOrEqual(Mask[i+1], i+1))
4179       return false;
4180
4181   return true;
4182 }
4183
4184 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4185 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4186 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4187 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
4188                            const X86Subtarget *Subtarget) {
4189   if (!Subtarget->hasSSE3())
4190     return false;
4191
4192   unsigned NumElems = VT.getVectorNumElements();
4193
4194   if ((VT.is128BitVector() && NumElems != 4) ||
4195       (VT.is256BitVector() && NumElems != 8))
4196     return false;
4197
4198   // "i" is the value the indexed mask element must have
4199   for (unsigned i = 0; i != NumElems; i += 2)
4200     if (!isUndefOrEqual(Mask[i], i) ||
4201         !isUndefOrEqual(Mask[i+1], i))
4202       return false;
4203
4204   return true;
4205 }
4206
4207 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4208 /// specifies a shuffle of elements that is suitable for input to 256-bit
4209 /// version of MOVDDUP.
4210 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4211   if (!HasFp256 || !VT.is256BitVector())
4212     return false;
4213
4214   unsigned NumElts = VT.getVectorNumElements();
4215   if (NumElts != 4)
4216     return false;
4217
4218   for (unsigned i = 0; i != NumElts/2; ++i)
4219     if (!isUndefOrEqual(Mask[i], 0))
4220       return false;
4221   for (unsigned i = NumElts/2; i != NumElts; ++i)
4222     if (!isUndefOrEqual(Mask[i], NumElts/2))
4223       return false;
4224   return true;
4225 }
4226
4227 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4228 /// specifies a shuffle of elements that is suitable for input to 128-bit
4229 /// version of MOVDDUP.
4230 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4231   if (!VT.is128BitVector())
4232     return false;
4233
4234   unsigned e = VT.getVectorNumElements() / 2;
4235   for (unsigned i = 0; i != e; ++i)
4236     if (!isUndefOrEqual(Mask[i], i))
4237       return false;
4238   for (unsigned i = 0; i != e; ++i)
4239     if (!isUndefOrEqual(Mask[e+i], i))
4240       return false;
4241   return true;
4242 }
4243
4244 /// isVEXTRACTIndex - Return true if the specified
4245 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4246 /// suitable for instruction that extract 128 or 256 bit vectors
4247 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4248   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4249   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4250     return false;
4251
4252   // The index should be aligned on a vecWidth-bit boundary.
4253   uint64_t Index =
4254     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4255
4256   MVT VT = N->getValueType(0).getSimpleVT();
4257   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4258   bool Result = (Index * ElSize) % vecWidth == 0;
4259
4260   return Result;
4261 }
4262
4263 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4264 /// operand specifies a subvector insert that is suitable for input to
4265 /// insertion of 128 or 256-bit subvectors
4266 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4267   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4268   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4269     return false;
4270   // The index should be aligned on a vecWidth-bit boundary.
4271   uint64_t Index =
4272     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4273
4274   MVT VT = N->getValueType(0).getSimpleVT();
4275   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4276   bool Result = (Index * ElSize) % vecWidth == 0;
4277
4278   return Result;
4279 }
4280
4281 bool X86::isVINSERT128Index(SDNode *N) {
4282   return isVINSERTIndex(N, 128);
4283 }
4284
4285 bool X86::isVINSERT256Index(SDNode *N) {
4286   return isVINSERTIndex(N, 256);
4287 }
4288
4289 bool X86::isVEXTRACT128Index(SDNode *N) {
4290   return isVEXTRACTIndex(N, 128);
4291 }
4292
4293 bool X86::isVEXTRACT256Index(SDNode *N) {
4294   return isVEXTRACTIndex(N, 256);
4295 }
4296
4297 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4298 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4299 /// Handles 128-bit and 256-bit.
4300 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4301   MVT VT = N->getValueType(0).getSimpleVT();
4302
4303   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4304          "Unsupported vector type for PSHUF/SHUFP");
4305
4306   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4307   // independently on 128-bit lanes.
4308   unsigned NumElts = VT.getVectorNumElements();
4309   unsigned NumLanes = VT.getSizeInBits()/128;
4310   unsigned NumLaneElts = NumElts/NumLanes;
4311
4312   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4313          "Only supports 2 or 4 elements per lane");
4314
4315   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4316   unsigned Mask = 0;
4317   for (unsigned i = 0; i != NumElts; ++i) {
4318     int Elt = N->getMaskElt(i);
4319     if (Elt < 0) continue;
4320     Elt &= NumLaneElts - 1;
4321     unsigned ShAmt = (i << Shift) % 8;
4322     Mask |= Elt << ShAmt;
4323   }
4324
4325   return Mask;
4326 }
4327
4328 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4329 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4330 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4331   MVT VT = N->getValueType(0).getSimpleVT();
4332
4333   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4334          "Unsupported vector type for PSHUFHW");
4335
4336   unsigned NumElts = VT.getVectorNumElements();
4337
4338   unsigned Mask = 0;
4339   for (unsigned l = 0; l != NumElts; l += 8) {
4340     // 8 nodes per lane, but we only care about the last 4.
4341     for (unsigned i = 0; i < 4; ++i) {
4342       int Elt = N->getMaskElt(l+i+4);
4343       if (Elt < 0) continue;
4344       Elt &= 0x3; // only 2-bits.
4345       Mask |= Elt << (i * 2);
4346     }
4347   }
4348
4349   return Mask;
4350 }
4351
4352 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4353 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4354 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4355   MVT VT = N->getValueType(0).getSimpleVT();
4356
4357   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4358          "Unsupported vector type for PSHUFHW");
4359
4360   unsigned NumElts = VT.getVectorNumElements();
4361
4362   unsigned Mask = 0;
4363   for (unsigned l = 0; l != NumElts; l += 8) {
4364     // 8 nodes per lane, but we only care about the first 4.
4365     for (unsigned i = 0; i < 4; ++i) {
4366       int Elt = N->getMaskElt(l+i);
4367       if (Elt < 0) continue;
4368       Elt &= 0x3; // only 2-bits
4369       Mask |= Elt << (i * 2);
4370     }
4371   }
4372
4373   return Mask;
4374 }
4375
4376 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4377 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4378 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4379   MVT VT = SVOp->getValueType(0).getSimpleVT();
4380   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4381
4382   unsigned NumElts = VT.getVectorNumElements();
4383   unsigned NumLanes = VT.getSizeInBits()/128;
4384   unsigned NumLaneElts = NumElts/NumLanes;
4385
4386   int Val = 0;
4387   unsigned i;
4388   for (i = 0; i != NumElts; ++i) {
4389     Val = SVOp->getMaskElt(i);
4390     if (Val >= 0)
4391       break;
4392   }
4393   if (Val >= (int)NumElts)
4394     Val -= NumElts - NumLaneElts;
4395
4396   assert(Val - i > 0 && "PALIGNR imm should be positive");
4397   return (Val - i) * EltSize;
4398 }
4399
4400 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4401   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4402   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4403     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4404
4405   uint64_t Index =
4406     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4407
4408   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4409   MVT ElVT = VecVT.getVectorElementType();
4410
4411   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4412   return Index / NumElemsPerChunk;
4413 }
4414
4415 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4416   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4417   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4418     llvm_unreachable("Illegal insert subvector for VINSERT");
4419
4420   uint64_t Index =
4421     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4422
4423   MVT VecVT = N->getValueType(0).getSimpleVT();
4424   MVT ElVT = VecVT.getVectorElementType();
4425
4426   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4427   return Index / NumElemsPerChunk;
4428 }
4429
4430 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4431 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4432 /// and VINSERTI128 instructions.
4433 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4434   return getExtractVEXTRACTImmediate(N, 128);
4435 }
4436
4437 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4438 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4439 /// and VINSERTI64x4 instructions.
4440 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4441   return getExtractVEXTRACTImmediate(N, 256);
4442 }
4443
4444 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4445 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4446 /// and VINSERTI128 instructions.
4447 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4448   return getInsertVINSERTImmediate(N, 128);
4449 }
4450
4451 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4452 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4453 /// and VINSERTI64x4 instructions.
4454 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4455   return getInsertVINSERTImmediate(N, 256);
4456 }
4457
4458 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4459 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4460 /// Handles 256-bit.
4461 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4462   MVT VT = N->getValueType(0).getSimpleVT();
4463
4464   unsigned NumElts = VT.getVectorNumElements();
4465
4466   assert((VT.is256BitVector() && NumElts == 4) &&
4467          "Unsupported vector type for VPERMQ/VPERMPD");
4468
4469   unsigned Mask = 0;
4470   for (unsigned i = 0; i != NumElts; ++i) {
4471     int Elt = N->getMaskElt(i);
4472     if (Elt < 0)
4473       continue;
4474     Mask |= Elt << (i*2);
4475   }
4476
4477   return Mask;
4478 }
4479 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4480 /// constant +0.0.
4481 bool X86::isZeroNode(SDValue Elt) {
4482   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4483     return CN->isNullValue();
4484   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4485     return CFP->getValueAPF().isPosZero();
4486   return false;
4487 }
4488
4489 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4490 /// their permute mask.
4491 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4492                                     SelectionDAG &DAG) {
4493   MVT VT = SVOp->getValueType(0).getSimpleVT();
4494   unsigned NumElems = VT.getVectorNumElements();
4495   SmallVector<int, 8> MaskVec;
4496
4497   for (unsigned i = 0; i != NumElems; ++i) {
4498     int Idx = SVOp->getMaskElt(i);
4499     if (Idx >= 0) {
4500       if (Idx < (int)NumElems)
4501         Idx += NumElems;
4502       else
4503         Idx -= NumElems;
4504     }
4505     MaskVec.push_back(Idx);
4506   }
4507   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4508                               SVOp->getOperand(0), &MaskVec[0]);
4509 }
4510
4511 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4512 /// match movhlps. The lower half elements should come from upper half of
4513 /// V1 (and in order), and the upper half elements should come from the upper
4514 /// half of V2 (and in order).
4515 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4516   if (!VT.is128BitVector())
4517     return false;
4518   if (VT.getVectorNumElements() != 4)
4519     return false;
4520   for (unsigned i = 0, e = 2; i != e; ++i)
4521     if (!isUndefOrEqual(Mask[i], i+2))
4522       return false;
4523   for (unsigned i = 2; i != 4; ++i)
4524     if (!isUndefOrEqual(Mask[i], i+4))
4525       return false;
4526   return true;
4527 }
4528
4529 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4530 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4531 /// required.
4532 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4533   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4534     return false;
4535   N = N->getOperand(0).getNode();
4536   if (!ISD::isNON_EXTLoad(N))
4537     return false;
4538   if (LD)
4539     *LD = cast<LoadSDNode>(N);
4540   return true;
4541 }
4542
4543 // Test whether the given value is a vector value which will be legalized
4544 // into a load.
4545 static bool WillBeConstantPoolLoad(SDNode *N) {
4546   if (N->getOpcode() != ISD::BUILD_VECTOR)
4547     return false;
4548
4549   // Check for any non-constant elements.
4550   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4551     switch (N->getOperand(i).getNode()->getOpcode()) {
4552     case ISD::UNDEF:
4553     case ISD::ConstantFP:
4554     case ISD::Constant:
4555       break;
4556     default:
4557       return false;
4558     }
4559
4560   // Vectors of all-zeros and all-ones are materialized with special
4561   // instructions rather than being loaded.
4562   return !ISD::isBuildVectorAllZeros(N) &&
4563          !ISD::isBuildVectorAllOnes(N);
4564 }
4565
4566 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4567 /// match movlp{s|d}. The lower half elements should come from lower half of
4568 /// V1 (and in order), and the upper half elements should come from the upper
4569 /// half of V2 (and in order). And since V1 will become the source of the
4570 /// MOVLP, it must be either a vector load or a scalar load to vector.
4571 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4572                                ArrayRef<int> Mask, EVT VT) {
4573   if (!VT.is128BitVector())
4574     return false;
4575
4576   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4577     return false;
4578   // Is V2 is a vector load, don't do this transformation. We will try to use
4579   // load folding shufps op.
4580   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4581     return false;
4582
4583   unsigned NumElems = VT.getVectorNumElements();
4584
4585   if (NumElems != 2 && NumElems != 4)
4586     return false;
4587   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4588     if (!isUndefOrEqual(Mask[i], i))
4589       return false;
4590   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4591     if (!isUndefOrEqual(Mask[i], i+NumElems))
4592       return false;
4593   return true;
4594 }
4595
4596 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4597 /// all the same.
4598 static bool isSplatVector(SDNode *N) {
4599   if (N->getOpcode() != ISD::BUILD_VECTOR)
4600     return false;
4601
4602   SDValue SplatValue = N->getOperand(0);
4603   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4604     if (N->getOperand(i) != SplatValue)
4605       return false;
4606   return true;
4607 }
4608
4609 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4610 /// to an zero vector.
4611 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4612 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4613   SDValue V1 = N->getOperand(0);
4614   SDValue V2 = N->getOperand(1);
4615   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4616   for (unsigned i = 0; i != NumElems; ++i) {
4617     int Idx = N->getMaskElt(i);
4618     if (Idx >= (int)NumElems) {
4619       unsigned Opc = V2.getOpcode();
4620       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4621         continue;
4622       if (Opc != ISD::BUILD_VECTOR ||
4623           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4624         return false;
4625     } else if (Idx >= 0) {
4626       unsigned Opc = V1.getOpcode();
4627       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4628         continue;
4629       if (Opc != ISD::BUILD_VECTOR ||
4630           !X86::isZeroNode(V1.getOperand(Idx)))
4631         return false;
4632     }
4633   }
4634   return true;
4635 }
4636
4637 /// getZeroVector - Returns a vector of specified type with all zero elements.
4638 ///
4639 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4640                              SelectionDAG &DAG, SDLoc dl) {
4641   assert(VT.isVector() && "Expected a vector type");
4642
4643   // Always build SSE zero vectors as <4 x i32> bitcasted
4644   // to their dest type. This ensures they get CSE'd.
4645   SDValue Vec;
4646   if (VT.is128BitVector()) {  // SSE
4647     if (Subtarget->hasSSE2()) {  // SSE2
4648       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4649       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4650     } else { // SSE1
4651       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4652       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4653     }
4654   } else if (VT.is256BitVector()) { // AVX
4655     if (Subtarget->hasInt256()) { // AVX2
4656       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4657       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4658       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4659                         array_lengthof(Ops));
4660     } else {
4661       // 256-bit logic and arithmetic instructions in AVX are all
4662       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4663       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4664       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4665       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4666                         array_lengthof(Ops));
4667     }
4668   } else
4669     llvm_unreachable("Unexpected vector type");
4670
4671   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4672 }
4673
4674 /// getOnesVector - Returns a vector of specified type with all bits set.
4675 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4676 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4677 /// Then bitcast to their original type, ensuring they get CSE'd.
4678 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4679                              SDLoc dl) {
4680   assert(VT.isVector() && "Expected a vector type");
4681
4682   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4683   SDValue Vec;
4684   if (VT.is256BitVector()) {
4685     if (HasInt256) { // AVX2
4686       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4687       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4688                         array_lengthof(Ops));
4689     } else { // AVX
4690       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4691       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4692     }
4693   } else if (VT.is128BitVector()) {
4694     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4695   } else
4696     llvm_unreachable("Unexpected vector type");
4697
4698   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4699 }
4700
4701 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4702 /// that point to V2 points to its first element.
4703 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4704   for (unsigned i = 0; i != NumElems; ++i) {
4705     if (Mask[i] > (int)NumElems) {
4706       Mask[i] = NumElems;
4707     }
4708   }
4709 }
4710
4711 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4712 /// operation of specified width.
4713 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4714                        SDValue V2) {
4715   unsigned NumElems = VT.getVectorNumElements();
4716   SmallVector<int, 8> Mask;
4717   Mask.push_back(NumElems);
4718   for (unsigned i = 1; i != NumElems; ++i)
4719     Mask.push_back(i);
4720   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4721 }
4722
4723 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4724 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4725                           SDValue V2) {
4726   unsigned NumElems = VT.getVectorNumElements();
4727   SmallVector<int, 8> Mask;
4728   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4729     Mask.push_back(i);
4730     Mask.push_back(i + NumElems);
4731   }
4732   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4733 }
4734
4735 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4736 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4737                           SDValue V2) {
4738   unsigned NumElems = VT.getVectorNumElements();
4739   SmallVector<int, 8> Mask;
4740   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4741     Mask.push_back(i + Half);
4742     Mask.push_back(i + NumElems + Half);
4743   }
4744   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4745 }
4746
4747 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4748 // a generic shuffle instruction because the target has no such instructions.
4749 // Generate shuffles which repeat i16 and i8 several times until they can be
4750 // represented by v4f32 and then be manipulated by target suported shuffles.
4751 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4752   EVT VT = V.getValueType();
4753   int NumElems = VT.getVectorNumElements();
4754   SDLoc dl(V);
4755
4756   while (NumElems > 4) {
4757     if (EltNo < NumElems/2) {
4758       V = getUnpackl(DAG, dl, VT, V, V);
4759     } else {
4760       V = getUnpackh(DAG, dl, VT, V, V);
4761       EltNo -= NumElems/2;
4762     }
4763     NumElems >>= 1;
4764   }
4765   return V;
4766 }
4767
4768 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4769 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4770   EVT VT = V.getValueType();
4771   SDLoc dl(V);
4772
4773   if (VT.is128BitVector()) {
4774     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4775     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4776     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4777                              &SplatMask[0]);
4778   } else if (VT.is256BitVector()) {
4779     // To use VPERMILPS to splat scalars, the second half of indicies must
4780     // refer to the higher part, which is a duplication of the lower one,
4781     // because VPERMILPS can only handle in-lane permutations.
4782     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4783                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4784
4785     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4786     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4787                              &SplatMask[0]);
4788   } else
4789     llvm_unreachable("Vector size not supported");
4790
4791   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4792 }
4793
4794 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4795 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4796   EVT SrcVT = SV->getValueType(0);
4797   SDValue V1 = SV->getOperand(0);
4798   SDLoc dl(SV);
4799
4800   int EltNo = SV->getSplatIndex();
4801   int NumElems = SrcVT.getVectorNumElements();
4802   bool Is256BitVec = SrcVT.is256BitVector();
4803
4804   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4805          "Unknown how to promote splat for type");
4806
4807   // Extract the 128-bit part containing the splat element and update
4808   // the splat element index when it refers to the higher register.
4809   if (Is256BitVec) {
4810     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4811     if (EltNo >= NumElems/2)
4812       EltNo -= NumElems/2;
4813   }
4814
4815   // All i16 and i8 vector types can't be used directly by a generic shuffle
4816   // instruction because the target has no such instruction. Generate shuffles
4817   // which repeat i16 and i8 several times until they fit in i32, and then can
4818   // be manipulated by target suported shuffles.
4819   EVT EltVT = SrcVT.getVectorElementType();
4820   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4821     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4822
4823   // Recreate the 256-bit vector and place the same 128-bit vector
4824   // into the low and high part. This is necessary because we want
4825   // to use VPERM* to shuffle the vectors
4826   if (Is256BitVec) {
4827     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4828   }
4829
4830   return getLegalSplat(DAG, V1, EltNo);
4831 }
4832
4833 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4834 /// vector of zero or undef vector.  This produces a shuffle where the low
4835 /// element of V2 is swizzled into the zero/undef vector, landing at element
4836 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4837 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4838                                            bool IsZero,
4839                                            const X86Subtarget *Subtarget,
4840                                            SelectionDAG &DAG) {
4841   EVT VT = V2.getValueType();
4842   SDValue V1 = IsZero
4843     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4844   unsigned NumElems = VT.getVectorNumElements();
4845   SmallVector<int, 16> MaskVec;
4846   for (unsigned i = 0; i != NumElems; ++i)
4847     // If this is the insertion idx, put the low elt of V2 here.
4848     MaskVec.push_back(i == Idx ? NumElems : i);
4849   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4850 }
4851
4852 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4853 /// target specific opcode. Returns true if the Mask could be calculated.
4854 /// Sets IsUnary to true if only uses one source.
4855 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4856                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4857   unsigned NumElems = VT.getVectorNumElements();
4858   SDValue ImmN;
4859
4860   IsUnary = false;
4861   switch(N->getOpcode()) {
4862   case X86ISD::SHUFP:
4863     ImmN = N->getOperand(N->getNumOperands()-1);
4864     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4865     break;
4866   case X86ISD::UNPCKH:
4867     DecodeUNPCKHMask(VT, Mask);
4868     break;
4869   case X86ISD::UNPCKL:
4870     DecodeUNPCKLMask(VT, Mask);
4871     break;
4872   case X86ISD::MOVHLPS:
4873     DecodeMOVHLPSMask(NumElems, Mask);
4874     break;
4875   case X86ISD::MOVLHPS:
4876     DecodeMOVLHPSMask(NumElems, Mask);
4877     break;
4878   case X86ISD::PALIGNR:
4879     ImmN = N->getOperand(N->getNumOperands()-1);
4880     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4881     break;
4882   case X86ISD::PSHUFD:
4883   case X86ISD::VPERMILP:
4884     ImmN = N->getOperand(N->getNumOperands()-1);
4885     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4886     IsUnary = true;
4887     break;
4888   case X86ISD::PSHUFHW:
4889     ImmN = N->getOperand(N->getNumOperands()-1);
4890     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4891     IsUnary = true;
4892     break;
4893   case X86ISD::PSHUFLW:
4894     ImmN = N->getOperand(N->getNumOperands()-1);
4895     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4896     IsUnary = true;
4897     break;
4898   case X86ISD::VPERMI:
4899     ImmN = N->getOperand(N->getNumOperands()-1);
4900     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4901     IsUnary = true;
4902     break;
4903   case X86ISD::MOVSS:
4904   case X86ISD::MOVSD: {
4905     // The index 0 always comes from the first element of the second source,
4906     // this is why MOVSS and MOVSD are used in the first place. The other
4907     // elements come from the other positions of the first source vector
4908     Mask.push_back(NumElems);
4909     for (unsigned i = 1; i != NumElems; ++i) {
4910       Mask.push_back(i);
4911     }
4912     break;
4913   }
4914   case X86ISD::VPERM2X128:
4915     ImmN = N->getOperand(N->getNumOperands()-1);
4916     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4917     if (Mask.empty()) return false;
4918     break;
4919   case X86ISD::MOVDDUP:
4920   case X86ISD::MOVLHPD:
4921   case X86ISD::MOVLPD:
4922   case X86ISD::MOVLPS:
4923   case X86ISD::MOVSHDUP:
4924   case X86ISD::MOVSLDUP:
4925     // Not yet implemented
4926     return false;
4927   default: llvm_unreachable("unknown target shuffle node");
4928   }
4929
4930   return true;
4931 }
4932
4933 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4934 /// element of the result of the vector shuffle.
4935 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4936                                    unsigned Depth) {
4937   if (Depth == 6)
4938     return SDValue();  // Limit search depth.
4939
4940   SDValue V = SDValue(N, 0);
4941   EVT VT = V.getValueType();
4942   unsigned Opcode = V.getOpcode();
4943
4944   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4945   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4946     int Elt = SV->getMaskElt(Index);
4947
4948     if (Elt < 0)
4949       return DAG.getUNDEF(VT.getVectorElementType());
4950
4951     unsigned NumElems = VT.getVectorNumElements();
4952     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4953                                          : SV->getOperand(1);
4954     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4955   }
4956
4957   // Recurse into target specific vector shuffles to find scalars.
4958   if (isTargetShuffle(Opcode)) {
4959     MVT ShufVT = V.getValueType().getSimpleVT();
4960     unsigned NumElems = ShufVT.getVectorNumElements();
4961     SmallVector<int, 16> ShuffleMask;
4962     bool IsUnary;
4963
4964     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4965       return SDValue();
4966
4967     int Elt = ShuffleMask[Index];
4968     if (Elt < 0)
4969       return DAG.getUNDEF(ShufVT.getVectorElementType());
4970
4971     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4972                                          : N->getOperand(1);
4973     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4974                                Depth+1);
4975   }
4976
4977   // Actual nodes that may contain scalar elements
4978   if (Opcode == ISD::BITCAST) {
4979     V = V.getOperand(0);
4980     EVT SrcVT = V.getValueType();
4981     unsigned NumElems = VT.getVectorNumElements();
4982
4983     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4984       return SDValue();
4985   }
4986
4987   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4988     return (Index == 0) ? V.getOperand(0)
4989                         : DAG.getUNDEF(VT.getVectorElementType());
4990
4991   if (V.getOpcode() == ISD::BUILD_VECTOR)
4992     return V.getOperand(Index);
4993
4994   return SDValue();
4995 }
4996
4997 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4998 /// shuffle operation which come from a consecutively from a zero. The
4999 /// search can start in two different directions, from left or right.
5000 /// We count undefs as zeros until PreferredNum is reached.
5001 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5002                                          unsigned NumElems, bool ZerosFromLeft,
5003                                          SelectionDAG &DAG,
5004                                          unsigned PreferredNum = -1U) {
5005   unsigned NumZeros = 0;
5006   for (unsigned i = 0; i != NumElems; ++i) {
5007     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5008     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5009     if (!Elt.getNode())
5010       break;
5011
5012     if (X86::isZeroNode(Elt))
5013       ++NumZeros;
5014     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5015       NumZeros = std::min(NumZeros + 1, PreferredNum);
5016     else
5017       break;
5018   }
5019
5020   return NumZeros;
5021 }
5022
5023 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5024 /// correspond consecutively to elements from one of the vector operands,
5025 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5026 static
5027 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5028                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5029                               unsigned NumElems, unsigned &OpNum) {
5030   bool SeenV1 = false;
5031   bool SeenV2 = false;
5032
5033   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5034     int Idx = SVOp->getMaskElt(i);
5035     // Ignore undef indicies
5036     if (Idx < 0)
5037       continue;
5038
5039     if (Idx < (int)NumElems)
5040       SeenV1 = true;
5041     else
5042       SeenV2 = true;
5043
5044     // Only accept consecutive elements from the same vector
5045     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5046       return false;
5047   }
5048
5049   OpNum = SeenV1 ? 0 : 1;
5050   return true;
5051 }
5052
5053 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5054 /// logical left shift of a vector.
5055 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5056                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5057   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5058   unsigned NumZeros = getNumOfConsecutiveZeros(
5059       SVOp, NumElems, false /* check zeros from right */, DAG,
5060       SVOp->getMaskElt(0));
5061   unsigned OpSrc;
5062
5063   if (!NumZeros)
5064     return false;
5065
5066   // Considering the elements in the mask that are not consecutive zeros,
5067   // check if they consecutively come from only one of the source vectors.
5068   //
5069   //               V1 = {X, A, B, C}     0
5070   //                         \  \  \    /
5071   //   vector_shuffle V1, V2 <1, 2, 3, X>
5072   //
5073   if (!isShuffleMaskConsecutive(SVOp,
5074             0,                   // Mask Start Index
5075             NumElems-NumZeros,   // Mask End Index(exclusive)
5076             NumZeros,            // Where to start looking in the src vector
5077             NumElems,            // Number of elements in vector
5078             OpSrc))              // Which source operand ?
5079     return false;
5080
5081   isLeft = false;
5082   ShAmt = NumZeros;
5083   ShVal = SVOp->getOperand(OpSrc);
5084   return true;
5085 }
5086
5087 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5088 /// logical left shift of a vector.
5089 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5090                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5091   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5092   unsigned NumZeros = getNumOfConsecutiveZeros(
5093       SVOp, NumElems, true /* check zeros from left */, DAG,
5094       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5095   unsigned OpSrc;
5096
5097   if (!NumZeros)
5098     return false;
5099
5100   // Considering the elements in the mask that are not consecutive zeros,
5101   // check if they consecutively come from only one of the source vectors.
5102   //
5103   //                           0    { A, B, X, X } = V2
5104   //                          / \    /  /
5105   //   vector_shuffle V1, V2 <X, X, 4, 5>
5106   //
5107   if (!isShuffleMaskConsecutive(SVOp,
5108             NumZeros,     // Mask Start Index
5109             NumElems,     // Mask End Index(exclusive)
5110             0,            // Where to start looking in the src vector
5111             NumElems,     // Number of elements in vector
5112             OpSrc))       // Which source operand ?
5113     return false;
5114
5115   isLeft = true;
5116   ShAmt = NumZeros;
5117   ShVal = SVOp->getOperand(OpSrc);
5118   return true;
5119 }
5120
5121 /// isVectorShift - Returns true if the shuffle can be implemented as a
5122 /// logical left or right shift of a vector.
5123 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5124                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5125   // Although the logic below support any bitwidth size, there are no
5126   // shift instructions which handle more than 128-bit vectors.
5127   if (!SVOp->getValueType(0).is128BitVector())
5128     return false;
5129
5130   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5131       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5132     return true;
5133
5134   return false;
5135 }
5136
5137 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5138 ///
5139 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5140                                        unsigned NumNonZero, unsigned NumZero,
5141                                        SelectionDAG &DAG,
5142                                        const X86Subtarget* Subtarget,
5143                                        const TargetLowering &TLI) {
5144   if (NumNonZero > 8)
5145     return SDValue();
5146
5147   SDLoc dl(Op);
5148   SDValue V(0, 0);
5149   bool First = true;
5150   for (unsigned i = 0; i < 16; ++i) {
5151     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5152     if (ThisIsNonZero && First) {
5153       if (NumZero)
5154         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5155       else
5156         V = DAG.getUNDEF(MVT::v8i16);
5157       First = false;
5158     }
5159
5160     if ((i & 1) != 0) {
5161       SDValue ThisElt(0, 0), LastElt(0, 0);
5162       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5163       if (LastIsNonZero) {
5164         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5165                               MVT::i16, Op.getOperand(i-1));
5166       }
5167       if (ThisIsNonZero) {
5168         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5169         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5170                               ThisElt, DAG.getConstant(8, MVT::i8));
5171         if (LastIsNonZero)
5172           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5173       } else
5174         ThisElt = LastElt;
5175
5176       if (ThisElt.getNode())
5177         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5178                         DAG.getIntPtrConstant(i/2));
5179     }
5180   }
5181
5182   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5183 }
5184
5185 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5186 ///
5187 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5188                                      unsigned NumNonZero, unsigned NumZero,
5189                                      SelectionDAG &DAG,
5190                                      const X86Subtarget* Subtarget,
5191                                      const TargetLowering &TLI) {
5192   if (NumNonZero > 4)
5193     return SDValue();
5194
5195   SDLoc dl(Op);
5196   SDValue V(0, 0);
5197   bool First = true;
5198   for (unsigned i = 0; i < 8; ++i) {
5199     bool isNonZero = (NonZeros & (1 << i)) != 0;
5200     if (isNonZero) {
5201       if (First) {
5202         if (NumZero)
5203           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5204         else
5205           V = DAG.getUNDEF(MVT::v8i16);
5206         First = false;
5207       }
5208       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5209                       MVT::v8i16, V, Op.getOperand(i),
5210                       DAG.getIntPtrConstant(i));
5211     }
5212   }
5213
5214   return V;
5215 }
5216
5217 /// getVShift - Return a vector logical shift node.
5218 ///
5219 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5220                          unsigned NumBits, SelectionDAG &DAG,
5221                          const TargetLowering &TLI, SDLoc dl) {
5222   assert(VT.is128BitVector() && "Unknown type for VShift");
5223   EVT ShVT = MVT::v2i64;
5224   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5225   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5226   return DAG.getNode(ISD::BITCAST, dl, VT,
5227                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5228                              DAG.getConstant(NumBits,
5229                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5230 }
5231
5232 SDValue
5233 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5234                                           SelectionDAG &DAG) const {
5235
5236   // Check if the scalar load can be widened into a vector load. And if
5237   // the address is "base + cst" see if the cst can be "absorbed" into
5238   // the shuffle mask.
5239   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5240     SDValue Ptr = LD->getBasePtr();
5241     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5242       return SDValue();
5243     EVT PVT = LD->getValueType(0);
5244     if (PVT != MVT::i32 && PVT != MVT::f32)
5245       return SDValue();
5246
5247     int FI = -1;
5248     int64_t Offset = 0;
5249     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5250       FI = FINode->getIndex();
5251       Offset = 0;
5252     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5253                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5254       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5255       Offset = Ptr.getConstantOperandVal(1);
5256       Ptr = Ptr.getOperand(0);
5257     } else {
5258       return SDValue();
5259     }
5260
5261     // FIXME: 256-bit vector instructions don't require a strict alignment,
5262     // improve this code to support it better.
5263     unsigned RequiredAlign = VT.getSizeInBits()/8;
5264     SDValue Chain = LD->getChain();
5265     // Make sure the stack object alignment is at least 16 or 32.
5266     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5267     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5268       if (MFI->isFixedObjectIndex(FI)) {
5269         // Can't change the alignment. FIXME: It's possible to compute
5270         // the exact stack offset and reference FI + adjust offset instead.
5271         // If someone *really* cares about this. That's the way to implement it.
5272         return SDValue();
5273       } else {
5274         MFI->setObjectAlignment(FI, RequiredAlign);
5275       }
5276     }
5277
5278     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5279     // Ptr + (Offset & ~15).
5280     if (Offset < 0)
5281       return SDValue();
5282     if ((Offset % RequiredAlign) & 3)
5283       return SDValue();
5284     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5285     if (StartOffset)
5286       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5287                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5288
5289     int EltNo = (Offset - StartOffset) >> 2;
5290     unsigned NumElems = VT.getVectorNumElements();
5291
5292     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5293     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5294                              LD->getPointerInfo().getWithOffset(StartOffset),
5295                              false, false, false, 0);
5296
5297     SmallVector<int, 8> Mask;
5298     for (unsigned i = 0; i != NumElems; ++i)
5299       Mask.push_back(EltNo);
5300
5301     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5302   }
5303
5304   return SDValue();
5305 }
5306
5307 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5308 /// vector of type 'VT', see if the elements can be replaced by a single large
5309 /// load which has the same value as a build_vector whose operands are 'elts'.
5310 ///
5311 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5312 ///
5313 /// FIXME: we'd also like to handle the case where the last elements are zero
5314 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5315 /// There's even a handy isZeroNode for that purpose.
5316 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5317                                         SDLoc &DL, SelectionDAG &DAG) {
5318   EVT EltVT = VT.getVectorElementType();
5319   unsigned NumElems = Elts.size();
5320
5321   LoadSDNode *LDBase = NULL;
5322   unsigned LastLoadedElt = -1U;
5323
5324   // For each element in the initializer, see if we've found a load or an undef.
5325   // If we don't find an initial load element, or later load elements are
5326   // non-consecutive, bail out.
5327   for (unsigned i = 0; i < NumElems; ++i) {
5328     SDValue Elt = Elts[i];
5329
5330     if (!Elt.getNode() ||
5331         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5332       return SDValue();
5333     if (!LDBase) {
5334       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5335         return SDValue();
5336       LDBase = cast<LoadSDNode>(Elt.getNode());
5337       LastLoadedElt = i;
5338       continue;
5339     }
5340     if (Elt.getOpcode() == ISD::UNDEF)
5341       continue;
5342
5343     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5344     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5345       return SDValue();
5346     LastLoadedElt = i;
5347   }
5348
5349   // If we have found an entire vector of loads and undefs, then return a large
5350   // load of the entire vector width starting at the base pointer.  If we found
5351   // consecutive loads for the low half, generate a vzext_load node.
5352   if (LastLoadedElt == NumElems - 1) {
5353     SDValue NewLd = SDValue();
5354     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5355       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5356                           LDBase->getPointerInfo(),
5357                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5358                           LDBase->isInvariant(), 0);
5359     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5360                         LDBase->getPointerInfo(),
5361                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5362                         LDBase->isInvariant(), LDBase->getAlignment());
5363
5364     if (LDBase->hasAnyUseOfValue(1)) {
5365       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5366                                      SDValue(LDBase, 1),
5367                                      SDValue(NewLd.getNode(), 1));
5368       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5369       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5370                              SDValue(NewLd.getNode(), 1));
5371     }
5372
5373     return NewLd;
5374   }
5375   if (NumElems == 4 && LastLoadedElt == 1 &&
5376       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5377     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5378     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5379     SDValue ResNode =
5380         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5381                                 array_lengthof(Ops), MVT::i64,
5382                                 LDBase->getPointerInfo(),
5383                                 LDBase->getAlignment(),
5384                                 false/*isVolatile*/, true/*ReadMem*/,
5385                                 false/*WriteMem*/);
5386
5387     // Make sure the newly-created LOAD is in the same position as LDBase in
5388     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5389     // update uses of LDBase's output chain to use the TokenFactor.
5390     if (LDBase->hasAnyUseOfValue(1)) {
5391       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5392                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5393       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5394       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5395                              SDValue(ResNode.getNode(), 1));
5396     }
5397
5398     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5399   }
5400   return SDValue();
5401 }
5402
5403 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5404 /// to generate a splat value for the following cases:
5405 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5406 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5407 /// a scalar load, or a constant.
5408 /// The VBROADCAST node is returned when a pattern is found,
5409 /// or SDValue() otherwise.
5410 SDValue
5411 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5412   if (!Subtarget->hasFp256())
5413     return SDValue();
5414
5415   MVT VT = Op.getValueType().getSimpleVT();
5416   SDLoc dl(Op);
5417
5418   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5419          "Unsupported vector type for broadcast.");
5420
5421   SDValue Ld;
5422   bool ConstSplatVal;
5423
5424   switch (Op.getOpcode()) {
5425     default:
5426       // Unknown pattern found.
5427       return SDValue();
5428
5429     case ISD::BUILD_VECTOR: {
5430       // The BUILD_VECTOR node must be a splat.
5431       if (!isSplatVector(Op.getNode()))
5432         return SDValue();
5433
5434       Ld = Op.getOperand(0);
5435       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5436                      Ld.getOpcode() == ISD::ConstantFP);
5437
5438       // The suspected load node has several users. Make sure that all
5439       // of its users are from the BUILD_VECTOR node.
5440       // Constants may have multiple users.
5441       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5442         return SDValue();
5443       break;
5444     }
5445
5446     case ISD::VECTOR_SHUFFLE: {
5447       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5448
5449       // Shuffles must have a splat mask where the first element is
5450       // broadcasted.
5451       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5452         return SDValue();
5453
5454       SDValue Sc = Op.getOperand(0);
5455       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5456           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5457
5458         if (!Subtarget->hasInt256())
5459           return SDValue();
5460
5461         // Use the register form of the broadcast instruction available on AVX2.
5462         if (VT.is256BitVector())
5463           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5464         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5465       }
5466
5467       Ld = Sc.getOperand(0);
5468       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5469                        Ld.getOpcode() == ISD::ConstantFP);
5470
5471       // The scalar_to_vector node and the suspected
5472       // load node must have exactly one user.
5473       // Constants may have multiple users.
5474       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5475         return SDValue();
5476       break;
5477     }
5478   }
5479
5480   bool Is256 = VT.is256BitVector();
5481
5482   // Handle the broadcasting a single constant scalar from the constant pool
5483   // into a vector. On Sandybridge it is still better to load a constant vector
5484   // from the constant pool and not to broadcast it from a scalar.
5485   if (ConstSplatVal && Subtarget->hasInt256()) {
5486     EVT CVT = Ld.getValueType();
5487     assert(!CVT.isVector() && "Must not broadcast a vector type");
5488     unsigned ScalarSize = CVT.getSizeInBits();
5489
5490     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5491       const Constant *C = 0;
5492       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5493         C = CI->getConstantIntValue();
5494       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5495         C = CF->getConstantFPValue();
5496
5497       assert(C && "Invalid constant type");
5498
5499       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5500       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5501       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5502                        MachinePointerInfo::getConstantPool(),
5503                        false, false, false, Alignment);
5504
5505       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5506     }
5507   }
5508
5509   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5510   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5511
5512   // Handle AVX2 in-register broadcasts.
5513   if (!IsLoad && Subtarget->hasInt256() &&
5514       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5515     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5516
5517   // The scalar source must be a normal load.
5518   if (!IsLoad)
5519     return SDValue();
5520
5521   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5522     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5523
5524   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5525   // double since there is no vbroadcastsd xmm
5526   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5527     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5528       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5529   }
5530
5531   // Unsupported broadcast.
5532   return SDValue();
5533 }
5534
5535 SDValue
5536 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5537   EVT VT = Op.getValueType();
5538
5539   // Skip if insert_vec_elt is not supported.
5540   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5541     return SDValue();
5542
5543   SDLoc DL(Op);
5544   unsigned NumElems = Op.getNumOperands();
5545
5546   SDValue VecIn1;
5547   SDValue VecIn2;
5548   SmallVector<unsigned, 4> InsertIndices;
5549   SmallVector<int, 8> Mask(NumElems, -1);
5550
5551   for (unsigned i = 0; i != NumElems; ++i) {
5552     unsigned Opc = Op.getOperand(i).getOpcode();
5553
5554     if (Opc == ISD::UNDEF)
5555       continue;
5556
5557     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5558       // Quit if more than 1 elements need inserting.
5559       if (InsertIndices.size() > 1)
5560         return SDValue();
5561
5562       InsertIndices.push_back(i);
5563       continue;
5564     }
5565
5566     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5567     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5568
5569     // Quit if extracted from vector of different type.
5570     if (ExtractedFromVec.getValueType() != VT)
5571       return SDValue();
5572
5573     // Quit if non-constant index.
5574     if (!isa<ConstantSDNode>(ExtIdx))
5575       return SDValue();
5576
5577     if (VecIn1.getNode() == 0)
5578       VecIn1 = ExtractedFromVec;
5579     else if (VecIn1 != ExtractedFromVec) {
5580       if (VecIn2.getNode() == 0)
5581         VecIn2 = ExtractedFromVec;
5582       else if (VecIn2 != ExtractedFromVec)
5583         // Quit if more than 2 vectors to shuffle
5584         return SDValue();
5585     }
5586
5587     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5588
5589     if (ExtractedFromVec == VecIn1)
5590       Mask[i] = Idx;
5591     else if (ExtractedFromVec == VecIn2)
5592       Mask[i] = Idx + NumElems;
5593   }
5594
5595   if (VecIn1.getNode() == 0)
5596     return SDValue();
5597
5598   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5599   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5600   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5601     unsigned Idx = InsertIndices[i];
5602     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5603                      DAG.getIntPtrConstant(Idx));
5604   }
5605
5606   return NV;
5607 }
5608
5609 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5610 SDValue
5611 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5612
5613   EVT VT = Op.getValueType();
5614   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5615          "Unexpected type in LowerBUILD_VECTORvXi1!");
5616
5617   SDLoc dl(Op);
5618   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5619     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5620     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5621                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5622     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5623                        Ops, VT.getVectorNumElements());
5624   }
5625
5626   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5627     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5628     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5629                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5630     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5631                        Ops, VT.getVectorNumElements());
5632   }
5633
5634   bool AllContants = true;
5635   uint64_t Immediate = 0;
5636   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5637     SDValue In = Op.getOperand(idx);
5638     if (In.getOpcode() == ISD::UNDEF)
5639       continue;
5640     if (!isa<ConstantSDNode>(In)) {
5641       AllContants = false;
5642       break;
5643     }
5644     if (cast<ConstantSDNode>(In)->getZExtValue())
5645       Immediate |= (1ULL << idx);
5646   }
5647
5648   if (AllContants) {
5649     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5650       DAG.getConstant(Immediate, MVT::i16));
5651     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5652                        DAG.getIntPtrConstant(0));
5653   }
5654
5655   if (!isSplatVector(Op.getNode()))
5656     llvm_unreachable("Unsupported predicate operation");
5657
5658   SDValue In = Op.getOperand(0);
5659   SDValue EFLAGS, X86CC;
5660   if (In.getOpcode() == ISD::SETCC) {
5661     SDValue Op0 = In.getOperand(0);
5662     SDValue Op1 = In.getOperand(1);
5663     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5664     bool isFP = Op1.getValueType().isFloatingPoint();
5665     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5666
5667     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5668
5669     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5670     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5671     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5672   } else if (In.getOpcode() == X86ISD::SETCC) {
5673     X86CC = In.getOperand(0);
5674     EFLAGS = In.getOperand(1);
5675   } else {
5676     // The algorithm:
5677     //   Bit1 = In & 0x1
5678     //   if (Bit1 != 0)
5679     //     ZF = 0
5680     //   else
5681     //     ZF = 1
5682     //   if (ZF == 0)
5683     //     res = allOnes ### CMOVNE -1, %res
5684     //   else
5685     //     res = allZero
5686     MVT InVT = In.getValueType().getSimpleVT();
5687     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5688     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5689     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5690   }
5691
5692   if (VT == MVT::v16i1) {
5693     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5694     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5695     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5696           Cst0, Cst1, X86CC, EFLAGS);
5697     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5698   }
5699
5700   if (VT == MVT::v8i1) {
5701     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5702     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5703     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5704           Cst0, Cst1, X86CC, EFLAGS);
5705     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5706     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5707   }
5708   llvm_unreachable("Unsupported predicate operation");
5709 }
5710
5711 SDValue
5712 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5713   SDLoc dl(Op);
5714
5715   MVT VT = Op.getValueType().getSimpleVT();
5716   MVT ExtVT = VT.getVectorElementType();
5717   unsigned NumElems = Op.getNumOperands();
5718
5719   // Generate vectors for predicate vectors.
5720   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5721     return LowerBUILD_VECTORvXi1(Op, DAG);
5722
5723   // Vectors containing all zeros can be matched by pxor and xorps later
5724   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5725     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5726     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5727     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5728       return Op;
5729
5730     return getZeroVector(VT, Subtarget, DAG, dl);
5731   }
5732
5733   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5734   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5735   // vpcmpeqd on 256-bit vectors.
5736   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5737     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5738       return Op;
5739
5740     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5741   }
5742
5743   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5744   if (Broadcast.getNode())
5745     return Broadcast;
5746
5747   unsigned EVTBits = ExtVT.getSizeInBits();
5748
5749   unsigned NumZero  = 0;
5750   unsigned NumNonZero = 0;
5751   unsigned NonZeros = 0;
5752   bool IsAllConstants = true;
5753   SmallSet<SDValue, 8> Values;
5754   for (unsigned i = 0; i < NumElems; ++i) {
5755     SDValue Elt = Op.getOperand(i);
5756     if (Elt.getOpcode() == ISD::UNDEF)
5757       continue;
5758     Values.insert(Elt);
5759     if (Elt.getOpcode() != ISD::Constant &&
5760         Elt.getOpcode() != ISD::ConstantFP)
5761       IsAllConstants = false;
5762     if (X86::isZeroNode(Elt))
5763       NumZero++;
5764     else {
5765       NonZeros |= (1 << i);
5766       NumNonZero++;
5767     }
5768   }
5769
5770   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5771   if (NumNonZero == 0)
5772     return DAG.getUNDEF(VT);
5773
5774   // Special case for single non-zero, non-undef, element.
5775   if (NumNonZero == 1) {
5776     unsigned Idx = countTrailingZeros(NonZeros);
5777     SDValue Item = Op.getOperand(Idx);
5778
5779     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5780     // the value are obviously zero, truncate the value to i32 and do the
5781     // insertion that way.  Only do this if the value is non-constant or if the
5782     // value is a constant being inserted into element 0.  It is cheaper to do
5783     // a constant pool load than it is to do a movd + shuffle.
5784     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5785         (!IsAllConstants || Idx == 0)) {
5786       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5787         // Handle SSE only.
5788         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5789         EVT VecVT = MVT::v4i32;
5790         unsigned VecElts = 4;
5791
5792         // Truncate the value (which may itself be a constant) to i32, and
5793         // convert it to a vector with movd (S2V+shuffle to zero extend).
5794         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5795         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5796         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5797
5798         // Now we have our 32-bit value zero extended in the low element of
5799         // a vector.  If Idx != 0, swizzle it into place.
5800         if (Idx != 0) {
5801           SmallVector<int, 4> Mask;
5802           Mask.push_back(Idx);
5803           for (unsigned i = 1; i != VecElts; ++i)
5804             Mask.push_back(i);
5805           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5806                                       &Mask[0]);
5807         }
5808         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5809       }
5810     }
5811
5812     // If we have a constant or non-constant insertion into the low element of
5813     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5814     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5815     // depending on what the source datatype is.
5816     if (Idx == 0) {
5817       if (NumZero == 0)
5818         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5819
5820       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5821           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5822         if (VT.is256BitVector()) {
5823           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5824           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5825                              Item, DAG.getIntPtrConstant(0));
5826         }
5827         assert(VT.is128BitVector() && "Expected an SSE value type!");
5828         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5829         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5830         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5831       }
5832
5833       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5834         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5835         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5836         if (VT.is256BitVector()) {
5837           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5838           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5839         } else {
5840           assert(VT.is128BitVector() && "Expected an SSE value type!");
5841           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5842         }
5843         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5844       }
5845     }
5846
5847     // Is it a vector logical left shift?
5848     if (NumElems == 2 && Idx == 1 &&
5849         X86::isZeroNode(Op.getOperand(0)) &&
5850         !X86::isZeroNode(Op.getOperand(1))) {
5851       unsigned NumBits = VT.getSizeInBits();
5852       return getVShift(true, VT,
5853                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5854                                    VT, Op.getOperand(1)),
5855                        NumBits/2, DAG, *this, dl);
5856     }
5857
5858     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5859       return SDValue();
5860
5861     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5862     // is a non-constant being inserted into an element other than the low one,
5863     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5864     // movd/movss) to move this into the low element, then shuffle it into
5865     // place.
5866     if (EVTBits == 32) {
5867       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5868
5869       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5870       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5871       SmallVector<int, 8> MaskVec;
5872       for (unsigned i = 0; i != NumElems; ++i)
5873         MaskVec.push_back(i == Idx ? 0 : 1);
5874       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5875     }
5876   }
5877
5878   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5879   if (Values.size() == 1) {
5880     if (EVTBits == 32) {
5881       // Instead of a shuffle like this:
5882       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5883       // Check if it's possible to issue this instead.
5884       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5885       unsigned Idx = countTrailingZeros(NonZeros);
5886       SDValue Item = Op.getOperand(Idx);
5887       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5888         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5889     }
5890     return SDValue();
5891   }
5892
5893   // A vector full of immediates; various special cases are already
5894   // handled, so this is best done with a single constant-pool load.
5895   if (IsAllConstants)
5896     return SDValue();
5897
5898   // For AVX-length vectors, build the individual 128-bit pieces and use
5899   // shuffles to put them in place.
5900   if (VT.is256BitVector()) {
5901     SmallVector<SDValue, 32> V;
5902     for (unsigned i = 0; i != NumElems; ++i)
5903       V.push_back(Op.getOperand(i));
5904
5905     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5906
5907     // Build both the lower and upper subvector.
5908     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5909     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5910                                 NumElems/2);
5911
5912     // Recreate the wider vector with the lower and upper part.
5913     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5914   }
5915
5916   // Let legalizer expand 2-wide build_vectors.
5917   if (EVTBits == 64) {
5918     if (NumNonZero == 1) {
5919       // One half is zero or undef.
5920       unsigned Idx = countTrailingZeros(NonZeros);
5921       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5922                                  Op.getOperand(Idx));
5923       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5924     }
5925     return SDValue();
5926   }
5927
5928   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5929   if (EVTBits == 8 && NumElems == 16) {
5930     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5931                                         Subtarget, *this);
5932     if (V.getNode()) return V;
5933   }
5934
5935   if (EVTBits == 16 && NumElems == 8) {
5936     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5937                                       Subtarget, *this);
5938     if (V.getNode()) return V;
5939   }
5940
5941   // If element VT is == 32 bits, turn it into a number of shuffles.
5942   SmallVector<SDValue, 8> V(NumElems);
5943   if (NumElems == 4 && NumZero > 0) {
5944     for (unsigned i = 0; i < 4; ++i) {
5945       bool isZero = !(NonZeros & (1 << i));
5946       if (isZero)
5947         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5948       else
5949         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5950     }
5951
5952     for (unsigned i = 0; i < 2; ++i) {
5953       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5954         default: break;
5955         case 0:
5956           V[i] = V[i*2];  // Must be a zero vector.
5957           break;
5958         case 1:
5959           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5960           break;
5961         case 2:
5962           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5963           break;
5964         case 3:
5965           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5966           break;
5967       }
5968     }
5969
5970     bool Reverse1 = (NonZeros & 0x3) == 2;
5971     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5972     int MaskVec[] = {
5973       Reverse1 ? 1 : 0,
5974       Reverse1 ? 0 : 1,
5975       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5976       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5977     };
5978     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5979   }
5980
5981   if (Values.size() > 1 && VT.is128BitVector()) {
5982     // Check for a build vector of consecutive loads.
5983     for (unsigned i = 0; i < NumElems; ++i)
5984       V[i] = Op.getOperand(i);
5985
5986     // Check for elements which are consecutive loads.
5987     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5988     if (LD.getNode())
5989       return LD;
5990
5991     // Check for a build vector from mostly shuffle plus few inserting.
5992     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5993     if (Sh.getNode())
5994       return Sh;
5995
5996     // For SSE 4.1, use insertps to put the high elements into the low element.
5997     if (getSubtarget()->hasSSE41()) {
5998       SDValue Result;
5999       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6000         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6001       else
6002         Result = DAG.getUNDEF(VT);
6003
6004       for (unsigned i = 1; i < NumElems; ++i) {
6005         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6006         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6007                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6008       }
6009       return Result;
6010     }
6011
6012     // Otherwise, expand into a number of unpckl*, start by extending each of
6013     // our (non-undef) elements to the full vector width with the element in the
6014     // bottom slot of the vector (which generates no code for SSE).
6015     for (unsigned i = 0; i < NumElems; ++i) {
6016       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6017         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6018       else
6019         V[i] = DAG.getUNDEF(VT);
6020     }
6021
6022     // Next, we iteratively mix elements, e.g. for v4f32:
6023     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6024     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6025     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6026     unsigned EltStride = NumElems >> 1;
6027     while (EltStride != 0) {
6028       for (unsigned i = 0; i < EltStride; ++i) {
6029         // If V[i+EltStride] is undef and this is the first round of mixing,
6030         // then it is safe to just drop this shuffle: V[i] is already in the
6031         // right place, the one element (since it's the first round) being
6032         // inserted as undef can be dropped.  This isn't safe for successive
6033         // rounds because they will permute elements within both vectors.
6034         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6035             EltStride == NumElems/2)
6036           continue;
6037
6038         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6039       }
6040       EltStride >>= 1;
6041     }
6042     return V[0];
6043   }
6044   return SDValue();
6045 }
6046
6047 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6048 // to create 256-bit vectors from two other 128-bit ones.
6049 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6050   SDLoc dl(Op);
6051   MVT ResVT = Op.getValueType().getSimpleVT();
6052
6053   assert((ResVT.is256BitVector() ||
6054           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6055
6056   SDValue V1 = Op.getOperand(0);
6057   SDValue V2 = Op.getOperand(1);
6058   unsigned NumElems = ResVT.getVectorNumElements();
6059   if(ResVT.is256BitVector())
6060     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6061
6062   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6063 }
6064
6065 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6066   assert(Op.getNumOperands() == 2);
6067
6068   // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
6069   // from two other 128-bit ones.
6070   return LowerAVXCONCAT_VECTORS(Op, DAG);
6071 }
6072
6073 // Try to lower a shuffle node into a simple blend instruction.
6074 static SDValue
6075 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6076                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6077   SDValue V1 = SVOp->getOperand(0);
6078   SDValue V2 = SVOp->getOperand(1);
6079   SDLoc dl(SVOp);
6080   MVT VT = SVOp->getValueType(0).getSimpleVT();
6081   MVT EltVT = VT.getVectorElementType();
6082   unsigned NumElems = VT.getVectorNumElements();
6083
6084   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6085     return SDValue();
6086   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6087     return SDValue();
6088
6089   // Check the mask for BLEND and build the value.
6090   unsigned MaskValue = 0;
6091   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6092   unsigned NumLanes = (NumElems-1)/8 + 1;
6093   unsigned NumElemsInLane = NumElems / NumLanes;
6094
6095   // Blend for v16i16 should be symetric for the both lanes.
6096   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6097
6098     int SndLaneEltIdx = (NumLanes == 2) ?
6099       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6100     int EltIdx = SVOp->getMaskElt(i);
6101
6102     if ((EltIdx < 0 || EltIdx == (int)i) &&
6103         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6104       continue;
6105
6106     if (((unsigned)EltIdx == (i + NumElems)) &&
6107         (SndLaneEltIdx < 0 ||
6108          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6109       MaskValue |= (1<<i);
6110     else
6111       return SDValue();
6112   }
6113
6114   // Convert i32 vectors to floating point if it is not AVX2.
6115   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6116   MVT BlendVT = VT;
6117   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6118     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6119                                NumElems);
6120     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6121     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6122   }
6123
6124   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6125                             DAG.getConstant(MaskValue, MVT::i32));
6126   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6127 }
6128
6129 // v8i16 shuffles - Prefer shuffles in the following order:
6130 // 1. [all]   pshuflw, pshufhw, optional move
6131 // 2. [ssse3] 1 x pshufb
6132 // 3. [ssse3] 2 x pshufb + 1 x por
6133 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6134 static SDValue
6135 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6136                          SelectionDAG &DAG) {
6137   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6138   SDValue V1 = SVOp->getOperand(0);
6139   SDValue V2 = SVOp->getOperand(1);
6140   SDLoc dl(SVOp);
6141   SmallVector<int, 8> MaskVals;
6142
6143   // Determine if more than 1 of the words in each of the low and high quadwords
6144   // of the result come from the same quadword of one of the two inputs.  Undef
6145   // mask values count as coming from any quadword, for better codegen.
6146   unsigned LoQuad[] = { 0, 0, 0, 0 };
6147   unsigned HiQuad[] = { 0, 0, 0, 0 };
6148   std::bitset<4> InputQuads;
6149   for (unsigned i = 0; i < 8; ++i) {
6150     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6151     int EltIdx = SVOp->getMaskElt(i);
6152     MaskVals.push_back(EltIdx);
6153     if (EltIdx < 0) {
6154       ++Quad[0];
6155       ++Quad[1];
6156       ++Quad[2];
6157       ++Quad[3];
6158       continue;
6159     }
6160     ++Quad[EltIdx / 4];
6161     InputQuads.set(EltIdx / 4);
6162   }
6163
6164   int BestLoQuad = -1;
6165   unsigned MaxQuad = 1;
6166   for (unsigned i = 0; i < 4; ++i) {
6167     if (LoQuad[i] > MaxQuad) {
6168       BestLoQuad = i;
6169       MaxQuad = LoQuad[i];
6170     }
6171   }
6172
6173   int BestHiQuad = -1;
6174   MaxQuad = 1;
6175   for (unsigned i = 0; i < 4; ++i) {
6176     if (HiQuad[i] > MaxQuad) {
6177       BestHiQuad = i;
6178       MaxQuad = HiQuad[i];
6179     }
6180   }
6181
6182   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6183   // of the two input vectors, shuffle them into one input vector so only a
6184   // single pshufb instruction is necessary. If There are more than 2 input
6185   // quads, disable the next transformation since it does not help SSSE3.
6186   bool V1Used = InputQuads[0] || InputQuads[1];
6187   bool V2Used = InputQuads[2] || InputQuads[3];
6188   if (Subtarget->hasSSSE3()) {
6189     if (InputQuads.count() == 2 && V1Used && V2Used) {
6190       BestLoQuad = InputQuads[0] ? 0 : 1;
6191       BestHiQuad = InputQuads[2] ? 2 : 3;
6192     }
6193     if (InputQuads.count() > 2) {
6194       BestLoQuad = -1;
6195       BestHiQuad = -1;
6196     }
6197   }
6198
6199   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6200   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6201   // words from all 4 input quadwords.
6202   SDValue NewV;
6203   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6204     int MaskV[] = {
6205       BestLoQuad < 0 ? 0 : BestLoQuad,
6206       BestHiQuad < 0 ? 1 : BestHiQuad
6207     };
6208     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6209                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6210                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6211     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6212
6213     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6214     // source words for the shuffle, to aid later transformations.
6215     bool AllWordsInNewV = true;
6216     bool InOrder[2] = { true, true };
6217     for (unsigned i = 0; i != 8; ++i) {
6218       int idx = MaskVals[i];
6219       if (idx != (int)i)
6220         InOrder[i/4] = false;
6221       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6222         continue;
6223       AllWordsInNewV = false;
6224       break;
6225     }
6226
6227     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6228     if (AllWordsInNewV) {
6229       for (int i = 0; i != 8; ++i) {
6230         int idx = MaskVals[i];
6231         if (idx < 0)
6232           continue;
6233         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6234         if ((idx != i) && idx < 4)
6235           pshufhw = false;
6236         if ((idx != i) && idx > 3)
6237           pshuflw = false;
6238       }
6239       V1 = NewV;
6240       V2Used = false;
6241       BestLoQuad = 0;
6242       BestHiQuad = 1;
6243     }
6244
6245     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6246     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6247     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6248       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6249       unsigned TargetMask = 0;
6250       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6251                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6252       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6253       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6254                              getShufflePSHUFLWImmediate(SVOp);
6255       V1 = NewV.getOperand(0);
6256       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6257     }
6258   }
6259
6260   // Promote splats to a larger type which usually leads to more efficient code.
6261   // FIXME: Is this true if pshufb is available?
6262   if (SVOp->isSplat())
6263     return PromoteSplat(SVOp, DAG);
6264
6265   // If we have SSSE3, and all words of the result are from 1 input vector,
6266   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6267   // is present, fall back to case 4.
6268   if (Subtarget->hasSSSE3()) {
6269     SmallVector<SDValue,16> pshufbMask;
6270
6271     // If we have elements from both input vectors, set the high bit of the
6272     // shuffle mask element to zero out elements that come from V2 in the V1
6273     // mask, and elements that come from V1 in the V2 mask, so that the two
6274     // results can be OR'd together.
6275     bool TwoInputs = V1Used && V2Used;
6276     for (unsigned i = 0; i != 8; ++i) {
6277       int EltIdx = MaskVals[i] * 2;
6278       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6279       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6280       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6281       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6282     }
6283     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6284     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6285                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6286                                  MVT::v16i8, &pshufbMask[0], 16));
6287     if (!TwoInputs)
6288       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6289
6290     // Calculate the shuffle mask for the second input, shuffle it, and
6291     // OR it with the first shuffled input.
6292     pshufbMask.clear();
6293     for (unsigned i = 0; i != 8; ++i) {
6294       int EltIdx = MaskVals[i] * 2;
6295       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6296       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6297       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6298       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6299     }
6300     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6301     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6302                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6303                                  MVT::v16i8, &pshufbMask[0], 16));
6304     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6305     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6306   }
6307
6308   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6309   // and update MaskVals with new element order.
6310   std::bitset<8> InOrder;
6311   if (BestLoQuad >= 0) {
6312     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6313     for (int i = 0; i != 4; ++i) {
6314       int idx = MaskVals[i];
6315       if (idx < 0) {
6316         InOrder.set(i);
6317       } else if ((idx / 4) == BestLoQuad) {
6318         MaskV[i] = idx & 3;
6319         InOrder.set(i);
6320       }
6321     }
6322     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6323                                 &MaskV[0]);
6324
6325     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6326       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6327       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6328                                   NewV.getOperand(0),
6329                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6330     }
6331   }
6332
6333   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6334   // and update MaskVals with the new element order.
6335   if (BestHiQuad >= 0) {
6336     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6337     for (unsigned i = 4; i != 8; ++i) {
6338       int idx = MaskVals[i];
6339       if (idx < 0) {
6340         InOrder.set(i);
6341       } else if ((idx / 4) == BestHiQuad) {
6342         MaskV[i] = (idx & 3) + 4;
6343         InOrder.set(i);
6344       }
6345     }
6346     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6347                                 &MaskV[0]);
6348
6349     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6350       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6351       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6352                                   NewV.getOperand(0),
6353                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6354     }
6355   }
6356
6357   // In case BestHi & BestLo were both -1, which means each quadword has a word
6358   // from each of the four input quadwords, calculate the InOrder bitvector now
6359   // before falling through to the insert/extract cleanup.
6360   if (BestLoQuad == -1 && BestHiQuad == -1) {
6361     NewV = V1;
6362     for (int i = 0; i != 8; ++i)
6363       if (MaskVals[i] < 0 || MaskVals[i] == i)
6364         InOrder.set(i);
6365   }
6366
6367   // The other elements are put in the right place using pextrw and pinsrw.
6368   for (unsigned i = 0; i != 8; ++i) {
6369     if (InOrder[i])
6370       continue;
6371     int EltIdx = MaskVals[i];
6372     if (EltIdx < 0)
6373       continue;
6374     SDValue ExtOp = (EltIdx < 8) ?
6375       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6376                   DAG.getIntPtrConstant(EltIdx)) :
6377       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6378                   DAG.getIntPtrConstant(EltIdx - 8));
6379     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6380                        DAG.getIntPtrConstant(i));
6381   }
6382   return NewV;
6383 }
6384
6385 // v16i8 shuffles - Prefer shuffles in the following order:
6386 // 1. [ssse3] 1 x pshufb
6387 // 2. [ssse3] 2 x pshufb + 1 x por
6388 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6389 static
6390 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6391                                  SelectionDAG &DAG,
6392                                  const X86TargetLowering &TLI) {
6393   SDValue V1 = SVOp->getOperand(0);
6394   SDValue V2 = SVOp->getOperand(1);
6395   SDLoc dl(SVOp);
6396   ArrayRef<int> MaskVals = SVOp->getMask();
6397
6398   // Promote splats to a larger type which usually leads to more efficient code.
6399   // FIXME: Is this true if pshufb is available?
6400   if (SVOp->isSplat())
6401     return PromoteSplat(SVOp, DAG);
6402
6403   // If we have SSSE3, case 1 is generated when all result bytes come from
6404   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6405   // present, fall back to case 3.
6406
6407   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6408   if (TLI.getSubtarget()->hasSSSE3()) {
6409     SmallVector<SDValue,16> pshufbMask;
6410
6411     // If all result elements are from one input vector, then only translate
6412     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6413     //
6414     // Otherwise, we have elements from both input vectors, and must zero out
6415     // elements that come from V2 in the first mask, and V1 in the second mask
6416     // so that we can OR them together.
6417     for (unsigned i = 0; i != 16; ++i) {
6418       int EltIdx = MaskVals[i];
6419       if (EltIdx < 0 || EltIdx >= 16)
6420         EltIdx = 0x80;
6421       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6422     }
6423     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6424                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6425                                  MVT::v16i8, &pshufbMask[0], 16));
6426
6427     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6428     // the 2nd operand if it's undefined or zero.
6429     if (V2.getOpcode() == ISD::UNDEF ||
6430         ISD::isBuildVectorAllZeros(V2.getNode()))
6431       return V1;
6432
6433     // Calculate the shuffle mask for the second input, shuffle it, and
6434     // OR it with the first shuffled input.
6435     pshufbMask.clear();
6436     for (unsigned i = 0; i != 16; ++i) {
6437       int EltIdx = MaskVals[i];
6438       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6439       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6440     }
6441     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6442                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6443                                  MVT::v16i8, &pshufbMask[0], 16));
6444     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6445   }
6446
6447   // No SSSE3 - Calculate in place words and then fix all out of place words
6448   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6449   // the 16 different words that comprise the two doublequadword input vectors.
6450   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6451   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6452   SDValue NewV = V1;
6453   for (int i = 0; i != 8; ++i) {
6454     int Elt0 = MaskVals[i*2];
6455     int Elt1 = MaskVals[i*2+1];
6456
6457     // This word of the result is all undef, skip it.
6458     if (Elt0 < 0 && Elt1 < 0)
6459       continue;
6460
6461     // This word of the result is already in the correct place, skip it.
6462     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6463       continue;
6464
6465     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6466     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6467     SDValue InsElt;
6468
6469     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6470     // using a single extract together, load it and store it.
6471     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6472       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6473                            DAG.getIntPtrConstant(Elt1 / 2));
6474       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6475                         DAG.getIntPtrConstant(i));
6476       continue;
6477     }
6478
6479     // If Elt1 is defined, extract it from the appropriate source.  If the
6480     // source byte is not also odd, shift the extracted word left 8 bits
6481     // otherwise clear the bottom 8 bits if we need to do an or.
6482     if (Elt1 >= 0) {
6483       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6484                            DAG.getIntPtrConstant(Elt1 / 2));
6485       if ((Elt1 & 1) == 0)
6486         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6487                              DAG.getConstant(8,
6488                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6489       else if (Elt0 >= 0)
6490         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6491                              DAG.getConstant(0xFF00, MVT::i16));
6492     }
6493     // If Elt0 is defined, extract it from the appropriate source.  If the
6494     // source byte is not also even, shift the extracted word right 8 bits. If
6495     // Elt1 was also defined, OR the extracted values together before
6496     // inserting them in the result.
6497     if (Elt0 >= 0) {
6498       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6499                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6500       if ((Elt0 & 1) != 0)
6501         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6502                               DAG.getConstant(8,
6503                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6504       else if (Elt1 >= 0)
6505         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6506                              DAG.getConstant(0x00FF, MVT::i16));
6507       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6508                          : InsElt0;
6509     }
6510     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6511                        DAG.getIntPtrConstant(i));
6512   }
6513   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6514 }
6515
6516 // v32i8 shuffles - Translate to VPSHUFB if possible.
6517 static
6518 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6519                                  const X86Subtarget *Subtarget,
6520                                  SelectionDAG &DAG) {
6521   MVT VT = SVOp->getValueType(0).getSimpleVT();
6522   SDValue V1 = SVOp->getOperand(0);
6523   SDValue V2 = SVOp->getOperand(1);
6524   SDLoc dl(SVOp);
6525   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6526
6527   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6528   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6529   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6530
6531   // VPSHUFB may be generated if
6532   // (1) one of input vector is undefined or zeroinitializer.
6533   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6534   // And (2) the mask indexes don't cross the 128-bit lane.
6535   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6536       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6537     return SDValue();
6538
6539   if (V1IsAllZero && !V2IsAllZero) {
6540     CommuteVectorShuffleMask(MaskVals, 32);
6541     V1 = V2;
6542   }
6543   SmallVector<SDValue, 32> pshufbMask;
6544   for (unsigned i = 0; i != 32; i++) {
6545     int EltIdx = MaskVals[i];
6546     if (EltIdx < 0 || EltIdx >= 32)
6547       EltIdx = 0x80;
6548     else {
6549       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6550         // Cross lane is not allowed.
6551         return SDValue();
6552       EltIdx &= 0xf;
6553     }
6554     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6555   }
6556   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6557                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6558                                   MVT::v32i8, &pshufbMask[0], 32));
6559 }
6560
6561 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6562 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6563 /// done when every pair / quad of shuffle mask elements point to elements in
6564 /// the right sequence. e.g.
6565 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6566 static
6567 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6568                                  SelectionDAG &DAG) {
6569   MVT VT = SVOp->getValueType(0).getSimpleVT();
6570   SDLoc dl(SVOp);
6571   unsigned NumElems = VT.getVectorNumElements();
6572   MVT NewVT;
6573   unsigned Scale;
6574   switch (VT.SimpleTy) {
6575   default: llvm_unreachable("Unexpected!");
6576   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6577   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6578   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6579   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6580   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6581   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6582   }
6583
6584   SmallVector<int, 8> MaskVec;
6585   for (unsigned i = 0; i != NumElems; i += Scale) {
6586     int StartIdx = -1;
6587     for (unsigned j = 0; j != Scale; ++j) {
6588       int EltIdx = SVOp->getMaskElt(i+j);
6589       if (EltIdx < 0)
6590         continue;
6591       if (StartIdx < 0)
6592         StartIdx = (EltIdx / Scale);
6593       if (EltIdx != (int)(StartIdx*Scale + j))
6594         return SDValue();
6595     }
6596     MaskVec.push_back(StartIdx);
6597   }
6598
6599   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6600   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6601   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6602 }
6603
6604 /// getVZextMovL - Return a zero-extending vector move low node.
6605 ///
6606 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6607                             SDValue SrcOp, SelectionDAG &DAG,
6608                             const X86Subtarget *Subtarget, SDLoc dl) {
6609   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6610     LoadSDNode *LD = NULL;
6611     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6612       LD = dyn_cast<LoadSDNode>(SrcOp);
6613     if (!LD) {
6614       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6615       // instead.
6616       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6617       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6618           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6619           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6620           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6621         // PR2108
6622         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6623         return DAG.getNode(ISD::BITCAST, dl, VT,
6624                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6625                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6626                                                    OpVT,
6627                                                    SrcOp.getOperand(0)
6628                                                           .getOperand(0))));
6629       }
6630     }
6631   }
6632
6633   return DAG.getNode(ISD::BITCAST, dl, VT,
6634                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6635                                  DAG.getNode(ISD::BITCAST, dl,
6636                                              OpVT, SrcOp)));
6637 }
6638
6639 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6640 /// which could not be matched by any known target speficic shuffle
6641 static SDValue
6642 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6643
6644   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6645   if (NewOp.getNode())
6646     return NewOp;
6647
6648   MVT VT = SVOp->getValueType(0).getSimpleVT();
6649
6650   unsigned NumElems = VT.getVectorNumElements();
6651   unsigned NumLaneElems = NumElems / 2;
6652
6653   SDLoc dl(SVOp);
6654   MVT EltVT = VT.getVectorElementType();
6655   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6656   SDValue Output[2];
6657
6658   SmallVector<int, 16> Mask;
6659   for (unsigned l = 0; l < 2; ++l) {
6660     // Build a shuffle mask for the output, discovering on the fly which
6661     // input vectors to use as shuffle operands (recorded in InputUsed).
6662     // If building a suitable shuffle vector proves too hard, then bail
6663     // out with UseBuildVector set.
6664     bool UseBuildVector = false;
6665     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6666     unsigned LaneStart = l * NumLaneElems;
6667     for (unsigned i = 0; i != NumLaneElems; ++i) {
6668       // The mask element.  This indexes into the input.
6669       int Idx = SVOp->getMaskElt(i+LaneStart);
6670       if (Idx < 0) {
6671         // the mask element does not index into any input vector.
6672         Mask.push_back(-1);
6673         continue;
6674       }
6675
6676       // The input vector this mask element indexes into.
6677       int Input = Idx / NumLaneElems;
6678
6679       // Turn the index into an offset from the start of the input vector.
6680       Idx -= Input * NumLaneElems;
6681
6682       // Find or create a shuffle vector operand to hold this input.
6683       unsigned OpNo;
6684       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6685         if (InputUsed[OpNo] == Input)
6686           // This input vector is already an operand.
6687           break;
6688         if (InputUsed[OpNo] < 0) {
6689           // Create a new operand for this input vector.
6690           InputUsed[OpNo] = Input;
6691           break;
6692         }
6693       }
6694
6695       if (OpNo >= array_lengthof(InputUsed)) {
6696         // More than two input vectors used!  Give up on trying to create a
6697         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6698         UseBuildVector = true;
6699         break;
6700       }
6701
6702       // Add the mask index for the new shuffle vector.
6703       Mask.push_back(Idx + OpNo * NumLaneElems);
6704     }
6705
6706     if (UseBuildVector) {
6707       SmallVector<SDValue, 16> SVOps;
6708       for (unsigned i = 0; i != NumLaneElems; ++i) {
6709         // The mask element.  This indexes into the input.
6710         int Idx = SVOp->getMaskElt(i+LaneStart);
6711         if (Idx < 0) {
6712           SVOps.push_back(DAG.getUNDEF(EltVT));
6713           continue;
6714         }
6715
6716         // The input vector this mask element indexes into.
6717         int Input = Idx / NumElems;
6718
6719         // Turn the index into an offset from the start of the input vector.
6720         Idx -= Input * NumElems;
6721
6722         // Extract the vector element by hand.
6723         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6724                                     SVOp->getOperand(Input),
6725                                     DAG.getIntPtrConstant(Idx)));
6726       }
6727
6728       // Construct the output using a BUILD_VECTOR.
6729       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6730                               SVOps.size());
6731     } else if (InputUsed[0] < 0) {
6732       // No input vectors were used! The result is undefined.
6733       Output[l] = DAG.getUNDEF(NVT);
6734     } else {
6735       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6736                                         (InputUsed[0] % 2) * NumLaneElems,
6737                                         DAG, dl);
6738       // If only one input was used, use an undefined vector for the other.
6739       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6740         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6741                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6742       // At least one input vector was used. Create a new shuffle vector.
6743       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6744     }
6745
6746     Mask.clear();
6747   }
6748
6749   // Concatenate the result back
6750   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6751 }
6752
6753 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6754 /// 4 elements, and match them with several different shuffle types.
6755 static SDValue
6756 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6757   SDValue V1 = SVOp->getOperand(0);
6758   SDValue V2 = SVOp->getOperand(1);
6759   SDLoc dl(SVOp);
6760   MVT VT = SVOp->getValueType(0).getSimpleVT();
6761
6762   assert(VT.is128BitVector() && "Unsupported vector size");
6763
6764   std::pair<int, int> Locs[4];
6765   int Mask1[] = { -1, -1, -1, -1 };
6766   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6767
6768   unsigned NumHi = 0;
6769   unsigned NumLo = 0;
6770   for (unsigned i = 0; i != 4; ++i) {
6771     int Idx = PermMask[i];
6772     if (Idx < 0) {
6773       Locs[i] = std::make_pair(-1, -1);
6774     } else {
6775       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6776       if (Idx < 4) {
6777         Locs[i] = std::make_pair(0, NumLo);
6778         Mask1[NumLo] = Idx;
6779         NumLo++;
6780       } else {
6781         Locs[i] = std::make_pair(1, NumHi);
6782         if (2+NumHi < 4)
6783           Mask1[2+NumHi] = Idx;
6784         NumHi++;
6785       }
6786     }
6787   }
6788
6789   if (NumLo <= 2 && NumHi <= 2) {
6790     // If no more than two elements come from either vector. This can be
6791     // implemented with two shuffles. First shuffle gather the elements.
6792     // The second shuffle, which takes the first shuffle as both of its
6793     // vector operands, put the elements into the right order.
6794     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6795
6796     int Mask2[] = { -1, -1, -1, -1 };
6797
6798     for (unsigned i = 0; i != 4; ++i)
6799       if (Locs[i].first != -1) {
6800         unsigned Idx = (i < 2) ? 0 : 4;
6801         Idx += Locs[i].first * 2 + Locs[i].second;
6802         Mask2[i] = Idx;
6803       }
6804
6805     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6806   }
6807
6808   if (NumLo == 3 || NumHi == 3) {
6809     // Otherwise, we must have three elements from one vector, call it X, and
6810     // one element from the other, call it Y.  First, use a shufps to build an
6811     // intermediate vector with the one element from Y and the element from X
6812     // that will be in the same half in the final destination (the indexes don't
6813     // matter). Then, use a shufps to build the final vector, taking the half
6814     // containing the element from Y from the intermediate, and the other half
6815     // from X.
6816     if (NumHi == 3) {
6817       // Normalize it so the 3 elements come from V1.
6818       CommuteVectorShuffleMask(PermMask, 4);
6819       std::swap(V1, V2);
6820     }
6821
6822     // Find the element from V2.
6823     unsigned HiIndex;
6824     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6825       int Val = PermMask[HiIndex];
6826       if (Val < 0)
6827         continue;
6828       if (Val >= 4)
6829         break;
6830     }
6831
6832     Mask1[0] = PermMask[HiIndex];
6833     Mask1[1] = -1;
6834     Mask1[2] = PermMask[HiIndex^1];
6835     Mask1[3] = -1;
6836     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6837
6838     if (HiIndex >= 2) {
6839       Mask1[0] = PermMask[0];
6840       Mask1[1] = PermMask[1];
6841       Mask1[2] = HiIndex & 1 ? 6 : 4;
6842       Mask1[3] = HiIndex & 1 ? 4 : 6;
6843       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6844     }
6845
6846     Mask1[0] = HiIndex & 1 ? 2 : 0;
6847     Mask1[1] = HiIndex & 1 ? 0 : 2;
6848     Mask1[2] = PermMask[2];
6849     Mask1[3] = PermMask[3];
6850     if (Mask1[2] >= 0)
6851       Mask1[2] += 4;
6852     if (Mask1[3] >= 0)
6853       Mask1[3] += 4;
6854     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6855   }
6856
6857   // Break it into (shuffle shuffle_hi, shuffle_lo).
6858   int LoMask[] = { -1, -1, -1, -1 };
6859   int HiMask[] = { -1, -1, -1, -1 };
6860
6861   int *MaskPtr = LoMask;
6862   unsigned MaskIdx = 0;
6863   unsigned LoIdx = 0;
6864   unsigned HiIdx = 2;
6865   for (unsigned i = 0; i != 4; ++i) {
6866     if (i == 2) {
6867       MaskPtr = HiMask;
6868       MaskIdx = 1;
6869       LoIdx = 0;
6870       HiIdx = 2;
6871     }
6872     int Idx = PermMask[i];
6873     if (Idx < 0) {
6874       Locs[i] = std::make_pair(-1, -1);
6875     } else if (Idx < 4) {
6876       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6877       MaskPtr[LoIdx] = Idx;
6878       LoIdx++;
6879     } else {
6880       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6881       MaskPtr[HiIdx] = Idx;
6882       HiIdx++;
6883     }
6884   }
6885
6886   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6887   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6888   int MaskOps[] = { -1, -1, -1, -1 };
6889   for (unsigned i = 0; i != 4; ++i)
6890     if (Locs[i].first != -1)
6891       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6892   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6893 }
6894
6895 static bool MayFoldVectorLoad(SDValue V) {
6896   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6897     V = V.getOperand(0);
6898
6899   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6900     V = V.getOperand(0);
6901   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6902       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6903     // BUILD_VECTOR (load), undef
6904     V = V.getOperand(0);
6905
6906   return MayFoldLoad(V);
6907 }
6908
6909 static
6910 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6911   EVT VT = Op.getValueType();
6912
6913   // Canonizalize to v2f64.
6914   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6915   return DAG.getNode(ISD::BITCAST, dl, VT,
6916                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6917                                           V1, DAG));
6918 }
6919
6920 static
6921 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6922                         bool HasSSE2) {
6923   SDValue V1 = Op.getOperand(0);
6924   SDValue V2 = Op.getOperand(1);
6925   EVT VT = Op.getValueType();
6926
6927   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6928
6929   if (HasSSE2 && VT == MVT::v2f64)
6930     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6931
6932   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6933   return DAG.getNode(ISD::BITCAST, dl, VT,
6934                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6935                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6936                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6937 }
6938
6939 static
6940 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6941   SDValue V1 = Op.getOperand(0);
6942   SDValue V2 = Op.getOperand(1);
6943   EVT VT = Op.getValueType();
6944
6945   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6946          "unsupported shuffle type");
6947
6948   if (V2.getOpcode() == ISD::UNDEF)
6949     V2 = V1;
6950
6951   // v4i32 or v4f32
6952   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6953 }
6954
6955 static
6956 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6957   SDValue V1 = Op.getOperand(0);
6958   SDValue V2 = Op.getOperand(1);
6959   EVT VT = Op.getValueType();
6960   unsigned NumElems = VT.getVectorNumElements();
6961
6962   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6963   // operand of these instructions is only memory, so check if there's a
6964   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6965   // same masks.
6966   bool CanFoldLoad = false;
6967
6968   // Trivial case, when V2 comes from a load.
6969   if (MayFoldVectorLoad(V2))
6970     CanFoldLoad = true;
6971
6972   // When V1 is a load, it can be folded later into a store in isel, example:
6973   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6974   //    turns into:
6975   //  (MOVLPSmr addr:$src1, VR128:$src2)
6976   // So, recognize this potential and also use MOVLPS or MOVLPD
6977   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6978     CanFoldLoad = true;
6979
6980   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6981   if (CanFoldLoad) {
6982     if (HasSSE2 && NumElems == 2)
6983       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6984
6985     if (NumElems == 4)
6986       // If we don't care about the second element, proceed to use movss.
6987       if (SVOp->getMaskElt(1) != -1)
6988         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6989   }
6990
6991   // movl and movlp will both match v2i64, but v2i64 is never matched by
6992   // movl earlier because we make it strict to avoid messing with the movlp load
6993   // folding logic (see the code above getMOVLP call). Match it here then,
6994   // this is horrible, but will stay like this until we move all shuffle
6995   // matching to x86 specific nodes. Note that for the 1st condition all
6996   // types are matched with movsd.
6997   if (HasSSE2) {
6998     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6999     // as to remove this logic from here, as much as possible
7000     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7001       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7002     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7003   }
7004
7005   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7006
7007   // Invert the operand order and use SHUFPS to match it.
7008   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7009                               getShuffleSHUFImmediate(SVOp), DAG);
7010 }
7011
7012 // Reduce a vector shuffle to zext.
7013 SDValue
7014 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
7015   // PMOVZX is only available from SSE41.
7016   if (!Subtarget->hasSSE41())
7017     return SDValue();
7018
7019   EVT VT = Op.getValueType();
7020
7021   // Only AVX2 support 256-bit vector integer extending.
7022   if (!Subtarget->hasInt256() && VT.is256BitVector())
7023     return SDValue();
7024
7025   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7026   SDLoc DL(Op);
7027   SDValue V1 = Op.getOperand(0);
7028   SDValue V2 = Op.getOperand(1);
7029   unsigned NumElems = VT.getVectorNumElements();
7030
7031   // Extending is an unary operation and the element type of the source vector
7032   // won't be equal to or larger than i64.
7033   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7034       VT.getVectorElementType() == MVT::i64)
7035     return SDValue();
7036
7037   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7038   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7039   while ((1U << Shift) < NumElems) {
7040     if (SVOp->getMaskElt(1U << Shift) == 1)
7041       break;
7042     Shift += 1;
7043     // The maximal ratio is 8, i.e. from i8 to i64.
7044     if (Shift > 3)
7045       return SDValue();
7046   }
7047
7048   // Check the shuffle mask.
7049   unsigned Mask = (1U << Shift) - 1;
7050   for (unsigned i = 0; i != NumElems; ++i) {
7051     int EltIdx = SVOp->getMaskElt(i);
7052     if ((i & Mask) != 0 && EltIdx != -1)
7053       return SDValue();
7054     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7055       return SDValue();
7056   }
7057
7058   LLVMContext *Context = DAG.getContext();
7059   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7060   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
7061   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
7062
7063   if (!isTypeLegal(NVT))
7064     return SDValue();
7065
7066   // Simplify the operand as it's prepared to be fed into shuffle.
7067   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7068   if (V1.getOpcode() == ISD::BITCAST &&
7069       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7070       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7071       V1.getOperand(0)
7072         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
7073     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7074     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7075     ConstantSDNode *CIdx =
7076       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7077     // If it's foldable, i.e. normal load with single use, we will let code
7078     // selection to fold it. Otherwise, we will short the conversion sequence.
7079     if (CIdx && CIdx->getZExtValue() == 0 &&
7080         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7081       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
7082         // The "ext_vec_elt" node is wider than the result node.
7083         // In this case we should extract subvector from V.
7084         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7085         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
7086         EVT FullVT = V.getValueType();
7087         EVT SubVecVT = EVT::getVectorVT(*Context,
7088                                         FullVT.getVectorElementType(),
7089                                         FullVT.getVectorNumElements()/Ratio);
7090         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7091                         DAG.getIntPtrConstant(0));
7092       }
7093       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
7094     }
7095   }
7096
7097   return DAG.getNode(ISD::BITCAST, DL, VT,
7098                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7099 }
7100
7101 SDValue
7102 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
7103   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7104   MVT VT = Op.getValueType().getSimpleVT();
7105   SDLoc dl(Op);
7106   SDValue V1 = Op.getOperand(0);
7107   SDValue V2 = Op.getOperand(1);
7108
7109   if (isZeroShuffle(SVOp))
7110     return getZeroVector(VT, Subtarget, DAG, dl);
7111
7112   // Handle splat operations
7113   if (SVOp->isSplat()) {
7114     // Use vbroadcast whenever the splat comes from a foldable load
7115     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
7116     if (Broadcast.getNode())
7117       return Broadcast;
7118   }
7119
7120   // Check integer expanding shuffles.
7121   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
7122   if (NewOp.getNode())
7123     return NewOp;
7124
7125   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7126   // do it!
7127   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7128       VT == MVT::v16i16 || VT == MVT::v32i8) {
7129     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7130     if (NewOp.getNode())
7131       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7132   } else if ((VT == MVT::v4i32 ||
7133              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7134     // FIXME: Figure out a cleaner way to do this.
7135     // Try to make use of movq to zero out the top part.
7136     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7137       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7138       if (NewOp.getNode()) {
7139         MVT NewVT = NewOp.getValueType().getSimpleVT();
7140         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7141                                NewVT, true, false))
7142           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7143                               DAG, Subtarget, dl);
7144       }
7145     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7146       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7147       if (NewOp.getNode()) {
7148         MVT NewVT = NewOp.getValueType().getSimpleVT();
7149         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7150           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7151                               DAG, Subtarget, dl);
7152       }
7153     }
7154   }
7155   return SDValue();
7156 }
7157
7158 SDValue
7159 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7160   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7161   SDValue V1 = Op.getOperand(0);
7162   SDValue V2 = Op.getOperand(1);
7163   MVT VT = Op.getValueType().getSimpleVT();
7164   SDLoc dl(Op);
7165   unsigned NumElems = VT.getVectorNumElements();
7166   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7167   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7168   bool V1IsSplat = false;
7169   bool V2IsSplat = false;
7170   bool HasSSE2 = Subtarget->hasSSE2();
7171   bool HasFp256    = Subtarget->hasFp256();
7172   bool HasInt256   = Subtarget->hasInt256();
7173   MachineFunction &MF = DAG.getMachineFunction();
7174   bool OptForSize = MF.getFunction()->getAttributes().
7175     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7176
7177   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7178
7179   if (V1IsUndef && V2IsUndef)
7180     return DAG.getUNDEF(VT);
7181
7182   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7183
7184   // Vector shuffle lowering takes 3 steps:
7185   //
7186   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7187   //    narrowing and commutation of operands should be handled.
7188   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7189   //    shuffle nodes.
7190   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7191   //    so the shuffle can be broken into other shuffles and the legalizer can
7192   //    try the lowering again.
7193   //
7194   // The general idea is that no vector_shuffle operation should be left to
7195   // be matched during isel, all of them must be converted to a target specific
7196   // node here.
7197
7198   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7199   // narrowing and commutation of operands should be handled. The actual code
7200   // doesn't include all of those, work in progress...
7201   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
7202   if (NewOp.getNode())
7203     return NewOp;
7204
7205   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7206
7207   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7208   // unpckh_undef). Only use pshufd if speed is more important than size.
7209   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7210     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7211   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7212     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7213
7214   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7215       V2IsUndef && MayFoldVectorLoad(V1))
7216     return getMOVDDup(Op, dl, V1, DAG);
7217
7218   if (isMOVHLPS_v_undef_Mask(M, VT))
7219     return getMOVHighToLow(Op, dl, DAG);
7220
7221   // Use to match splats
7222   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7223       (VT == MVT::v2f64 || VT == MVT::v2i64))
7224     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7225
7226   if (isPSHUFDMask(M, VT)) {
7227     // The actual implementation will match the mask in the if above and then
7228     // during isel it can match several different instructions, not only pshufd
7229     // as its name says, sad but true, emulate the behavior for now...
7230     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7231       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7232
7233     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7234
7235     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7236       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7237
7238     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7239       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7240                                   DAG);
7241
7242     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7243                                 TargetMask, DAG);
7244   }
7245
7246   if (isPALIGNRMask(M, VT, Subtarget))
7247     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7248                                 getShufflePALIGNRImmediate(SVOp),
7249                                 DAG);
7250
7251   // Check if this can be converted into a logical shift.
7252   bool isLeft = false;
7253   unsigned ShAmt = 0;
7254   SDValue ShVal;
7255   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7256   if (isShift && ShVal.hasOneUse()) {
7257     // If the shifted value has multiple uses, it may be cheaper to use
7258     // v_set0 + movlhps or movhlps, etc.
7259     MVT EltVT = VT.getVectorElementType();
7260     ShAmt *= EltVT.getSizeInBits();
7261     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7262   }
7263
7264   if (isMOVLMask(M, VT)) {
7265     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7266       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7267     if (!isMOVLPMask(M, VT)) {
7268       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7269         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7270
7271       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7272         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7273     }
7274   }
7275
7276   // FIXME: fold these into legal mask.
7277   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7278     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7279
7280   if (isMOVHLPSMask(M, VT))
7281     return getMOVHighToLow(Op, dl, DAG);
7282
7283   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7284     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7285
7286   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7287     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7288
7289   if (isMOVLPMask(M, VT))
7290     return getMOVLP(Op, dl, DAG, HasSSE2);
7291
7292   if (ShouldXformToMOVHLPS(M, VT) ||
7293       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7294     return CommuteVectorShuffle(SVOp, DAG);
7295
7296   if (isShift) {
7297     // No better options. Use a vshldq / vsrldq.
7298     MVT EltVT = VT.getVectorElementType();
7299     ShAmt *= EltVT.getSizeInBits();
7300     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7301   }
7302
7303   bool Commuted = false;
7304   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7305   // 1,1,1,1 -> v8i16 though.
7306   V1IsSplat = isSplatVector(V1.getNode());
7307   V2IsSplat = isSplatVector(V2.getNode());
7308
7309   // Canonicalize the splat or undef, if present, to be on the RHS.
7310   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7311     CommuteVectorShuffleMask(M, NumElems);
7312     std::swap(V1, V2);
7313     std::swap(V1IsSplat, V2IsSplat);
7314     Commuted = true;
7315   }
7316
7317   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7318     // Shuffling low element of v1 into undef, just return v1.
7319     if (V2IsUndef)
7320       return V1;
7321     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7322     // the instruction selector will not match, so get a canonical MOVL with
7323     // swapped operands to undo the commute.
7324     return getMOVL(DAG, dl, VT, V2, V1);
7325   }
7326
7327   if (isUNPCKLMask(M, VT, HasInt256))
7328     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7329
7330   if (isUNPCKHMask(M, VT, HasInt256))
7331     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7332
7333   if (V2IsSplat) {
7334     // Normalize mask so all entries that point to V2 points to its first
7335     // element then try to match unpck{h|l} again. If match, return a
7336     // new vector_shuffle with the corrected mask.p
7337     SmallVector<int, 8> NewMask(M.begin(), M.end());
7338     NormalizeMask(NewMask, NumElems);
7339     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7340       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7341     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7342       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7343   }
7344
7345   if (Commuted) {
7346     // Commute is back and try unpck* again.
7347     // FIXME: this seems wrong.
7348     CommuteVectorShuffleMask(M, NumElems);
7349     std::swap(V1, V2);
7350     std::swap(V1IsSplat, V2IsSplat);
7351     Commuted = false;
7352
7353     if (isUNPCKLMask(M, VT, HasInt256))
7354       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7355
7356     if (isUNPCKHMask(M, VT, HasInt256))
7357       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7358   }
7359
7360   // Normalize the node to match x86 shuffle ops if needed
7361   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7362     return CommuteVectorShuffle(SVOp, DAG);
7363
7364   // The checks below are all present in isShuffleMaskLegal, but they are
7365   // inlined here right now to enable us to directly emit target specific
7366   // nodes, and remove one by one until they don't return Op anymore.
7367
7368   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7369       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7370     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7371       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7372   }
7373
7374   if (isPSHUFHWMask(M, VT, HasInt256))
7375     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7376                                 getShufflePSHUFHWImmediate(SVOp),
7377                                 DAG);
7378
7379   if (isPSHUFLWMask(M, VT, HasInt256))
7380     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7381                                 getShufflePSHUFLWImmediate(SVOp),
7382                                 DAG);
7383
7384   if (isSHUFPMask(M, VT, HasFp256))
7385     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7386                                 getShuffleSHUFImmediate(SVOp), DAG);
7387
7388   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7389     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7390   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7391     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7392
7393   //===--------------------------------------------------------------------===//
7394   // Generate target specific nodes for 128 or 256-bit shuffles only
7395   // supported in the AVX instruction set.
7396   //
7397
7398   // Handle VMOVDDUPY permutations
7399   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7400     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7401
7402   // Handle VPERMILPS/D* permutations
7403   if (isVPERMILPMask(M, VT, HasFp256)) {
7404     if (HasInt256 && VT == MVT::v8i32)
7405       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7406                                   getShuffleSHUFImmediate(SVOp), DAG);
7407     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7408                                 getShuffleSHUFImmediate(SVOp), DAG);
7409   }
7410
7411   // Handle VPERM2F128/VPERM2I128 permutations
7412   if (isVPERM2X128Mask(M, VT, HasFp256))
7413     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7414                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7415
7416   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7417   if (BlendOp.getNode())
7418     return BlendOp;
7419
7420   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7421     SmallVector<SDValue, 8> permclMask;
7422     for (unsigned i = 0; i != 8; ++i) {
7423       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7424     }
7425     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7426                                &permclMask[0], 8);
7427     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7428     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7429                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7430   }
7431
7432   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7433     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7434                                 getShuffleCLImmediate(SVOp), DAG);
7435
7436   //===--------------------------------------------------------------------===//
7437   // Since no target specific shuffle was selected for this generic one,
7438   // lower it into other known shuffles. FIXME: this isn't true yet, but
7439   // this is the plan.
7440   //
7441
7442   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7443   if (VT == MVT::v8i16) {
7444     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7445     if (NewOp.getNode())
7446       return NewOp;
7447   }
7448
7449   if (VT == MVT::v16i8) {
7450     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7451     if (NewOp.getNode())
7452       return NewOp;
7453   }
7454
7455   if (VT == MVT::v32i8) {
7456     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7457     if (NewOp.getNode())
7458       return NewOp;
7459   }
7460
7461   // Handle all 128-bit wide vectors with 4 elements, and match them with
7462   // several different shuffle types.
7463   if (NumElems == 4 && VT.is128BitVector())
7464     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7465
7466   // Handle general 256-bit shuffles
7467   if (VT.is256BitVector())
7468     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7469
7470   return SDValue();
7471 }
7472
7473 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7474   MVT VT = Op.getValueType().getSimpleVT();
7475   SDLoc dl(Op);
7476
7477   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7478     return SDValue();
7479
7480   if (VT.getSizeInBits() == 8) {
7481     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7482                                   Op.getOperand(0), Op.getOperand(1));
7483     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7484                                   DAG.getValueType(VT));
7485     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7486   }
7487
7488   if (VT.getSizeInBits() == 16) {
7489     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7490     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7491     if (Idx == 0)
7492       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7493                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7494                                      DAG.getNode(ISD::BITCAST, dl,
7495                                                  MVT::v4i32,
7496                                                  Op.getOperand(0)),
7497                                      Op.getOperand(1)));
7498     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7499                                   Op.getOperand(0), Op.getOperand(1));
7500     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7501                                   DAG.getValueType(VT));
7502     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7503   }
7504
7505   if (VT == MVT::f32) {
7506     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7507     // the result back to FR32 register. It's only worth matching if the
7508     // result has a single use which is a store or a bitcast to i32.  And in
7509     // the case of a store, it's not worth it if the index is a constant 0,
7510     // because a MOVSSmr can be used instead, which is smaller and faster.
7511     if (!Op.hasOneUse())
7512       return SDValue();
7513     SDNode *User = *Op.getNode()->use_begin();
7514     if ((User->getOpcode() != ISD::STORE ||
7515          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7516           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7517         (User->getOpcode() != ISD::BITCAST ||
7518          User->getValueType(0) != MVT::i32))
7519       return SDValue();
7520     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7521                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7522                                               Op.getOperand(0)),
7523                                               Op.getOperand(1));
7524     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7525   }
7526
7527   if (VT == MVT::i32 || VT == MVT::i64) {
7528     // ExtractPS/pextrq works with constant index.
7529     if (isa<ConstantSDNode>(Op.getOperand(1)))
7530       return Op;
7531   }
7532   return SDValue();
7533 }
7534
7535 SDValue
7536 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7537                                            SelectionDAG &DAG) const {
7538   SDLoc dl(Op);
7539   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7540     return SDValue();
7541
7542   SDValue Vec = Op.getOperand(0);
7543   MVT VecVT = Vec.getValueType().getSimpleVT();
7544
7545   // If this is a 256-bit vector result, first extract the 128-bit vector and
7546   // then extract the element from the 128-bit vector.
7547   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7548     SDValue Idx = Op.getOperand(1);
7549     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7550
7551     // Get the 128-bit vector.
7552     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7553     EVT EltVT = VecVT.getVectorElementType();
7554
7555     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7556
7557     //if (IdxVal >= NumElems/2)
7558     //  IdxVal -= NumElems/2;
7559     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7560     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7561                        DAG.getConstant(IdxVal, MVT::i32));
7562   }
7563
7564   assert(VecVT.is128BitVector() && "Unexpected vector length");
7565
7566   if (Subtarget->hasSSE41()) {
7567     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7568     if (Res.getNode())
7569       return Res;
7570   }
7571
7572   MVT VT = Op.getValueType().getSimpleVT();
7573   // TODO: handle v16i8.
7574   if (VT.getSizeInBits() == 16) {
7575     SDValue Vec = Op.getOperand(0);
7576     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7577     if (Idx == 0)
7578       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7579                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7580                                      DAG.getNode(ISD::BITCAST, dl,
7581                                                  MVT::v4i32, Vec),
7582                                      Op.getOperand(1)));
7583     // Transform it so it match pextrw which produces a 32-bit result.
7584     MVT EltVT = MVT::i32;
7585     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7586                                   Op.getOperand(0), Op.getOperand(1));
7587     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7588                                   DAG.getValueType(VT));
7589     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7590   }
7591
7592   if (VT.getSizeInBits() == 32) {
7593     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7594     if (Idx == 0)
7595       return Op;
7596
7597     // SHUFPS the element to the lowest double word, then movss.
7598     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7599     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7600     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7601                                        DAG.getUNDEF(VVT), Mask);
7602     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7603                        DAG.getIntPtrConstant(0));
7604   }
7605
7606   if (VT.getSizeInBits() == 64) {
7607     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7608     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7609     //        to match extract_elt for f64.
7610     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7611     if (Idx == 0)
7612       return Op;
7613
7614     // UNPCKHPD the element to the lowest double word, then movsd.
7615     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7616     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7617     int Mask[2] = { 1, -1 };
7618     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7619     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7620                                        DAG.getUNDEF(VVT), Mask);
7621     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7622                        DAG.getIntPtrConstant(0));
7623   }
7624
7625   return SDValue();
7626 }
7627
7628 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7629   MVT VT = Op.getValueType().getSimpleVT();
7630   MVT EltVT = VT.getVectorElementType();
7631   SDLoc dl(Op);
7632
7633   SDValue N0 = Op.getOperand(0);
7634   SDValue N1 = Op.getOperand(1);
7635   SDValue N2 = Op.getOperand(2);
7636
7637   if (!VT.is128BitVector())
7638     return SDValue();
7639
7640   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7641       isa<ConstantSDNode>(N2)) {
7642     unsigned Opc;
7643     if (VT == MVT::v8i16)
7644       Opc = X86ISD::PINSRW;
7645     else if (VT == MVT::v16i8)
7646       Opc = X86ISD::PINSRB;
7647     else
7648       Opc = X86ISD::PINSRB;
7649
7650     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7651     // argument.
7652     if (N1.getValueType() != MVT::i32)
7653       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7654     if (N2.getValueType() != MVT::i32)
7655       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7656     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7657   }
7658
7659   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7660     // Bits [7:6] of the constant are the source select.  This will always be
7661     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7662     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7663     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7664     // Bits [5:4] of the constant are the destination select.  This is the
7665     //  value of the incoming immediate.
7666     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7667     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7668     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7669     // Create this as a scalar to vector..
7670     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7671     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7672   }
7673
7674   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7675     // PINSR* works with constant index.
7676     return Op;
7677   }
7678   return SDValue();
7679 }
7680
7681 SDValue
7682 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7683   MVT VT = Op.getValueType().getSimpleVT();
7684   MVT EltVT = VT.getVectorElementType();
7685
7686   SDLoc dl(Op);
7687   SDValue N0 = Op.getOperand(0);
7688   SDValue N1 = Op.getOperand(1);
7689   SDValue N2 = Op.getOperand(2);
7690
7691   // If this is a 256-bit vector result, first extract the 128-bit vector,
7692   // insert the element into the extracted half and then place it back.
7693   if (VT.is256BitVector() || VT.is512BitVector()) {
7694     if (!isa<ConstantSDNode>(N2))
7695       return SDValue();
7696
7697     // Get the desired 128-bit vector half.
7698     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7699     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7700
7701     // Insert the element into the desired half.
7702     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7703     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7704
7705     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7706                     DAG.getConstant(IdxIn128, MVT::i32));
7707
7708     // Insert the changed part back to the 256-bit vector
7709     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7710   }
7711
7712   if (Subtarget->hasSSE41())
7713     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7714
7715   if (EltVT == MVT::i8)
7716     return SDValue();
7717
7718   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7719     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7720     // as its second argument.
7721     if (N1.getValueType() != MVT::i32)
7722       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7723     if (N2.getValueType() != MVT::i32)
7724       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7725     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7726   }
7727   return SDValue();
7728 }
7729
7730 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7731   LLVMContext *Context = DAG.getContext();
7732   SDLoc dl(Op);
7733   MVT OpVT = Op.getValueType().getSimpleVT();
7734
7735   // If this is a 256-bit vector result, first insert into a 128-bit
7736   // vector and then insert into the 256-bit vector.
7737   if (!OpVT.is128BitVector()) {
7738     // Insert into a 128-bit vector.
7739     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7740     EVT VT128 = EVT::getVectorVT(*Context,
7741                                  OpVT.getVectorElementType(),
7742                                  OpVT.getVectorNumElements() / SizeFactor);
7743
7744     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7745
7746     // Insert the 128-bit vector.
7747     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7748   }
7749
7750   if (OpVT == MVT::v1i64 &&
7751       Op.getOperand(0).getValueType() == MVT::i64)
7752     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7753
7754   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7755   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7756   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7757                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7758 }
7759
7760 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7761 // a simple subregister reference or explicit instructions to grab
7762 // upper bits of a vector.
7763 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7764                                       SelectionDAG &DAG) {
7765   SDLoc dl(Op);
7766   SDValue In =  Op.getOperand(0);
7767   SDValue Idx = Op.getOperand(1);
7768   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7769   EVT ResVT   = Op.getValueType();
7770   EVT InVT    = In.getValueType();
7771
7772   if (Subtarget->hasFp256()) {
7773     if (ResVT.is128BitVector() &&
7774         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7775         isa<ConstantSDNode>(Idx)) {
7776       return Extract128BitVector(In, IdxVal, DAG, dl);
7777     }
7778     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7779         isa<ConstantSDNode>(Idx)) {
7780       return Extract256BitVector(In, IdxVal, DAG, dl);
7781     }
7782   }
7783   return SDValue();
7784 }
7785
7786 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7787 // simple superregister reference or explicit instructions to insert
7788 // the upper bits of a vector.
7789 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7790                                      SelectionDAG &DAG) {
7791   if (Subtarget->hasFp256()) {
7792     SDLoc dl(Op.getNode());
7793     SDValue Vec = Op.getNode()->getOperand(0);
7794     SDValue SubVec = Op.getNode()->getOperand(1);
7795     SDValue Idx = Op.getNode()->getOperand(2);
7796
7797     if ((Op.getNode()->getValueType(0).is256BitVector() ||
7798          Op.getNode()->getValueType(0).is512BitVector()) &&
7799         SubVec.getNode()->getValueType(0).is128BitVector() &&
7800         isa<ConstantSDNode>(Idx)) {
7801       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7802       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7803     }
7804
7805     if (Op.getNode()->getValueType(0).is512BitVector() &&
7806         SubVec.getNode()->getValueType(0).is256BitVector() &&
7807         isa<ConstantSDNode>(Idx)) {
7808       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7809       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7810     }
7811   }
7812   return SDValue();
7813 }
7814
7815 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7816 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7817 // one of the above mentioned nodes. It has to be wrapped because otherwise
7818 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7819 // be used to form addressing mode. These wrapped nodes will be selected
7820 // into MOV32ri.
7821 SDValue
7822 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7823   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7824
7825   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7826   // global base reg.
7827   unsigned char OpFlag = 0;
7828   unsigned WrapperKind = X86ISD::Wrapper;
7829   CodeModel::Model M = getTargetMachine().getCodeModel();
7830
7831   if (Subtarget->isPICStyleRIPRel() &&
7832       (M == CodeModel::Small || M == CodeModel::Kernel))
7833     WrapperKind = X86ISD::WrapperRIP;
7834   else if (Subtarget->isPICStyleGOT())
7835     OpFlag = X86II::MO_GOTOFF;
7836   else if (Subtarget->isPICStyleStubPIC())
7837     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7838
7839   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7840                                              CP->getAlignment(),
7841                                              CP->getOffset(), OpFlag);
7842   SDLoc DL(CP);
7843   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7844   // With PIC, the address is actually $g + Offset.
7845   if (OpFlag) {
7846     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7847                          DAG.getNode(X86ISD::GlobalBaseReg,
7848                                      SDLoc(), getPointerTy()),
7849                          Result);
7850   }
7851
7852   return Result;
7853 }
7854
7855 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7856   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7857
7858   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7859   // global base reg.
7860   unsigned char OpFlag = 0;
7861   unsigned WrapperKind = X86ISD::Wrapper;
7862   CodeModel::Model M = getTargetMachine().getCodeModel();
7863
7864   if (Subtarget->isPICStyleRIPRel() &&
7865       (M == CodeModel::Small || M == CodeModel::Kernel))
7866     WrapperKind = X86ISD::WrapperRIP;
7867   else if (Subtarget->isPICStyleGOT())
7868     OpFlag = X86II::MO_GOTOFF;
7869   else if (Subtarget->isPICStyleStubPIC())
7870     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7871
7872   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7873                                           OpFlag);
7874   SDLoc DL(JT);
7875   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7876
7877   // With PIC, the address is actually $g + Offset.
7878   if (OpFlag)
7879     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7880                          DAG.getNode(X86ISD::GlobalBaseReg,
7881                                      SDLoc(), getPointerTy()),
7882                          Result);
7883
7884   return Result;
7885 }
7886
7887 SDValue
7888 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7889   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7890
7891   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7892   // global base reg.
7893   unsigned char OpFlag = 0;
7894   unsigned WrapperKind = X86ISD::Wrapper;
7895   CodeModel::Model M = getTargetMachine().getCodeModel();
7896
7897   if (Subtarget->isPICStyleRIPRel() &&
7898       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7899     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7900       OpFlag = X86II::MO_GOTPCREL;
7901     WrapperKind = X86ISD::WrapperRIP;
7902   } else if (Subtarget->isPICStyleGOT()) {
7903     OpFlag = X86II::MO_GOT;
7904   } else if (Subtarget->isPICStyleStubPIC()) {
7905     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7906   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7907     OpFlag = X86II::MO_DARWIN_NONLAZY;
7908   }
7909
7910   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7911
7912   SDLoc DL(Op);
7913   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7914
7915   // With PIC, the address is actually $g + Offset.
7916   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7917       !Subtarget->is64Bit()) {
7918     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7919                          DAG.getNode(X86ISD::GlobalBaseReg,
7920                                      SDLoc(), getPointerTy()),
7921                          Result);
7922   }
7923
7924   // For symbols that require a load from a stub to get the address, emit the
7925   // load.
7926   if (isGlobalStubReference(OpFlag))
7927     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7928                          MachinePointerInfo::getGOT(), false, false, false, 0);
7929
7930   return Result;
7931 }
7932
7933 SDValue
7934 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7935   // Create the TargetBlockAddressAddress node.
7936   unsigned char OpFlags =
7937     Subtarget->ClassifyBlockAddressReference();
7938   CodeModel::Model M = getTargetMachine().getCodeModel();
7939   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7940   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7941   SDLoc dl(Op);
7942   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7943                                              OpFlags);
7944
7945   if (Subtarget->isPICStyleRIPRel() &&
7946       (M == CodeModel::Small || M == CodeModel::Kernel))
7947     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7948   else
7949     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7950
7951   // With PIC, the address is actually $g + Offset.
7952   if (isGlobalRelativeToPICBase(OpFlags)) {
7953     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7954                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7955                          Result);
7956   }
7957
7958   return Result;
7959 }
7960
7961 SDValue
7962 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7963                                       int64_t Offset, SelectionDAG &DAG) const {
7964   // Create the TargetGlobalAddress node, folding in the constant
7965   // offset if it is legal.
7966   unsigned char OpFlags =
7967     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7968   CodeModel::Model M = getTargetMachine().getCodeModel();
7969   SDValue Result;
7970   if (OpFlags == X86II::MO_NO_FLAG &&
7971       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7972     // A direct static reference to a global.
7973     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7974     Offset = 0;
7975   } else {
7976     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7977   }
7978
7979   if (Subtarget->isPICStyleRIPRel() &&
7980       (M == CodeModel::Small || M == CodeModel::Kernel))
7981     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7982   else
7983     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7984
7985   // With PIC, the address is actually $g + Offset.
7986   if (isGlobalRelativeToPICBase(OpFlags)) {
7987     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7988                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7989                          Result);
7990   }
7991
7992   // For globals that require a load from a stub to get the address, emit the
7993   // load.
7994   if (isGlobalStubReference(OpFlags))
7995     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7996                          MachinePointerInfo::getGOT(), false, false, false, 0);
7997
7998   // If there was a non-zero offset that we didn't fold, create an explicit
7999   // addition for it.
8000   if (Offset != 0)
8001     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8002                          DAG.getConstant(Offset, getPointerTy()));
8003
8004   return Result;
8005 }
8006
8007 SDValue
8008 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8009   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8010   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8011   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8012 }
8013
8014 static SDValue
8015 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8016            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8017            unsigned char OperandFlags, bool LocalDynamic = false) {
8018   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8019   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8020   SDLoc dl(GA);
8021   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8022                                            GA->getValueType(0),
8023                                            GA->getOffset(),
8024                                            OperandFlags);
8025
8026   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8027                                            : X86ISD::TLSADDR;
8028
8029   if (InFlag) {
8030     SDValue Ops[] = { Chain,  TGA, *InFlag };
8031     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8032   } else {
8033     SDValue Ops[]  = { Chain, TGA };
8034     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8035   }
8036
8037   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8038   MFI->setAdjustsStack(true);
8039
8040   SDValue Flag = Chain.getValue(1);
8041   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8042 }
8043
8044 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8045 static SDValue
8046 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8047                                 const EVT PtrVT) {
8048   SDValue InFlag;
8049   SDLoc dl(GA);  // ? function entry point might be better
8050   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8051                                    DAG.getNode(X86ISD::GlobalBaseReg,
8052                                                SDLoc(), PtrVT), InFlag);
8053   InFlag = Chain.getValue(1);
8054
8055   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8056 }
8057
8058 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8059 static SDValue
8060 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8061                                 const EVT PtrVT) {
8062   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8063                     X86::RAX, X86II::MO_TLSGD);
8064 }
8065
8066 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8067                                            SelectionDAG &DAG,
8068                                            const EVT PtrVT,
8069                                            bool is64Bit) {
8070   SDLoc dl(GA);
8071
8072   // Get the start address of the TLS block for this module.
8073   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8074       .getInfo<X86MachineFunctionInfo>();
8075   MFI->incNumLocalDynamicTLSAccesses();
8076
8077   SDValue Base;
8078   if (is64Bit) {
8079     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8080                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8081   } else {
8082     SDValue InFlag;
8083     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8084         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8085     InFlag = Chain.getValue(1);
8086     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8087                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8088   }
8089
8090   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8091   // of Base.
8092
8093   // Build x@dtpoff.
8094   unsigned char OperandFlags = X86II::MO_DTPOFF;
8095   unsigned WrapperKind = X86ISD::Wrapper;
8096   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8097                                            GA->getValueType(0),
8098                                            GA->getOffset(), OperandFlags);
8099   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8100
8101   // Add x@dtpoff with the base.
8102   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8103 }
8104
8105 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8106 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8107                                    const EVT PtrVT, TLSModel::Model model,
8108                                    bool is64Bit, bool isPIC) {
8109   SDLoc dl(GA);
8110
8111   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8112   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8113                                                          is64Bit ? 257 : 256));
8114
8115   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8116                                       DAG.getIntPtrConstant(0),
8117                                       MachinePointerInfo(Ptr),
8118                                       false, false, false, 0);
8119
8120   unsigned char OperandFlags = 0;
8121   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8122   // initialexec.
8123   unsigned WrapperKind = X86ISD::Wrapper;
8124   if (model == TLSModel::LocalExec) {
8125     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8126   } else if (model == TLSModel::InitialExec) {
8127     if (is64Bit) {
8128       OperandFlags = X86II::MO_GOTTPOFF;
8129       WrapperKind = X86ISD::WrapperRIP;
8130     } else {
8131       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8132     }
8133   } else {
8134     llvm_unreachable("Unexpected model");
8135   }
8136
8137   // emit "addl x@ntpoff,%eax" (local exec)
8138   // or "addl x@indntpoff,%eax" (initial exec)
8139   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8140   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8141                                            GA->getValueType(0),
8142                                            GA->getOffset(), OperandFlags);
8143   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8144
8145   if (model == TLSModel::InitialExec) {
8146     if (isPIC && !is64Bit) {
8147       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8148                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8149                            Offset);
8150     }
8151
8152     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8153                          MachinePointerInfo::getGOT(), false, false, false,
8154                          0);
8155   }
8156
8157   // The address of the thread local variable is the add of the thread
8158   // pointer with the offset of the variable.
8159   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8160 }
8161
8162 SDValue
8163 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8164
8165   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8166   const GlobalValue *GV = GA->getGlobal();
8167
8168   if (Subtarget->isTargetELF()) {
8169     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8170
8171     switch (model) {
8172       case TLSModel::GeneralDynamic:
8173         if (Subtarget->is64Bit())
8174           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8175         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8176       case TLSModel::LocalDynamic:
8177         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8178                                            Subtarget->is64Bit());
8179       case TLSModel::InitialExec:
8180       case TLSModel::LocalExec:
8181         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8182                                    Subtarget->is64Bit(),
8183                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8184     }
8185     llvm_unreachable("Unknown TLS model.");
8186   }
8187
8188   if (Subtarget->isTargetDarwin()) {
8189     // Darwin only has one model of TLS.  Lower to that.
8190     unsigned char OpFlag = 0;
8191     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8192                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8193
8194     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8195     // global base reg.
8196     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8197                   !Subtarget->is64Bit();
8198     if (PIC32)
8199       OpFlag = X86II::MO_TLVP_PIC_BASE;
8200     else
8201       OpFlag = X86II::MO_TLVP;
8202     SDLoc DL(Op);
8203     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8204                                                 GA->getValueType(0),
8205                                                 GA->getOffset(), OpFlag);
8206     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8207
8208     // With PIC32, the address is actually $g + Offset.
8209     if (PIC32)
8210       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8211                            DAG.getNode(X86ISD::GlobalBaseReg,
8212                                        SDLoc(), getPointerTy()),
8213                            Offset);
8214
8215     // Lowering the machine isd will make sure everything is in the right
8216     // location.
8217     SDValue Chain = DAG.getEntryNode();
8218     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8219     SDValue Args[] = { Chain, Offset };
8220     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8221
8222     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8223     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8224     MFI->setAdjustsStack(true);
8225
8226     // And our return value (tls address) is in the standard call return value
8227     // location.
8228     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8229     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8230                               Chain.getValue(1));
8231   }
8232
8233   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8234     // Just use the implicit TLS architecture
8235     // Need to generate someting similar to:
8236     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8237     //                                  ; from TEB
8238     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8239     //   mov     rcx, qword [rdx+rcx*8]
8240     //   mov     eax, .tls$:tlsvar
8241     //   [rax+rcx] contains the address
8242     // Windows 64bit: gs:0x58
8243     // Windows 32bit: fs:__tls_array
8244
8245     // If GV is an alias then use the aliasee for determining
8246     // thread-localness.
8247     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8248       GV = GA->resolveAliasedGlobal(false);
8249     SDLoc dl(GA);
8250     SDValue Chain = DAG.getEntryNode();
8251
8252     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8253     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8254     // use its literal value of 0x2C.
8255     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8256                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8257                                                              256)
8258                                         : Type::getInt32PtrTy(*DAG.getContext(),
8259                                                               257));
8260
8261     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8262       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8263         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8264
8265     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8266                                         MachinePointerInfo(Ptr),
8267                                         false, false, false, 0);
8268
8269     // Load the _tls_index variable
8270     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8271     if (Subtarget->is64Bit())
8272       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8273                            IDX, MachinePointerInfo(), MVT::i32,
8274                            false, false, 0);
8275     else
8276       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8277                         false, false, false, 0);
8278
8279     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8280                                     getPointerTy());
8281     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8282
8283     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8284     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8285                       false, false, false, 0);
8286
8287     // Get the offset of start of .tls section
8288     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8289                                              GA->getValueType(0),
8290                                              GA->getOffset(), X86II::MO_SECREL);
8291     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8292
8293     // The address of the thread local variable is the add of the thread
8294     // pointer with the offset of the variable.
8295     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8296   }
8297
8298   llvm_unreachable("TLS not implemented for this target.");
8299 }
8300
8301 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8302 /// and take a 2 x i32 value to shift plus a shift amount.
8303 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8304   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8305   EVT VT = Op.getValueType();
8306   unsigned VTBits = VT.getSizeInBits();
8307   SDLoc dl(Op);
8308   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8309   SDValue ShOpLo = Op.getOperand(0);
8310   SDValue ShOpHi = Op.getOperand(1);
8311   SDValue ShAmt  = Op.getOperand(2);
8312   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8313                                      DAG.getConstant(VTBits - 1, MVT::i8))
8314                        : DAG.getConstant(0, VT);
8315
8316   SDValue Tmp2, Tmp3;
8317   if (Op.getOpcode() == ISD::SHL_PARTS) {
8318     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8319     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8320   } else {
8321     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8322     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8323   }
8324
8325   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8326                                 DAG.getConstant(VTBits, MVT::i8));
8327   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8328                              AndNode, DAG.getConstant(0, MVT::i8));
8329
8330   SDValue Hi, Lo;
8331   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8332   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8333   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8334
8335   if (Op.getOpcode() == ISD::SHL_PARTS) {
8336     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8337     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8338   } else {
8339     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8340     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8341   }
8342
8343   SDValue Ops[2] = { Lo, Hi };
8344   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8345 }
8346
8347 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8348                                            SelectionDAG &DAG) const {
8349   EVT SrcVT = Op.getOperand(0).getValueType();
8350
8351   if (SrcVT.isVector())
8352     return SDValue();
8353
8354   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8355          "Unknown SINT_TO_FP to lower!");
8356
8357   // These are really Legal; return the operand so the caller accepts it as
8358   // Legal.
8359   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8360     return Op;
8361   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8362       Subtarget->is64Bit()) {
8363     return Op;
8364   }
8365
8366   SDLoc dl(Op);
8367   unsigned Size = SrcVT.getSizeInBits()/8;
8368   MachineFunction &MF = DAG.getMachineFunction();
8369   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8370   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8371   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8372                                StackSlot,
8373                                MachinePointerInfo::getFixedStack(SSFI),
8374                                false, false, 0);
8375   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8376 }
8377
8378 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8379                                      SDValue StackSlot,
8380                                      SelectionDAG &DAG) const {
8381   // Build the FILD
8382   SDLoc DL(Op);
8383   SDVTList Tys;
8384   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8385   if (useSSE)
8386     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8387   else
8388     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8389
8390   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8391
8392   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8393   MachineMemOperand *MMO;
8394   if (FI) {
8395     int SSFI = FI->getIndex();
8396     MMO =
8397       DAG.getMachineFunction()
8398       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8399                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8400   } else {
8401     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8402     StackSlot = StackSlot.getOperand(1);
8403   }
8404   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8405   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8406                                            X86ISD::FILD, DL,
8407                                            Tys, Ops, array_lengthof(Ops),
8408                                            SrcVT, MMO);
8409
8410   if (useSSE) {
8411     Chain = Result.getValue(1);
8412     SDValue InFlag = Result.getValue(2);
8413
8414     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8415     // shouldn't be necessary except that RFP cannot be live across
8416     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8417     MachineFunction &MF = DAG.getMachineFunction();
8418     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8419     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8420     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8421     Tys = DAG.getVTList(MVT::Other);
8422     SDValue Ops[] = {
8423       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8424     };
8425     MachineMemOperand *MMO =
8426       DAG.getMachineFunction()
8427       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8428                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8429
8430     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8431                                     Ops, array_lengthof(Ops),
8432                                     Op.getValueType(), MMO);
8433     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8434                          MachinePointerInfo::getFixedStack(SSFI),
8435                          false, false, false, 0);
8436   }
8437
8438   return Result;
8439 }
8440
8441 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8442 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8443                                                SelectionDAG &DAG) const {
8444   // This algorithm is not obvious. Here it is what we're trying to output:
8445   /*
8446      movq       %rax,  %xmm0
8447      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8448      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8449      #ifdef __SSE3__
8450        haddpd   %xmm0, %xmm0
8451      #else
8452        pshufd   $0x4e, %xmm0, %xmm1
8453        addpd    %xmm1, %xmm0
8454      #endif
8455   */
8456
8457   SDLoc dl(Op);
8458   LLVMContext *Context = DAG.getContext();
8459
8460   // Build some magic constants.
8461   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8462   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8463   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8464
8465   SmallVector<Constant*,2> CV1;
8466   CV1.push_back(
8467     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8468                                       APInt(64, 0x4330000000000000ULL))));
8469   CV1.push_back(
8470     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8471                                       APInt(64, 0x4530000000000000ULL))));
8472   Constant *C1 = ConstantVector::get(CV1);
8473   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8474
8475   // Load the 64-bit value into an XMM register.
8476   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8477                             Op.getOperand(0));
8478   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8479                               MachinePointerInfo::getConstantPool(),
8480                               false, false, false, 16);
8481   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8482                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8483                               CLod0);
8484
8485   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8486                               MachinePointerInfo::getConstantPool(),
8487                               false, false, false, 16);
8488   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8489   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8490   SDValue Result;
8491
8492   if (Subtarget->hasSSE3()) {
8493     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8494     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8495   } else {
8496     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8497     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8498                                            S2F, 0x4E, DAG);
8499     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8500                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8501                          Sub);
8502   }
8503
8504   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8505                      DAG.getIntPtrConstant(0));
8506 }
8507
8508 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8509 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8510                                                SelectionDAG &DAG) const {
8511   SDLoc dl(Op);
8512   // FP constant to bias correct the final result.
8513   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8514                                    MVT::f64);
8515
8516   // Load the 32-bit value into an XMM register.
8517   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8518                              Op.getOperand(0));
8519
8520   // Zero out the upper parts of the register.
8521   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8522
8523   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8524                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8525                      DAG.getIntPtrConstant(0));
8526
8527   // Or the load with the bias.
8528   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8529                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8530                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8531                                                    MVT::v2f64, Load)),
8532                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8533                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8534                                                    MVT::v2f64, Bias)));
8535   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8536                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8537                    DAG.getIntPtrConstant(0));
8538
8539   // Subtract the bias.
8540   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8541
8542   // Handle final rounding.
8543   EVT DestVT = Op.getValueType();
8544
8545   if (DestVT.bitsLT(MVT::f64))
8546     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8547                        DAG.getIntPtrConstant(0));
8548   if (DestVT.bitsGT(MVT::f64))
8549     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8550
8551   // Handle final rounding.
8552   return Sub;
8553 }
8554
8555 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8556                                                SelectionDAG &DAG) const {
8557   SDValue N0 = Op.getOperand(0);
8558   EVT SVT = N0.getValueType();
8559   SDLoc dl(Op);
8560
8561   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8562           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8563          "Custom UINT_TO_FP is not supported!");
8564
8565   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8566                              SVT.getVectorNumElements());
8567   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8568                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8569 }
8570
8571 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8572                                            SelectionDAG &DAG) const {
8573   SDValue N0 = Op.getOperand(0);
8574   SDLoc dl(Op);
8575
8576   if (Op.getValueType().isVector())
8577     return lowerUINT_TO_FP_vec(Op, DAG);
8578
8579   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8580   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8581   // the optimization here.
8582   if (DAG.SignBitIsZero(N0))
8583     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8584
8585   EVT SrcVT = N0.getValueType();
8586   EVT DstVT = Op.getValueType();
8587   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8588     return LowerUINT_TO_FP_i64(Op, DAG);
8589   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8590     return LowerUINT_TO_FP_i32(Op, DAG);
8591   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8592     return SDValue();
8593
8594   // Make a 64-bit buffer, and use it to build an FILD.
8595   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8596   if (SrcVT == MVT::i32) {
8597     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8598     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8599                                      getPointerTy(), StackSlot, WordOff);
8600     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8601                                   StackSlot, MachinePointerInfo(),
8602                                   false, false, 0);
8603     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8604                                   OffsetSlot, MachinePointerInfo(),
8605                                   false, false, 0);
8606     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8607     return Fild;
8608   }
8609
8610   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8611   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8612                                StackSlot, MachinePointerInfo(),
8613                                false, false, 0);
8614   // For i64 source, we need to add the appropriate power of 2 if the input
8615   // was negative.  This is the same as the optimization in
8616   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8617   // we must be careful to do the computation in x87 extended precision, not
8618   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8619   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8620   MachineMemOperand *MMO =
8621     DAG.getMachineFunction()
8622     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8623                           MachineMemOperand::MOLoad, 8, 8);
8624
8625   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8626   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8627   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8628                                          array_lengthof(Ops), MVT::i64, MMO);
8629
8630   APInt FF(32, 0x5F800000ULL);
8631
8632   // Check whether the sign bit is set.
8633   SDValue SignSet = DAG.getSetCC(dl,
8634                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8635                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8636                                  ISD::SETLT);
8637
8638   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8639   SDValue FudgePtr = DAG.getConstantPool(
8640                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8641                                          getPointerTy());
8642
8643   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8644   SDValue Zero = DAG.getIntPtrConstant(0);
8645   SDValue Four = DAG.getIntPtrConstant(4);
8646   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8647                                Zero, Four);
8648   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8649
8650   // Load the value out, extending it from f32 to f80.
8651   // FIXME: Avoid the extend by constructing the right constant pool?
8652   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8653                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8654                                  MVT::f32, false, false, 4);
8655   // Extend everything to 80 bits to force it to be done on x87.
8656   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8657   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8658 }
8659
8660 std::pair<SDValue,SDValue>
8661 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8662                                     bool IsSigned, bool IsReplace) const {
8663   SDLoc DL(Op);
8664
8665   EVT DstTy = Op.getValueType();
8666
8667   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8668     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8669     DstTy = MVT::i64;
8670   }
8671
8672   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8673          DstTy.getSimpleVT() >= MVT::i16 &&
8674          "Unknown FP_TO_INT to lower!");
8675
8676   // These are really Legal.
8677   if (DstTy == MVT::i32 &&
8678       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8679     return std::make_pair(SDValue(), SDValue());
8680   if (Subtarget->is64Bit() &&
8681       DstTy == MVT::i64 &&
8682       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8683     return std::make_pair(SDValue(), SDValue());
8684
8685   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8686   // stack slot, or into the FTOL runtime function.
8687   MachineFunction &MF = DAG.getMachineFunction();
8688   unsigned MemSize = DstTy.getSizeInBits()/8;
8689   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8690   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8691
8692   unsigned Opc;
8693   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8694     Opc = X86ISD::WIN_FTOL;
8695   else
8696     switch (DstTy.getSimpleVT().SimpleTy) {
8697     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8698     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8699     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8700     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8701     }
8702
8703   SDValue Chain = DAG.getEntryNode();
8704   SDValue Value = Op.getOperand(0);
8705   EVT TheVT = Op.getOperand(0).getValueType();
8706   // FIXME This causes a redundant load/store if the SSE-class value is already
8707   // in memory, such as if it is on the callstack.
8708   if (isScalarFPTypeInSSEReg(TheVT)) {
8709     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8710     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8711                          MachinePointerInfo::getFixedStack(SSFI),
8712                          false, false, 0);
8713     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8714     SDValue Ops[] = {
8715       Chain, StackSlot, DAG.getValueType(TheVT)
8716     };
8717
8718     MachineMemOperand *MMO =
8719       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8720                               MachineMemOperand::MOLoad, MemSize, MemSize);
8721     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8722                                     array_lengthof(Ops), DstTy, MMO);
8723     Chain = Value.getValue(1);
8724     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8725     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8726   }
8727
8728   MachineMemOperand *MMO =
8729     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8730                             MachineMemOperand::MOStore, MemSize, MemSize);
8731
8732   if (Opc != X86ISD::WIN_FTOL) {
8733     // Build the FP_TO_INT*_IN_MEM
8734     SDValue Ops[] = { Chain, Value, StackSlot };
8735     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8736                                            Ops, array_lengthof(Ops), DstTy,
8737                                            MMO);
8738     return std::make_pair(FIST, StackSlot);
8739   } else {
8740     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8741       DAG.getVTList(MVT::Other, MVT::Glue),
8742       Chain, Value);
8743     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8744       MVT::i32, ftol.getValue(1));
8745     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8746       MVT::i32, eax.getValue(2));
8747     SDValue Ops[] = { eax, edx };
8748     SDValue pair = IsReplace
8749       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8750       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8751     return std::make_pair(pair, SDValue());
8752   }
8753 }
8754
8755 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8756                               const X86Subtarget *Subtarget) {
8757   MVT VT = Op->getValueType(0).getSimpleVT();
8758   SDValue In = Op->getOperand(0);
8759   MVT InVT = In.getValueType().getSimpleVT();
8760   SDLoc dl(Op);
8761
8762   // Optimize vectors in AVX mode:
8763   //
8764   //   v8i16 -> v8i32
8765   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8766   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8767   //   Concat upper and lower parts.
8768   //
8769   //   v4i32 -> v4i64
8770   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8771   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8772   //   Concat upper and lower parts.
8773   //
8774
8775   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8776       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8777     return SDValue();
8778
8779   if (Subtarget->hasInt256())
8780     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8781
8782   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8783   SDValue Undef = DAG.getUNDEF(InVT);
8784   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8785   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8786   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8787
8788   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8789                              VT.getVectorNumElements()/2);
8790
8791   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8792   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8793
8794   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8795 }
8796
8797 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8798                                            SelectionDAG &DAG) const {
8799   if (Subtarget->hasFp256()) {
8800     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8801     if (Res.getNode())
8802       return Res;
8803   }
8804
8805   return SDValue();
8806 }
8807 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8808                                             SelectionDAG &DAG) const {
8809   SDLoc DL(Op);
8810   MVT VT = Op.getValueType().getSimpleVT();
8811   SDValue In = Op.getOperand(0);
8812   MVT SVT = In.getValueType().getSimpleVT();
8813
8814   if (Subtarget->hasFp256()) {
8815     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8816     if (Res.getNode())
8817       return Res;
8818   }
8819
8820   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8821       VT.getVectorNumElements() != SVT.getVectorNumElements())
8822     return SDValue();
8823
8824   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8825
8826   // AVX2 has better support of integer extending.
8827   if (Subtarget->hasInt256())
8828     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8829
8830   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8831   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8832   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8833                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8834                                                 DAG.getUNDEF(MVT::v8i16),
8835                                                 &Mask[0]));
8836
8837   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8838 }
8839
8840 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8841   SDLoc DL(Op);
8842   MVT VT = Op.getValueType().getSimpleVT();
8843   SDValue In = Op.getOperand(0);
8844   MVT SVT = In.getValueType().getSimpleVT();
8845
8846   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8847     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8848     if (Subtarget->hasInt256()) {
8849       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8850       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8851       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8852                                 ShufMask);
8853       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8854                          DAG.getIntPtrConstant(0));
8855     }
8856
8857     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8858     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8859                                DAG.getIntPtrConstant(0));
8860     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8861                                DAG.getIntPtrConstant(2));
8862
8863     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8864     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8865
8866     // The PSHUFD mask:
8867     static const int ShufMask1[] = {0, 2, 0, 0};
8868     SDValue Undef = DAG.getUNDEF(VT);
8869     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8870     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8871
8872     // The MOVLHPS mask:
8873     static const int ShufMask2[] = {0, 1, 4, 5};
8874     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8875   }
8876
8877   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8878     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8879     if (Subtarget->hasInt256()) {
8880       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8881
8882       SmallVector<SDValue,32> pshufbMask;
8883       for (unsigned i = 0; i < 2; ++i) {
8884         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8885         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8886         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8887         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8888         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8889         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8890         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8891         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8892         for (unsigned j = 0; j < 8; ++j)
8893           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8894       }
8895       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8896                                &pshufbMask[0], 32);
8897       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8898       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8899
8900       static const int ShufMask[] = {0,  2,  -1,  -1};
8901       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8902                                 &ShufMask[0]);
8903       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8904                        DAG.getIntPtrConstant(0));
8905       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8906     }
8907
8908     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8909                                DAG.getIntPtrConstant(0));
8910
8911     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8912                                DAG.getIntPtrConstant(4));
8913
8914     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8915     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8916
8917     // The PSHUFB mask:
8918     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8919                                    -1, -1, -1, -1, -1, -1, -1, -1};
8920
8921     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8922     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8923     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8924
8925     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8926     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8927
8928     // The MOVLHPS Mask:
8929     static const int ShufMask2[] = {0, 1, 4, 5};
8930     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8931     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8932   }
8933
8934   // Handle truncation of V256 to V128 using shuffles.
8935   if (!VT.is128BitVector() || !SVT.is256BitVector())
8936     return SDValue();
8937
8938   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8939          "Invalid op");
8940   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8941
8942   unsigned NumElems = VT.getVectorNumElements();
8943   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8944                              NumElems * 2);
8945
8946   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8947   // Prepare truncation shuffle mask
8948   for (unsigned i = 0; i != NumElems; ++i)
8949     MaskVec[i] = i * 2;
8950   SDValue V = DAG.getVectorShuffle(NVT, DL,
8951                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8952                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8953   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8954                      DAG.getIntPtrConstant(0));
8955 }
8956
8957 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8958                                            SelectionDAG &DAG) const {
8959   MVT VT = Op.getValueType().getSimpleVT();
8960   if (VT.isVector()) {
8961     if (VT == MVT::v8i16)
8962       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8963                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8964                                      MVT::v8i32, Op.getOperand(0)));
8965     return SDValue();
8966   }
8967
8968   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8969     /*IsSigned=*/ true, /*IsReplace=*/ false);
8970   SDValue FIST = Vals.first, StackSlot = Vals.second;
8971   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8972   if (FIST.getNode() == 0) return Op;
8973
8974   if (StackSlot.getNode())
8975     // Load the result.
8976     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8977                        FIST, StackSlot, MachinePointerInfo(),
8978                        false, false, false, 0);
8979
8980   // The node is the result.
8981   return FIST;
8982 }
8983
8984 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8985                                            SelectionDAG &DAG) const {
8986   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8987     /*IsSigned=*/ false, /*IsReplace=*/ false);
8988   SDValue FIST = Vals.first, StackSlot = Vals.second;
8989   assert(FIST.getNode() && "Unexpected failure");
8990
8991   if (StackSlot.getNode())
8992     // Load the result.
8993     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8994                        FIST, StackSlot, MachinePointerInfo(),
8995                        false, false, false, 0);
8996
8997   // The node is the result.
8998   return FIST;
8999 }
9000
9001 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9002   SDLoc DL(Op);
9003   MVT VT = Op.getValueType().getSimpleVT();
9004   SDValue In = Op.getOperand(0);
9005   MVT SVT = In.getValueType().getSimpleVT();
9006
9007   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9008
9009   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9010                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9011                                  In, DAG.getUNDEF(SVT)));
9012 }
9013
9014 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9015   LLVMContext *Context = DAG.getContext();
9016   SDLoc dl(Op);
9017   MVT VT = Op.getValueType().getSimpleVT();
9018   MVT EltVT = VT;
9019   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9020   if (VT.isVector()) {
9021     EltVT = VT.getVectorElementType();
9022     NumElts = VT.getVectorNumElements();
9023   }
9024   Constant *C;
9025   if (EltVT == MVT::f64)
9026     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9027                                           APInt(64, ~(1ULL << 63))));
9028   else
9029     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9030                                           APInt(32, ~(1U << 31))));
9031   C = ConstantVector::getSplat(NumElts, C);
9032   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9033   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9034   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9035                              MachinePointerInfo::getConstantPool(),
9036                              false, false, false, Alignment);
9037   if (VT.isVector()) {
9038     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9039     return DAG.getNode(ISD::BITCAST, dl, VT,
9040                        DAG.getNode(ISD::AND, dl, ANDVT,
9041                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9042                                                Op.getOperand(0)),
9043                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9044   }
9045   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9046 }
9047
9048 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9049   LLVMContext *Context = DAG.getContext();
9050   SDLoc dl(Op);
9051   MVT VT = Op.getValueType().getSimpleVT();
9052   MVT EltVT = VT;
9053   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9054   if (VT.isVector()) {
9055     EltVT = VT.getVectorElementType();
9056     NumElts = VT.getVectorNumElements();
9057   }
9058   Constant *C;
9059   if (EltVT == MVT::f64)
9060     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9061                                           APInt(64, 1ULL << 63)));
9062   else
9063     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9064                                           APInt(32, 1U << 31)));
9065   C = ConstantVector::getSplat(NumElts, C);
9066   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9067   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9068   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9069                              MachinePointerInfo::getConstantPool(),
9070                              false, false, false, Alignment);
9071   if (VT.isVector()) {
9072     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9073     return DAG.getNode(ISD::BITCAST, dl, VT,
9074                        DAG.getNode(ISD::XOR, dl, XORVT,
9075                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9076                                                Op.getOperand(0)),
9077                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9078   }
9079
9080   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9081 }
9082
9083 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9084   LLVMContext *Context = DAG.getContext();
9085   SDValue Op0 = Op.getOperand(0);
9086   SDValue Op1 = Op.getOperand(1);
9087   SDLoc dl(Op);
9088   MVT VT = Op.getValueType().getSimpleVT();
9089   MVT SrcVT = Op1.getValueType().getSimpleVT();
9090
9091   // If second operand is smaller, extend it first.
9092   if (SrcVT.bitsLT(VT)) {
9093     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9094     SrcVT = VT;
9095   }
9096   // And if it is bigger, shrink it first.
9097   if (SrcVT.bitsGT(VT)) {
9098     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9099     SrcVT = VT;
9100   }
9101
9102   // At this point the operands and the result should have the same
9103   // type, and that won't be f80 since that is not custom lowered.
9104
9105   // First get the sign bit of second operand.
9106   SmallVector<Constant*,4> CV;
9107   if (SrcVT == MVT::f64) {
9108     const fltSemantics &Sem = APFloat::IEEEdouble;
9109     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9110     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9111   } else {
9112     const fltSemantics &Sem = APFloat::IEEEsingle;
9113     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9114     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9115     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9116     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9117   }
9118   Constant *C = ConstantVector::get(CV);
9119   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9120   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9121                               MachinePointerInfo::getConstantPool(),
9122                               false, false, false, 16);
9123   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9124
9125   // Shift sign bit right or left if the two operands have different types.
9126   if (SrcVT.bitsGT(VT)) {
9127     // Op0 is MVT::f32, Op1 is MVT::f64.
9128     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9129     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9130                           DAG.getConstant(32, MVT::i32));
9131     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9132     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9133                           DAG.getIntPtrConstant(0));
9134   }
9135
9136   // Clear first operand sign bit.
9137   CV.clear();
9138   if (VT == MVT::f64) {
9139     const fltSemantics &Sem = APFloat::IEEEdouble;
9140     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9141                                                    APInt(64, ~(1ULL << 63)))));
9142     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9143   } else {
9144     const fltSemantics &Sem = APFloat::IEEEsingle;
9145     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9146                                                    APInt(32, ~(1U << 31)))));
9147     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9148     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9149     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9150   }
9151   C = ConstantVector::get(CV);
9152   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9153   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9154                               MachinePointerInfo::getConstantPool(),
9155                               false, false, false, 16);
9156   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9157
9158   // Or the value with the sign bit.
9159   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9160 }
9161
9162 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9163   SDValue N0 = Op.getOperand(0);
9164   SDLoc dl(Op);
9165   MVT VT = Op.getValueType().getSimpleVT();
9166
9167   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9168   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9169                                   DAG.getConstant(1, VT));
9170   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9171 }
9172
9173 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9174 //
9175 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
9176                                                   SelectionDAG &DAG) const {
9177   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9178
9179   if (!Subtarget->hasSSE41())
9180     return SDValue();
9181
9182   if (!Op->hasOneUse())
9183     return SDValue();
9184
9185   SDNode *N = Op.getNode();
9186   SDLoc DL(N);
9187
9188   SmallVector<SDValue, 8> Opnds;
9189   DenseMap<SDValue, unsigned> VecInMap;
9190   EVT VT = MVT::Other;
9191
9192   // Recognize a special case where a vector is casted into wide integer to
9193   // test all 0s.
9194   Opnds.push_back(N->getOperand(0));
9195   Opnds.push_back(N->getOperand(1));
9196
9197   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9198     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9199     // BFS traverse all OR'd operands.
9200     if (I->getOpcode() == ISD::OR) {
9201       Opnds.push_back(I->getOperand(0));
9202       Opnds.push_back(I->getOperand(1));
9203       // Re-evaluate the number of nodes to be traversed.
9204       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9205       continue;
9206     }
9207
9208     // Quit if a non-EXTRACT_VECTOR_ELT
9209     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9210       return SDValue();
9211
9212     // Quit if without a constant index.
9213     SDValue Idx = I->getOperand(1);
9214     if (!isa<ConstantSDNode>(Idx))
9215       return SDValue();
9216
9217     SDValue ExtractedFromVec = I->getOperand(0);
9218     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9219     if (M == VecInMap.end()) {
9220       VT = ExtractedFromVec.getValueType();
9221       // Quit if not 128/256-bit vector.
9222       if (!VT.is128BitVector() && !VT.is256BitVector())
9223         return SDValue();
9224       // Quit if not the same type.
9225       if (VecInMap.begin() != VecInMap.end() &&
9226           VT != VecInMap.begin()->first.getValueType())
9227         return SDValue();
9228       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9229     }
9230     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9231   }
9232
9233   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9234          "Not extracted from 128-/256-bit vector.");
9235
9236   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9237   SmallVector<SDValue, 8> VecIns;
9238
9239   for (DenseMap<SDValue, unsigned>::const_iterator
9240         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9241     // Quit if not all elements are used.
9242     if (I->second != FullMask)
9243       return SDValue();
9244     VecIns.push_back(I->first);
9245   }
9246
9247   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9248
9249   // Cast all vectors into TestVT for PTEST.
9250   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9251     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9252
9253   // If more than one full vectors are evaluated, OR them first before PTEST.
9254   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9255     // Each iteration will OR 2 nodes and append the result until there is only
9256     // 1 node left, i.e. the final OR'd value of all vectors.
9257     SDValue LHS = VecIns[Slot];
9258     SDValue RHS = VecIns[Slot + 1];
9259     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9260   }
9261
9262   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9263                      VecIns.back(), VecIns.back());
9264 }
9265
9266 /// Emit nodes that will be selected as "test Op0,Op0", or something
9267 /// equivalent.
9268 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9269                                     SelectionDAG &DAG) const {
9270   SDLoc dl(Op);
9271
9272   // CF and OF aren't always set the way we want. Determine which
9273   // of these we need.
9274   bool NeedCF = false;
9275   bool NeedOF = false;
9276   switch (X86CC) {
9277   default: break;
9278   case X86::COND_A: case X86::COND_AE:
9279   case X86::COND_B: case X86::COND_BE:
9280     NeedCF = true;
9281     break;
9282   case X86::COND_G: case X86::COND_GE:
9283   case X86::COND_L: case X86::COND_LE:
9284   case X86::COND_O: case X86::COND_NO:
9285     NeedOF = true;
9286     break;
9287   }
9288
9289   // See if we can use the EFLAGS value from the operand instead of
9290   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9291   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9292   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9293     // Emit a CMP with 0, which is the TEST pattern.
9294     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9295                        DAG.getConstant(0, Op.getValueType()));
9296
9297   unsigned Opcode = 0;
9298   unsigned NumOperands = 0;
9299
9300   // Truncate operations may prevent the merge of the SETCC instruction
9301   // and the arithmetic intruction before it. Attempt to truncate the operands
9302   // of the arithmetic instruction and use a reduced bit-width instruction.
9303   bool NeedTruncation = false;
9304   SDValue ArithOp = Op;
9305   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9306     SDValue Arith = Op->getOperand(0);
9307     // Both the trunc and the arithmetic op need to have one user each.
9308     if (Arith->hasOneUse())
9309       switch (Arith.getOpcode()) {
9310         default: break;
9311         case ISD::ADD:
9312         case ISD::SUB:
9313         case ISD::AND:
9314         case ISD::OR:
9315         case ISD::XOR: {
9316           NeedTruncation = true;
9317           ArithOp = Arith;
9318         }
9319       }
9320   }
9321
9322   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9323   // which may be the result of a CAST.  We use the variable 'Op', which is the
9324   // non-casted variable when we check for possible users.
9325   switch (ArithOp.getOpcode()) {
9326   case ISD::ADD:
9327     // Due to an isel shortcoming, be conservative if this add is likely to be
9328     // selected as part of a load-modify-store instruction. When the root node
9329     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9330     // uses of other nodes in the match, such as the ADD in this case. This
9331     // leads to the ADD being left around and reselected, with the result being
9332     // two adds in the output.  Alas, even if none our users are stores, that
9333     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9334     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9335     // climbing the DAG back to the root, and it doesn't seem to be worth the
9336     // effort.
9337     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9338          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9339       if (UI->getOpcode() != ISD::CopyToReg &&
9340           UI->getOpcode() != ISD::SETCC &&
9341           UI->getOpcode() != ISD::STORE)
9342         goto default_case;
9343
9344     if (ConstantSDNode *C =
9345         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9346       // An add of one will be selected as an INC.
9347       if (C->getAPIntValue() == 1) {
9348         Opcode = X86ISD::INC;
9349         NumOperands = 1;
9350         break;
9351       }
9352
9353       // An add of negative one (subtract of one) will be selected as a DEC.
9354       if (C->getAPIntValue().isAllOnesValue()) {
9355         Opcode = X86ISD::DEC;
9356         NumOperands = 1;
9357         break;
9358       }
9359     }
9360
9361     // Otherwise use a regular EFLAGS-setting add.
9362     Opcode = X86ISD::ADD;
9363     NumOperands = 2;
9364     break;
9365   case ISD::AND: {
9366     // If the primary and result isn't used, don't bother using X86ISD::AND,
9367     // because a TEST instruction will be better.
9368     bool NonFlagUse = false;
9369     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9370            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9371       SDNode *User = *UI;
9372       unsigned UOpNo = UI.getOperandNo();
9373       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9374         // Look pass truncate.
9375         UOpNo = User->use_begin().getOperandNo();
9376         User = *User->use_begin();
9377       }
9378
9379       if (User->getOpcode() != ISD::BRCOND &&
9380           User->getOpcode() != ISD::SETCC &&
9381           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9382         NonFlagUse = true;
9383         break;
9384       }
9385     }
9386
9387     if (!NonFlagUse)
9388       break;
9389   }
9390     // FALL THROUGH
9391   case ISD::SUB:
9392   case ISD::OR:
9393   case ISD::XOR:
9394     // Due to the ISEL shortcoming noted above, be conservative if this op is
9395     // likely to be selected as part of a load-modify-store instruction.
9396     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9397            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9398       if (UI->getOpcode() == ISD::STORE)
9399         goto default_case;
9400
9401     // Otherwise use a regular EFLAGS-setting instruction.
9402     switch (ArithOp.getOpcode()) {
9403     default: llvm_unreachable("unexpected operator!");
9404     case ISD::SUB: Opcode = X86ISD::SUB; break;
9405     case ISD::XOR: Opcode = X86ISD::XOR; break;
9406     case ISD::AND: Opcode = X86ISD::AND; break;
9407     case ISD::OR: {
9408       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9409         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9410         if (EFLAGS.getNode())
9411           return EFLAGS;
9412       }
9413       Opcode = X86ISD::OR;
9414       break;
9415     }
9416     }
9417
9418     NumOperands = 2;
9419     break;
9420   case X86ISD::ADD:
9421   case X86ISD::SUB:
9422   case X86ISD::INC:
9423   case X86ISD::DEC:
9424   case X86ISD::OR:
9425   case X86ISD::XOR:
9426   case X86ISD::AND:
9427     return SDValue(Op.getNode(), 1);
9428   default:
9429   default_case:
9430     break;
9431   }
9432
9433   // If we found that truncation is beneficial, perform the truncation and
9434   // update 'Op'.
9435   if (NeedTruncation) {
9436     EVT VT = Op.getValueType();
9437     SDValue WideVal = Op->getOperand(0);
9438     EVT WideVT = WideVal.getValueType();
9439     unsigned ConvertedOp = 0;
9440     // Use a target machine opcode to prevent further DAGCombine
9441     // optimizations that may separate the arithmetic operations
9442     // from the setcc node.
9443     switch (WideVal.getOpcode()) {
9444       default: break;
9445       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9446       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9447       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9448       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9449       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9450     }
9451
9452     if (ConvertedOp) {
9453       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9454       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9455         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9456         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9457         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9458       }
9459     }
9460   }
9461
9462   if (Opcode == 0)
9463     // Emit a CMP with 0, which is the TEST pattern.
9464     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9465                        DAG.getConstant(0, Op.getValueType()));
9466
9467   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9468   SmallVector<SDValue, 4> Ops;
9469   for (unsigned i = 0; i != NumOperands; ++i)
9470     Ops.push_back(Op.getOperand(i));
9471
9472   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9473   DAG.ReplaceAllUsesWith(Op, New);
9474   return SDValue(New.getNode(), 1);
9475 }
9476
9477 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9478 /// equivalent.
9479 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9480                                    SelectionDAG &DAG) const {
9481   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9482     if (C->getAPIntValue() == 0)
9483       return EmitTest(Op0, X86CC, DAG);
9484
9485   SDLoc dl(Op0);
9486   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9487        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9488     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9489     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9490     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9491                               Op0, Op1);
9492     return SDValue(Sub.getNode(), 1);
9493   }
9494   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9495 }
9496
9497 /// Convert a comparison if required by the subtarget.
9498 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9499                                                  SelectionDAG &DAG) const {
9500   // If the subtarget does not support the FUCOMI instruction, floating-point
9501   // comparisons have to be converted.
9502   if (Subtarget->hasCMov() ||
9503       Cmp.getOpcode() != X86ISD::CMP ||
9504       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9505       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9506     return Cmp;
9507
9508   // The instruction selector will select an FUCOM instruction instead of
9509   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9510   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9511   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9512   SDLoc dl(Cmp);
9513   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9514   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9515   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9516                             DAG.getConstant(8, MVT::i8));
9517   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9518   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9519 }
9520
9521 static bool isAllOnes(SDValue V) {
9522   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9523   return C && C->isAllOnesValue();
9524 }
9525
9526 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9527 /// if it's possible.
9528 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9529                                      SDLoc dl, SelectionDAG &DAG) const {
9530   SDValue Op0 = And.getOperand(0);
9531   SDValue Op1 = And.getOperand(1);
9532   if (Op0.getOpcode() == ISD::TRUNCATE)
9533     Op0 = Op0.getOperand(0);
9534   if (Op1.getOpcode() == ISD::TRUNCATE)
9535     Op1 = Op1.getOperand(0);
9536
9537   SDValue LHS, RHS;
9538   if (Op1.getOpcode() == ISD::SHL)
9539     std::swap(Op0, Op1);
9540   if (Op0.getOpcode() == ISD::SHL) {
9541     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9542       if (And00C->getZExtValue() == 1) {
9543         // If we looked past a truncate, check that it's only truncating away
9544         // known zeros.
9545         unsigned BitWidth = Op0.getValueSizeInBits();
9546         unsigned AndBitWidth = And.getValueSizeInBits();
9547         if (BitWidth > AndBitWidth) {
9548           APInt Zeros, Ones;
9549           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9550           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9551             return SDValue();
9552         }
9553         LHS = Op1;
9554         RHS = Op0.getOperand(1);
9555       }
9556   } else if (Op1.getOpcode() == ISD::Constant) {
9557     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9558     uint64_t AndRHSVal = AndRHS->getZExtValue();
9559     SDValue AndLHS = Op0;
9560
9561     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9562       LHS = AndLHS.getOperand(0);
9563       RHS = AndLHS.getOperand(1);
9564     }
9565
9566     // Use BT if the immediate can't be encoded in a TEST instruction.
9567     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9568       LHS = AndLHS;
9569       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9570     }
9571   }
9572
9573   if (LHS.getNode()) {
9574     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9575     // instruction.  Since the shift amount is in-range-or-undefined, we know
9576     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9577     // the encoding for the i16 version is larger than the i32 version.
9578     // Also promote i16 to i32 for performance / code size reason.
9579     if (LHS.getValueType() == MVT::i8 ||
9580         LHS.getValueType() == MVT::i16)
9581       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9582
9583     // If the operand types disagree, extend the shift amount to match.  Since
9584     // BT ignores high bits (like shifts) we can use anyextend.
9585     if (LHS.getValueType() != RHS.getValueType())
9586       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9587
9588     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9589     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9590     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9591                        DAG.getConstant(Cond, MVT::i8), BT);
9592   }
9593
9594   return SDValue();
9595 }
9596
9597 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9598 /// mask CMPs.
9599 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9600                               SDValue &Op1) {
9601   unsigned SSECC;
9602   bool Swap = false;
9603
9604   // SSE Condition code mapping:
9605   //  0 - EQ
9606   //  1 - LT
9607   //  2 - LE
9608   //  3 - UNORD
9609   //  4 - NEQ
9610   //  5 - NLT
9611   //  6 - NLE
9612   //  7 - ORD
9613   switch (SetCCOpcode) {
9614   default: llvm_unreachable("Unexpected SETCC condition");
9615   case ISD::SETOEQ:
9616   case ISD::SETEQ:  SSECC = 0; break;
9617   case ISD::SETOGT:
9618   case ISD::SETGT:  Swap = true; // Fallthrough
9619   case ISD::SETLT:
9620   case ISD::SETOLT: SSECC = 1; break;
9621   case ISD::SETOGE:
9622   case ISD::SETGE:  Swap = true; // Fallthrough
9623   case ISD::SETLE:
9624   case ISD::SETOLE: SSECC = 2; break;
9625   case ISD::SETUO:  SSECC = 3; break;
9626   case ISD::SETUNE:
9627   case ISD::SETNE:  SSECC = 4; break;
9628   case ISD::SETULE: Swap = true; // Fallthrough
9629   case ISD::SETUGE: SSECC = 5; break;
9630   case ISD::SETULT: Swap = true; // Fallthrough
9631   case ISD::SETUGT: SSECC = 6; break;
9632   case ISD::SETO:   SSECC = 7; break;
9633   case ISD::SETUEQ:
9634   case ISD::SETONE: SSECC = 8; break;
9635   }
9636   if (Swap)
9637     std::swap(Op0, Op1);
9638
9639   return SSECC;
9640 }
9641
9642 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9643 // ones, and then concatenate the result back.
9644 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9645   MVT VT = Op.getValueType().getSimpleVT();
9646
9647   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9648          "Unsupported value type for operation");
9649
9650   unsigned NumElems = VT.getVectorNumElements();
9651   SDLoc dl(Op);
9652   SDValue CC = Op.getOperand(2);
9653
9654   // Extract the LHS vectors
9655   SDValue LHS = Op.getOperand(0);
9656   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9657   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9658
9659   // Extract the RHS vectors
9660   SDValue RHS = Op.getOperand(1);
9661   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9662   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9663
9664   // Issue the operation on the smaller types and concatenate the result back
9665   MVT EltVT = VT.getVectorElementType();
9666   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9667   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9668                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9669                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9670 }
9671
9672 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9673                            SelectionDAG &DAG) {
9674   SDValue Cond;
9675   SDValue Op0 = Op.getOperand(0);
9676   SDValue Op1 = Op.getOperand(1);
9677   SDValue CC = Op.getOperand(2);
9678   MVT VT = Op.getValueType().getSimpleVT();
9679   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9680   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9681   SDLoc dl(Op);
9682
9683   if (isFP) {
9684 #ifndef NDEBUG
9685     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9686     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9687 #endif
9688
9689     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9690
9691     // In the two special cases we can't handle, emit two comparisons.
9692     if (SSECC == 8) {
9693       unsigned CC0, CC1;
9694       unsigned CombineOpc;
9695       if (SetCCOpcode == ISD::SETUEQ) {
9696         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9697       } else {
9698         assert(SetCCOpcode == ISD::SETONE);
9699         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9700       }
9701
9702       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9703                                  DAG.getConstant(CC0, MVT::i8));
9704       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9705                                  DAG.getConstant(CC1, MVT::i8));
9706       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9707     }
9708     // Handle all other FP comparisons here.
9709     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9710                        DAG.getConstant(SSECC, MVT::i8));
9711   }
9712
9713   // Break 256-bit integer vector compare into smaller ones.
9714   if (VT.is256BitVector() && !Subtarget->hasInt256())
9715     return Lower256IntVSETCC(Op, DAG);
9716
9717   // We are handling one of the integer comparisons here.  Since SSE only has
9718   // GT and EQ comparisons for integer, swapping operands and multiple
9719   // operations may be required for some comparisons.
9720   unsigned Opc;
9721   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9722   
9723   switch (SetCCOpcode) {
9724   default: llvm_unreachable("Unexpected SETCC condition");
9725   case ISD::SETNE:  Invert = true;
9726   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9727   case ISD::SETLT:  Swap = true;
9728   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9729   case ISD::SETGE:  Swap = true;
9730   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9731   case ISD::SETULT: Swap = true;
9732   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9733   case ISD::SETUGE: Swap = true;
9734   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9735   }
9736   
9737   // Special case: Use min/max operations for SETULE/SETUGE
9738   MVT VET = VT.getVectorElementType();
9739   bool hasMinMax =
9740        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9741     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
9742   
9743   if (hasMinMax) {
9744     switch (SetCCOpcode) {
9745     default: break;
9746     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9747     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9748     }
9749     
9750     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9751   }
9752   
9753   if (Swap)
9754     std::swap(Op0, Op1);
9755
9756   // Check that the operation in question is available (most are plain SSE2,
9757   // but PCMPGTQ and PCMPEQQ have different requirements).
9758   if (VT == MVT::v2i64) {
9759     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9760       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9761
9762       // First cast everything to the right type.
9763       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9764       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9765
9766       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9767       // bits of the inputs before performing those operations. The lower
9768       // compare is always unsigned.
9769       SDValue SB;
9770       if (FlipSigns) {
9771         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9772       } else {
9773         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9774         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9775         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9776                          Sign, Zero, Sign, Zero);
9777       }
9778       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9779       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9780
9781       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9782       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9783       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9784
9785       // Create masks for only the low parts/high parts of the 64 bit integers.
9786       static const int MaskHi[] = { 1, 1, 3, 3 };
9787       static const int MaskLo[] = { 0, 0, 2, 2 };
9788       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9789       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9790       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9791
9792       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9793       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9794
9795       if (Invert)
9796         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9797
9798       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9799     }
9800
9801     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9802       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9803       // pcmpeqd + pshufd + pand.
9804       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9805
9806       // First cast everything to the right type.
9807       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9808       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9809
9810       // Do the compare.
9811       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9812
9813       // Make sure the lower and upper halves are both all-ones.
9814       static const int Mask[] = { 1, 0, 3, 2 };
9815       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9816       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9817
9818       if (Invert)
9819         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9820
9821       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9822     }
9823   }
9824
9825   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9826   // bits of the inputs before performing those operations.
9827   if (FlipSigns) {
9828     EVT EltVT = VT.getVectorElementType();
9829     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9830     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9831     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9832   }
9833
9834   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9835
9836   // If the logical-not of the result is required, perform that now.
9837   if (Invert)
9838     Result = DAG.getNOT(dl, Result, VT);
9839   
9840   if (MinMax)
9841     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9842
9843   return Result;
9844 }
9845
9846 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9847
9848   MVT VT = Op.getValueType().getSimpleVT();
9849
9850   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9851
9852   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9853   SDValue Op0 = Op.getOperand(0);
9854   SDValue Op1 = Op.getOperand(1);
9855   SDLoc dl(Op);
9856   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9857
9858   // Optimize to BT if possible.
9859   // Lower (X & (1 << N)) == 0 to BT(X, N).
9860   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9861   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9862   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9863       Op1.getOpcode() == ISD::Constant &&
9864       cast<ConstantSDNode>(Op1)->isNullValue() &&
9865       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9866     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9867     if (NewSetCC.getNode())
9868       return NewSetCC;
9869   }
9870
9871   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9872   // these.
9873   if (Op1.getOpcode() == ISD::Constant &&
9874       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9875        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9876       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9877
9878     // If the input is a setcc, then reuse the input setcc or use a new one with
9879     // the inverted condition.
9880     if (Op0.getOpcode() == X86ISD::SETCC) {
9881       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9882       bool Invert = (CC == ISD::SETNE) ^
9883         cast<ConstantSDNode>(Op1)->isNullValue();
9884       if (!Invert) return Op0;
9885
9886       CCode = X86::GetOppositeBranchCondition(CCode);
9887       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9888                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9889     }
9890   }
9891
9892   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9893   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9894   if (X86CC == X86::COND_INVALID)
9895     return SDValue();
9896
9897   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9898   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9899   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9900                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9901 }
9902
9903 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9904 static bool isX86LogicalCmp(SDValue Op) {
9905   unsigned Opc = Op.getNode()->getOpcode();
9906   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9907       Opc == X86ISD::SAHF)
9908     return true;
9909   if (Op.getResNo() == 1 &&
9910       (Opc == X86ISD::ADD ||
9911        Opc == X86ISD::SUB ||
9912        Opc == X86ISD::ADC ||
9913        Opc == X86ISD::SBB ||
9914        Opc == X86ISD::SMUL ||
9915        Opc == X86ISD::UMUL ||
9916        Opc == X86ISD::INC ||
9917        Opc == X86ISD::DEC ||
9918        Opc == X86ISD::OR ||
9919        Opc == X86ISD::XOR ||
9920        Opc == X86ISD::AND))
9921     return true;
9922
9923   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9924     return true;
9925
9926   return false;
9927 }
9928
9929 static bool isZero(SDValue V) {
9930   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9931   return C && C->isNullValue();
9932 }
9933
9934 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9935   if (V.getOpcode() != ISD::TRUNCATE)
9936     return false;
9937
9938   SDValue VOp0 = V.getOperand(0);
9939   unsigned InBits = VOp0.getValueSizeInBits();
9940   unsigned Bits = V.getValueSizeInBits();
9941   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9942 }
9943
9944 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9945   bool addTest = true;
9946   SDValue Cond  = Op.getOperand(0);
9947   SDValue Op1 = Op.getOperand(1);
9948   SDValue Op2 = Op.getOperand(2);
9949   SDLoc DL(Op);
9950   EVT VT = Op1.getValueType();
9951   SDValue CC;
9952
9953   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
9954   // are available. Otherwise fp cmovs get lowered into a less efficient branch
9955   // sequence later on.
9956   if (Cond.getOpcode() == ISD::SETCC &&
9957       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
9958        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
9959       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
9960     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
9961     int SSECC = translateX86FSETCC(
9962         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
9963
9964     if (SSECC != 8) {
9965       unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
9966       SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
9967                                 DAG.getConstant(SSECC, MVT::i8));
9968       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
9969       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
9970       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
9971     }
9972   }
9973
9974   if (Cond.getOpcode() == ISD::SETCC) {
9975     SDValue NewCond = LowerSETCC(Cond, DAG);
9976     if (NewCond.getNode())
9977       Cond = NewCond;
9978   }
9979
9980   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9981   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9982   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9983   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9984   if (Cond.getOpcode() == X86ISD::SETCC &&
9985       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9986       isZero(Cond.getOperand(1).getOperand(1))) {
9987     SDValue Cmp = Cond.getOperand(1);
9988
9989     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9990
9991     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9992         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9993       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9994
9995       SDValue CmpOp0 = Cmp.getOperand(0);
9996       // Apply further optimizations for special cases
9997       // (select (x != 0), -1, 0) -> neg & sbb
9998       // (select (x == 0), 0, -1) -> neg & sbb
9999       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10000         if (YC->isNullValue() &&
10001             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10002           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10003           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10004                                     DAG.getConstant(0, CmpOp0.getValueType()),
10005                                     CmpOp0);
10006           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10007                                     DAG.getConstant(X86::COND_B, MVT::i8),
10008                                     SDValue(Neg.getNode(), 1));
10009           return Res;
10010         }
10011
10012       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10013                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10014       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10015
10016       SDValue Res =   // Res = 0 or -1.
10017         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10018                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10019
10020       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10021         Res = DAG.getNOT(DL, Res, Res.getValueType());
10022
10023       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10024       if (N2C == 0 || !N2C->isNullValue())
10025         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10026       return Res;
10027     }
10028   }
10029
10030   // Look past (and (setcc_carry (cmp ...)), 1).
10031   if (Cond.getOpcode() == ISD::AND &&
10032       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10033     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10034     if (C && C->getAPIntValue() == 1)
10035       Cond = Cond.getOperand(0);
10036   }
10037
10038   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10039   // setting operand in place of the X86ISD::SETCC.
10040   unsigned CondOpcode = Cond.getOpcode();
10041   if (CondOpcode == X86ISD::SETCC ||
10042       CondOpcode == X86ISD::SETCC_CARRY) {
10043     CC = Cond.getOperand(0);
10044
10045     SDValue Cmp = Cond.getOperand(1);
10046     unsigned Opc = Cmp.getOpcode();
10047     MVT VT = Op.getValueType().getSimpleVT();
10048
10049     bool IllegalFPCMov = false;
10050     if (VT.isFloatingPoint() && !VT.isVector() &&
10051         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10052       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10053
10054     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10055         Opc == X86ISD::BT) { // FIXME
10056       Cond = Cmp;
10057       addTest = false;
10058     }
10059   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10060              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10061              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10062               Cond.getOperand(0).getValueType() != MVT::i8)) {
10063     SDValue LHS = Cond.getOperand(0);
10064     SDValue RHS = Cond.getOperand(1);
10065     unsigned X86Opcode;
10066     unsigned X86Cond;
10067     SDVTList VTs;
10068     switch (CondOpcode) {
10069     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10070     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10071     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10072     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10073     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10074     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10075     default: llvm_unreachable("unexpected overflowing operator");
10076     }
10077     if (CondOpcode == ISD::UMULO)
10078       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10079                           MVT::i32);
10080     else
10081       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10082
10083     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10084
10085     if (CondOpcode == ISD::UMULO)
10086       Cond = X86Op.getValue(2);
10087     else
10088       Cond = X86Op.getValue(1);
10089
10090     CC = DAG.getConstant(X86Cond, MVT::i8);
10091     addTest = false;
10092   }
10093
10094   if (addTest) {
10095     // Look pass the truncate if the high bits are known zero.
10096     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10097         Cond = Cond.getOperand(0);
10098
10099     // We know the result of AND is compared against zero. Try to match
10100     // it to BT.
10101     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10102       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10103       if (NewSetCC.getNode()) {
10104         CC = NewSetCC.getOperand(0);
10105         Cond = NewSetCC.getOperand(1);
10106         addTest = false;
10107       }
10108     }
10109   }
10110
10111   if (addTest) {
10112     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10113     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10114   }
10115
10116   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10117   // a <  b ?  0 : -1 -> RES = setcc_carry
10118   // a >= b ? -1 :  0 -> RES = setcc_carry
10119   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10120   if (Cond.getOpcode() == X86ISD::SUB) {
10121     Cond = ConvertCmpIfNecessary(Cond, DAG);
10122     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10123
10124     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10125         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10126       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10127                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10128       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10129         return DAG.getNOT(DL, Res, Res.getValueType());
10130       return Res;
10131     }
10132   }
10133
10134   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10135   // widen the cmov and push the truncate through. This avoids introducing a new
10136   // branch during isel and doesn't add any extensions.
10137   if (Op.getValueType() == MVT::i8 &&
10138       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10139     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10140     if (T1.getValueType() == T2.getValueType() &&
10141         // Blacklist CopyFromReg to avoid partial register stalls.
10142         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10143       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10144       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10145       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10146     }
10147   }
10148
10149   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10150   // condition is true.
10151   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10152   SDValue Ops[] = { Op2, Op1, CC, Cond };
10153   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10154 }
10155
10156 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10157                                             SelectionDAG &DAG) const {
10158   MVT VT = Op->getValueType(0).getSimpleVT();
10159   SDValue In = Op->getOperand(0);
10160   MVT InVT = In.getValueType().getSimpleVT();
10161   SDLoc dl(Op);
10162
10163   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10164       (VT != MVT::v8i32 || InVT != MVT::v8i16))
10165     return SDValue();
10166
10167   if (Subtarget->hasInt256())
10168     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10169
10170   // Optimize vectors in AVX mode
10171   // Sign extend  v8i16 to v8i32 and
10172   //              v4i32 to v4i64
10173   //
10174   // Divide input vector into two parts
10175   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10176   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10177   // concat the vectors to original VT
10178
10179   unsigned NumElems = InVT.getVectorNumElements();
10180   SDValue Undef = DAG.getUNDEF(InVT);
10181
10182   SmallVector<int,8> ShufMask1(NumElems, -1);
10183   for (unsigned i = 0; i != NumElems/2; ++i)
10184     ShufMask1[i] = i;
10185
10186   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10187
10188   SmallVector<int,8> ShufMask2(NumElems, -1);
10189   for (unsigned i = 0; i != NumElems/2; ++i)
10190     ShufMask2[i] = i + NumElems/2;
10191
10192   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10193
10194   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10195                                 VT.getVectorNumElements()/2);
10196
10197   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10198   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10199
10200   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10201 }
10202
10203 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10204 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10205 // from the AND / OR.
10206 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10207   Opc = Op.getOpcode();
10208   if (Opc != ISD::OR && Opc != ISD::AND)
10209     return false;
10210   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10211           Op.getOperand(0).hasOneUse() &&
10212           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10213           Op.getOperand(1).hasOneUse());
10214 }
10215
10216 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10217 // 1 and that the SETCC node has a single use.
10218 static bool isXor1OfSetCC(SDValue Op) {
10219   if (Op.getOpcode() != ISD::XOR)
10220     return false;
10221   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10222   if (N1C && N1C->getAPIntValue() == 1) {
10223     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10224       Op.getOperand(0).hasOneUse();
10225   }
10226   return false;
10227 }
10228
10229 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10230   bool addTest = true;
10231   SDValue Chain = Op.getOperand(0);
10232   SDValue Cond  = Op.getOperand(1);
10233   SDValue Dest  = Op.getOperand(2);
10234   SDLoc dl(Op);
10235   SDValue CC;
10236   bool Inverted = false;
10237
10238   if (Cond.getOpcode() == ISD::SETCC) {
10239     // Check for setcc([su]{add,sub,mul}o == 0).
10240     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10241         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10242         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10243         Cond.getOperand(0).getResNo() == 1 &&
10244         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10245          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10246          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10247          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10248          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10249          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10250       Inverted = true;
10251       Cond = Cond.getOperand(0);
10252     } else {
10253       SDValue NewCond = LowerSETCC(Cond, DAG);
10254       if (NewCond.getNode())
10255         Cond = NewCond;
10256     }
10257   }
10258 #if 0
10259   // FIXME: LowerXALUO doesn't handle these!!
10260   else if (Cond.getOpcode() == X86ISD::ADD  ||
10261            Cond.getOpcode() == X86ISD::SUB  ||
10262            Cond.getOpcode() == X86ISD::SMUL ||
10263            Cond.getOpcode() == X86ISD::UMUL)
10264     Cond = LowerXALUO(Cond, DAG);
10265 #endif
10266
10267   // Look pass (and (setcc_carry (cmp ...)), 1).
10268   if (Cond.getOpcode() == ISD::AND &&
10269       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10270     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10271     if (C && C->getAPIntValue() == 1)
10272       Cond = Cond.getOperand(0);
10273   }
10274
10275   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10276   // setting operand in place of the X86ISD::SETCC.
10277   unsigned CondOpcode = Cond.getOpcode();
10278   if (CondOpcode == X86ISD::SETCC ||
10279       CondOpcode == X86ISD::SETCC_CARRY) {
10280     CC = Cond.getOperand(0);
10281
10282     SDValue Cmp = Cond.getOperand(1);
10283     unsigned Opc = Cmp.getOpcode();
10284     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10285     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10286       Cond = Cmp;
10287       addTest = false;
10288     } else {
10289       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10290       default: break;
10291       case X86::COND_O:
10292       case X86::COND_B:
10293         // These can only come from an arithmetic instruction with overflow,
10294         // e.g. SADDO, UADDO.
10295         Cond = Cond.getNode()->getOperand(1);
10296         addTest = false;
10297         break;
10298       }
10299     }
10300   }
10301   CondOpcode = Cond.getOpcode();
10302   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10303       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10304       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10305        Cond.getOperand(0).getValueType() != MVT::i8)) {
10306     SDValue LHS = Cond.getOperand(0);
10307     SDValue RHS = Cond.getOperand(1);
10308     unsigned X86Opcode;
10309     unsigned X86Cond;
10310     SDVTList VTs;
10311     switch (CondOpcode) {
10312     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10313     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10314     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10315     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10316     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10317     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10318     default: llvm_unreachable("unexpected overflowing operator");
10319     }
10320     if (Inverted)
10321       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10322     if (CondOpcode == ISD::UMULO)
10323       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10324                           MVT::i32);
10325     else
10326       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10327
10328     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10329
10330     if (CondOpcode == ISD::UMULO)
10331       Cond = X86Op.getValue(2);
10332     else
10333       Cond = X86Op.getValue(1);
10334
10335     CC = DAG.getConstant(X86Cond, MVT::i8);
10336     addTest = false;
10337   } else {
10338     unsigned CondOpc;
10339     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10340       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10341       if (CondOpc == ISD::OR) {
10342         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10343         // two branches instead of an explicit OR instruction with a
10344         // separate test.
10345         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10346             isX86LogicalCmp(Cmp)) {
10347           CC = Cond.getOperand(0).getOperand(0);
10348           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10349                               Chain, Dest, CC, Cmp);
10350           CC = Cond.getOperand(1).getOperand(0);
10351           Cond = Cmp;
10352           addTest = false;
10353         }
10354       } else { // ISD::AND
10355         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10356         // two branches instead of an explicit AND instruction with a
10357         // separate test. However, we only do this if this block doesn't
10358         // have a fall-through edge, because this requires an explicit
10359         // jmp when the condition is false.
10360         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10361             isX86LogicalCmp(Cmp) &&
10362             Op.getNode()->hasOneUse()) {
10363           X86::CondCode CCode =
10364             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10365           CCode = X86::GetOppositeBranchCondition(CCode);
10366           CC = DAG.getConstant(CCode, MVT::i8);
10367           SDNode *User = *Op.getNode()->use_begin();
10368           // Look for an unconditional branch following this conditional branch.
10369           // We need this because we need to reverse the successors in order
10370           // to implement FCMP_OEQ.
10371           if (User->getOpcode() == ISD::BR) {
10372             SDValue FalseBB = User->getOperand(1);
10373             SDNode *NewBR =
10374               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10375             assert(NewBR == User);
10376             (void)NewBR;
10377             Dest = FalseBB;
10378
10379             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10380                                 Chain, Dest, CC, Cmp);
10381             X86::CondCode CCode =
10382               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10383             CCode = X86::GetOppositeBranchCondition(CCode);
10384             CC = DAG.getConstant(CCode, MVT::i8);
10385             Cond = Cmp;
10386             addTest = false;
10387           }
10388         }
10389       }
10390     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10391       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10392       // It should be transformed during dag combiner except when the condition
10393       // is set by a arithmetics with overflow node.
10394       X86::CondCode CCode =
10395         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10396       CCode = X86::GetOppositeBranchCondition(CCode);
10397       CC = DAG.getConstant(CCode, MVT::i8);
10398       Cond = Cond.getOperand(0).getOperand(1);
10399       addTest = false;
10400     } else if (Cond.getOpcode() == ISD::SETCC &&
10401                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10402       // For FCMP_OEQ, we can emit
10403       // two branches instead of an explicit AND instruction with a
10404       // separate test. However, we only do this if this block doesn't
10405       // have a fall-through edge, because this requires an explicit
10406       // jmp when the condition is false.
10407       if (Op.getNode()->hasOneUse()) {
10408         SDNode *User = *Op.getNode()->use_begin();
10409         // Look for an unconditional branch following this conditional branch.
10410         // We need this because we need to reverse the successors in order
10411         // to implement FCMP_OEQ.
10412         if (User->getOpcode() == ISD::BR) {
10413           SDValue FalseBB = User->getOperand(1);
10414           SDNode *NewBR =
10415             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10416           assert(NewBR == User);
10417           (void)NewBR;
10418           Dest = FalseBB;
10419
10420           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10421                                     Cond.getOperand(0), Cond.getOperand(1));
10422           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10423           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10424           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10425                               Chain, Dest, CC, Cmp);
10426           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10427           Cond = Cmp;
10428           addTest = false;
10429         }
10430       }
10431     } else if (Cond.getOpcode() == ISD::SETCC &&
10432                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10433       // For FCMP_UNE, we can emit
10434       // two branches instead of an explicit AND instruction with a
10435       // separate test. However, we only do this if this block doesn't
10436       // have a fall-through edge, because this requires an explicit
10437       // jmp when the condition is false.
10438       if (Op.getNode()->hasOneUse()) {
10439         SDNode *User = *Op.getNode()->use_begin();
10440         // Look for an unconditional branch following this conditional branch.
10441         // We need this because we need to reverse the successors in order
10442         // to implement FCMP_UNE.
10443         if (User->getOpcode() == ISD::BR) {
10444           SDValue FalseBB = User->getOperand(1);
10445           SDNode *NewBR =
10446             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10447           assert(NewBR == User);
10448           (void)NewBR;
10449
10450           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10451                                     Cond.getOperand(0), Cond.getOperand(1));
10452           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10453           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10454           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10455                               Chain, Dest, CC, Cmp);
10456           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10457           Cond = Cmp;
10458           addTest = false;
10459           Dest = FalseBB;
10460         }
10461       }
10462     }
10463   }
10464
10465   if (addTest) {
10466     // Look pass the truncate if the high bits are known zero.
10467     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10468         Cond = Cond.getOperand(0);
10469
10470     // We know the result of AND is compared against zero. Try to match
10471     // it to BT.
10472     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10473       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10474       if (NewSetCC.getNode()) {
10475         CC = NewSetCC.getOperand(0);
10476         Cond = NewSetCC.getOperand(1);
10477         addTest = false;
10478       }
10479     }
10480   }
10481
10482   if (addTest) {
10483     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10484     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10485   }
10486   Cond = ConvertCmpIfNecessary(Cond, DAG);
10487   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10488                      Chain, Dest, CC, Cond);
10489 }
10490
10491 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10492 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10493 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10494 // that the guard pages used by the OS virtual memory manager are allocated in
10495 // correct sequence.
10496 SDValue
10497 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10498                                            SelectionDAG &DAG) const {
10499   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10500           getTargetMachine().Options.EnableSegmentedStacks) &&
10501          "This should be used only on Windows targets or when segmented stacks "
10502          "are being used");
10503   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10504   SDLoc dl(Op);
10505
10506   // Get the inputs.
10507   SDValue Chain = Op.getOperand(0);
10508   SDValue Size  = Op.getOperand(1);
10509   // FIXME: Ensure alignment here
10510
10511   bool Is64Bit = Subtarget->is64Bit();
10512   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10513
10514   if (getTargetMachine().Options.EnableSegmentedStacks) {
10515     MachineFunction &MF = DAG.getMachineFunction();
10516     MachineRegisterInfo &MRI = MF.getRegInfo();
10517
10518     if (Is64Bit) {
10519       // The 64 bit implementation of segmented stacks needs to clobber both r10
10520       // r11. This makes it impossible to use it along with nested parameters.
10521       const Function *F = MF.getFunction();
10522
10523       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10524            I != E; ++I)
10525         if (I->hasNestAttr())
10526           report_fatal_error("Cannot use segmented stacks with functions that "
10527                              "have nested arguments.");
10528     }
10529
10530     const TargetRegisterClass *AddrRegClass =
10531       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10532     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10533     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10534     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10535                                 DAG.getRegister(Vreg, SPTy));
10536     SDValue Ops1[2] = { Value, Chain };
10537     return DAG.getMergeValues(Ops1, 2, dl);
10538   } else {
10539     SDValue Flag;
10540     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10541
10542     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10543     Flag = Chain.getValue(1);
10544     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10545
10546     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10547     Flag = Chain.getValue(1);
10548
10549     const X86RegisterInfo *RegInfo =
10550       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10551     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10552                                SPTy).getValue(1);
10553
10554     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10555     return DAG.getMergeValues(Ops1, 2, dl);
10556   }
10557 }
10558
10559 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10560   MachineFunction &MF = DAG.getMachineFunction();
10561   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10562
10563   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10564   SDLoc DL(Op);
10565
10566   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10567     // vastart just stores the address of the VarArgsFrameIndex slot into the
10568     // memory location argument.
10569     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10570                                    getPointerTy());
10571     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10572                         MachinePointerInfo(SV), false, false, 0);
10573   }
10574
10575   // __va_list_tag:
10576   //   gp_offset         (0 - 6 * 8)
10577   //   fp_offset         (48 - 48 + 8 * 16)
10578   //   overflow_arg_area (point to parameters coming in memory).
10579   //   reg_save_area
10580   SmallVector<SDValue, 8> MemOps;
10581   SDValue FIN = Op.getOperand(1);
10582   // Store gp_offset
10583   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10584                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10585                                                MVT::i32),
10586                                FIN, MachinePointerInfo(SV), false, false, 0);
10587   MemOps.push_back(Store);
10588
10589   // Store fp_offset
10590   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10591                     FIN, DAG.getIntPtrConstant(4));
10592   Store = DAG.getStore(Op.getOperand(0), DL,
10593                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10594                                        MVT::i32),
10595                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10596   MemOps.push_back(Store);
10597
10598   // Store ptr to overflow_arg_area
10599   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10600                     FIN, DAG.getIntPtrConstant(4));
10601   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10602                                     getPointerTy());
10603   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10604                        MachinePointerInfo(SV, 8),
10605                        false, false, 0);
10606   MemOps.push_back(Store);
10607
10608   // Store ptr to reg_save_area.
10609   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10610                     FIN, DAG.getIntPtrConstant(8));
10611   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10612                                     getPointerTy());
10613   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10614                        MachinePointerInfo(SV, 16), false, false, 0);
10615   MemOps.push_back(Store);
10616   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10617                      &MemOps[0], MemOps.size());
10618 }
10619
10620 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10621   assert(Subtarget->is64Bit() &&
10622          "LowerVAARG only handles 64-bit va_arg!");
10623   assert((Subtarget->isTargetLinux() ||
10624           Subtarget->isTargetDarwin()) &&
10625           "Unhandled target in LowerVAARG");
10626   assert(Op.getNode()->getNumOperands() == 4);
10627   SDValue Chain = Op.getOperand(0);
10628   SDValue SrcPtr = Op.getOperand(1);
10629   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10630   unsigned Align = Op.getConstantOperandVal(3);
10631   SDLoc dl(Op);
10632
10633   EVT ArgVT = Op.getNode()->getValueType(0);
10634   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10635   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10636   uint8_t ArgMode;
10637
10638   // Decide which area this value should be read from.
10639   // TODO: Implement the AMD64 ABI in its entirety. This simple
10640   // selection mechanism works only for the basic types.
10641   if (ArgVT == MVT::f80) {
10642     llvm_unreachable("va_arg for f80 not yet implemented");
10643   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10644     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10645   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10646     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10647   } else {
10648     llvm_unreachable("Unhandled argument type in LowerVAARG");
10649   }
10650
10651   if (ArgMode == 2) {
10652     // Sanity Check: Make sure using fp_offset makes sense.
10653     assert(!getTargetMachine().Options.UseSoftFloat &&
10654            !(DAG.getMachineFunction()
10655                 .getFunction()->getAttributes()
10656                 .hasAttribute(AttributeSet::FunctionIndex,
10657                               Attribute::NoImplicitFloat)) &&
10658            Subtarget->hasSSE1());
10659   }
10660
10661   // Insert VAARG_64 node into the DAG
10662   // VAARG_64 returns two values: Variable Argument Address, Chain
10663   SmallVector<SDValue, 11> InstOps;
10664   InstOps.push_back(Chain);
10665   InstOps.push_back(SrcPtr);
10666   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10667   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10668   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10669   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10670   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10671                                           VTs, &InstOps[0], InstOps.size(),
10672                                           MVT::i64,
10673                                           MachinePointerInfo(SV),
10674                                           /*Align=*/0,
10675                                           /*Volatile=*/false,
10676                                           /*ReadMem=*/true,
10677                                           /*WriteMem=*/true);
10678   Chain = VAARG.getValue(1);
10679
10680   // Load the next argument and return it
10681   return DAG.getLoad(ArgVT, dl,
10682                      Chain,
10683                      VAARG,
10684                      MachinePointerInfo(),
10685                      false, false, false, 0);
10686 }
10687
10688 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10689                            SelectionDAG &DAG) {
10690   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10691   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10692   SDValue Chain = Op.getOperand(0);
10693   SDValue DstPtr = Op.getOperand(1);
10694   SDValue SrcPtr = Op.getOperand(2);
10695   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10696   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10697   SDLoc DL(Op);
10698
10699   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10700                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10701                        false,
10702                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10703 }
10704
10705 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10706 // may or may not be a constant. Takes immediate version of shift as input.
10707 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10708                                    SDValue SrcOp, SDValue ShAmt,
10709                                    SelectionDAG &DAG) {
10710   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10711
10712   if (isa<ConstantSDNode>(ShAmt)) {
10713     // Constant may be a TargetConstant. Use a regular constant.
10714     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10715     switch (Opc) {
10716       default: llvm_unreachable("Unknown target vector shift node");
10717       case X86ISD::VSHLI:
10718       case X86ISD::VSRLI:
10719       case X86ISD::VSRAI:
10720         return DAG.getNode(Opc, dl, VT, SrcOp,
10721                            DAG.getConstant(ShiftAmt, MVT::i32));
10722     }
10723   }
10724
10725   // Change opcode to non-immediate version
10726   switch (Opc) {
10727     default: llvm_unreachable("Unknown target vector shift node");
10728     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10729     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10730     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10731   }
10732
10733   // Need to build a vector containing shift amount
10734   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10735   SDValue ShOps[4];
10736   ShOps[0] = ShAmt;
10737   ShOps[1] = DAG.getConstant(0, MVT::i32);
10738   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10739   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10740
10741   // The return type has to be a 128-bit type with the same element
10742   // type as the input type.
10743   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10744   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10745
10746   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10747   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10748 }
10749
10750 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10751   SDLoc dl(Op);
10752   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10753   switch (IntNo) {
10754   default: return SDValue();    // Don't custom lower most intrinsics.
10755   // Comparison intrinsics.
10756   case Intrinsic::x86_sse_comieq_ss:
10757   case Intrinsic::x86_sse_comilt_ss:
10758   case Intrinsic::x86_sse_comile_ss:
10759   case Intrinsic::x86_sse_comigt_ss:
10760   case Intrinsic::x86_sse_comige_ss:
10761   case Intrinsic::x86_sse_comineq_ss:
10762   case Intrinsic::x86_sse_ucomieq_ss:
10763   case Intrinsic::x86_sse_ucomilt_ss:
10764   case Intrinsic::x86_sse_ucomile_ss:
10765   case Intrinsic::x86_sse_ucomigt_ss:
10766   case Intrinsic::x86_sse_ucomige_ss:
10767   case Intrinsic::x86_sse_ucomineq_ss:
10768   case Intrinsic::x86_sse2_comieq_sd:
10769   case Intrinsic::x86_sse2_comilt_sd:
10770   case Intrinsic::x86_sse2_comile_sd:
10771   case Intrinsic::x86_sse2_comigt_sd:
10772   case Intrinsic::x86_sse2_comige_sd:
10773   case Intrinsic::x86_sse2_comineq_sd:
10774   case Intrinsic::x86_sse2_ucomieq_sd:
10775   case Intrinsic::x86_sse2_ucomilt_sd:
10776   case Intrinsic::x86_sse2_ucomile_sd:
10777   case Intrinsic::x86_sse2_ucomigt_sd:
10778   case Intrinsic::x86_sse2_ucomige_sd:
10779   case Intrinsic::x86_sse2_ucomineq_sd: {
10780     unsigned Opc;
10781     ISD::CondCode CC;
10782     switch (IntNo) {
10783     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10784     case Intrinsic::x86_sse_comieq_ss:
10785     case Intrinsic::x86_sse2_comieq_sd:
10786       Opc = X86ISD::COMI;
10787       CC = ISD::SETEQ;
10788       break;
10789     case Intrinsic::x86_sse_comilt_ss:
10790     case Intrinsic::x86_sse2_comilt_sd:
10791       Opc = X86ISD::COMI;
10792       CC = ISD::SETLT;
10793       break;
10794     case Intrinsic::x86_sse_comile_ss:
10795     case Intrinsic::x86_sse2_comile_sd:
10796       Opc = X86ISD::COMI;
10797       CC = ISD::SETLE;
10798       break;
10799     case Intrinsic::x86_sse_comigt_ss:
10800     case Intrinsic::x86_sse2_comigt_sd:
10801       Opc = X86ISD::COMI;
10802       CC = ISD::SETGT;
10803       break;
10804     case Intrinsic::x86_sse_comige_ss:
10805     case Intrinsic::x86_sse2_comige_sd:
10806       Opc = X86ISD::COMI;
10807       CC = ISD::SETGE;
10808       break;
10809     case Intrinsic::x86_sse_comineq_ss:
10810     case Intrinsic::x86_sse2_comineq_sd:
10811       Opc = X86ISD::COMI;
10812       CC = ISD::SETNE;
10813       break;
10814     case Intrinsic::x86_sse_ucomieq_ss:
10815     case Intrinsic::x86_sse2_ucomieq_sd:
10816       Opc = X86ISD::UCOMI;
10817       CC = ISD::SETEQ;
10818       break;
10819     case Intrinsic::x86_sse_ucomilt_ss:
10820     case Intrinsic::x86_sse2_ucomilt_sd:
10821       Opc = X86ISD::UCOMI;
10822       CC = ISD::SETLT;
10823       break;
10824     case Intrinsic::x86_sse_ucomile_ss:
10825     case Intrinsic::x86_sse2_ucomile_sd:
10826       Opc = X86ISD::UCOMI;
10827       CC = ISD::SETLE;
10828       break;
10829     case Intrinsic::x86_sse_ucomigt_ss:
10830     case Intrinsic::x86_sse2_ucomigt_sd:
10831       Opc = X86ISD::UCOMI;
10832       CC = ISD::SETGT;
10833       break;
10834     case Intrinsic::x86_sse_ucomige_ss:
10835     case Intrinsic::x86_sse2_ucomige_sd:
10836       Opc = X86ISD::UCOMI;
10837       CC = ISD::SETGE;
10838       break;
10839     case Intrinsic::x86_sse_ucomineq_ss:
10840     case Intrinsic::x86_sse2_ucomineq_sd:
10841       Opc = X86ISD::UCOMI;
10842       CC = ISD::SETNE;
10843       break;
10844     }
10845
10846     SDValue LHS = Op.getOperand(1);
10847     SDValue RHS = Op.getOperand(2);
10848     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10849     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10850     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10851     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10852                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10853     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10854   }
10855
10856   // Arithmetic intrinsics.
10857   case Intrinsic::x86_sse2_pmulu_dq:
10858   case Intrinsic::x86_avx2_pmulu_dq:
10859     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10860                        Op.getOperand(1), Op.getOperand(2));
10861
10862   // SSE2/AVX2 sub with unsigned saturation intrinsics
10863   case Intrinsic::x86_sse2_psubus_b:
10864   case Intrinsic::x86_sse2_psubus_w:
10865   case Intrinsic::x86_avx2_psubus_b:
10866   case Intrinsic::x86_avx2_psubus_w:
10867     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10868                        Op.getOperand(1), Op.getOperand(2));
10869
10870   // SSE3/AVX horizontal add/sub intrinsics
10871   case Intrinsic::x86_sse3_hadd_ps:
10872   case Intrinsic::x86_sse3_hadd_pd:
10873   case Intrinsic::x86_avx_hadd_ps_256:
10874   case Intrinsic::x86_avx_hadd_pd_256:
10875   case Intrinsic::x86_sse3_hsub_ps:
10876   case Intrinsic::x86_sse3_hsub_pd:
10877   case Intrinsic::x86_avx_hsub_ps_256:
10878   case Intrinsic::x86_avx_hsub_pd_256:
10879   case Intrinsic::x86_ssse3_phadd_w_128:
10880   case Intrinsic::x86_ssse3_phadd_d_128:
10881   case Intrinsic::x86_avx2_phadd_w:
10882   case Intrinsic::x86_avx2_phadd_d:
10883   case Intrinsic::x86_ssse3_phsub_w_128:
10884   case Intrinsic::x86_ssse3_phsub_d_128:
10885   case Intrinsic::x86_avx2_phsub_w:
10886   case Intrinsic::x86_avx2_phsub_d: {
10887     unsigned Opcode;
10888     switch (IntNo) {
10889     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10890     case Intrinsic::x86_sse3_hadd_ps:
10891     case Intrinsic::x86_sse3_hadd_pd:
10892     case Intrinsic::x86_avx_hadd_ps_256:
10893     case Intrinsic::x86_avx_hadd_pd_256:
10894       Opcode = X86ISD::FHADD;
10895       break;
10896     case Intrinsic::x86_sse3_hsub_ps:
10897     case Intrinsic::x86_sse3_hsub_pd:
10898     case Intrinsic::x86_avx_hsub_ps_256:
10899     case Intrinsic::x86_avx_hsub_pd_256:
10900       Opcode = X86ISD::FHSUB;
10901       break;
10902     case Intrinsic::x86_ssse3_phadd_w_128:
10903     case Intrinsic::x86_ssse3_phadd_d_128:
10904     case Intrinsic::x86_avx2_phadd_w:
10905     case Intrinsic::x86_avx2_phadd_d:
10906       Opcode = X86ISD::HADD;
10907       break;
10908     case Intrinsic::x86_ssse3_phsub_w_128:
10909     case Intrinsic::x86_ssse3_phsub_d_128:
10910     case Intrinsic::x86_avx2_phsub_w:
10911     case Intrinsic::x86_avx2_phsub_d:
10912       Opcode = X86ISD::HSUB;
10913       break;
10914     }
10915     return DAG.getNode(Opcode, dl, Op.getValueType(),
10916                        Op.getOperand(1), Op.getOperand(2));
10917   }
10918
10919   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10920   case Intrinsic::x86_sse2_pmaxu_b:
10921   case Intrinsic::x86_sse41_pmaxuw:
10922   case Intrinsic::x86_sse41_pmaxud:
10923   case Intrinsic::x86_avx2_pmaxu_b:
10924   case Intrinsic::x86_avx2_pmaxu_w:
10925   case Intrinsic::x86_avx2_pmaxu_d:
10926   case Intrinsic::x86_sse2_pminu_b:
10927   case Intrinsic::x86_sse41_pminuw:
10928   case Intrinsic::x86_sse41_pminud:
10929   case Intrinsic::x86_avx2_pminu_b:
10930   case Intrinsic::x86_avx2_pminu_w:
10931   case Intrinsic::x86_avx2_pminu_d:
10932   case Intrinsic::x86_sse41_pmaxsb:
10933   case Intrinsic::x86_sse2_pmaxs_w:
10934   case Intrinsic::x86_sse41_pmaxsd:
10935   case Intrinsic::x86_avx2_pmaxs_b:
10936   case Intrinsic::x86_avx2_pmaxs_w:
10937   case Intrinsic::x86_avx2_pmaxs_d:
10938   case Intrinsic::x86_sse41_pminsb:
10939   case Intrinsic::x86_sse2_pmins_w:
10940   case Intrinsic::x86_sse41_pminsd:
10941   case Intrinsic::x86_avx2_pmins_b:
10942   case Intrinsic::x86_avx2_pmins_w:
10943   case Intrinsic::x86_avx2_pmins_d: {
10944     unsigned Opcode;
10945     switch (IntNo) {
10946     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10947     case Intrinsic::x86_sse2_pmaxu_b:
10948     case Intrinsic::x86_sse41_pmaxuw:
10949     case Intrinsic::x86_sse41_pmaxud:
10950     case Intrinsic::x86_avx2_pmaxu_b:
10951     case Intrinsic::x86_avx2_pmaxu_w:
10952     case Intrinsic::x86_avx2_pmaxu_d:
10953       Opcode = X86ISD::UMAX;
10954       break;
10955     case Intrinsic::x86_sse2_pminu_b:
10956     case Intrinsic::x86_sse41_pminuw:
10957     case Intrinsic::x86_sse41_pminud:
10958     case Intrinsic::x86_avx2_pminu_b:
10959     case Intrinsic::x86_avx2_pminu_w:
10960     case Intrinsic::x86_avx2_pminu_d:
10961       Opcode = X86ISD::UMIN;
10962       break;
10963     case Intrinsic::x86_sse41_pmaxsb:
10964     case Intrinsic::x86_sse2_pmaxs_w:
10965     case Intrinsic::x86_sse41_pmaxsd:
10966     case Intrinsic::x86_avx2_pmaxs_b:
10967     case Intrinsic::x86_avx2_pmaxs_w:
10968     case Intrinsic::x86_avx2_pmaxs_d:
10969       Opcode = X86ISD::SMAX;
10970       break;
10971     case Intrinsic::x86_sse41_pminsb:
10972     case Intrinsic::x86_sse2_pmins_w:
10973     case Intrinsic::x86_sse41_pminsd:
10974     case Intrinsic::x86_avx2_pmins_b:
10975     case Intrinsic::x86_avx2_pmins_w:
10976     case Intrinsic::x86_avx2_pmins_d:
10977       Opcode = X86ISD::SMIN;
10978       break;
10979     }
10980     return DAG.getNode(Opcode, dl, Op.getValueType(),
10981                        Op.getOperand(1), Op.getOperand(2));
10982   }
10983
10984   // SSE/SSE2/AVX floating point max/min intrinsics.
10985   case Intrinsic::x86_sse_max_ps:
10986   case Intrinsic::x86_sse2_max_pd:
10987   case Intrinsic::x86_avx_max_ps_256:
10988   case Intrinsic::x86_avx_max_pd_256:
10989   case Intrinsic::x86_sse_min_ps:
10990   case Intrinsic::x86_sse2_min_pd:
10991   case Intrinsic::x86_avx_min_ps_256:
10992   case Intrinsic::x86_avx_min_pd_256: {
10993     unsigned Opcode;
10994     switch (IntNo) {
10995     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10996     case Intrinsic::x86_sse_max_ps:
10997     case Intrinsic::x86_sse2_max_pd:
10998     case Intrinsic::x86_avx_max_ps_256:
10999     case Intrinsic::x86_avx_max_pd_256:
11000       Opcode = X86ISD::FMAX;
11001       break;
11002     case Intrinsic::x86_sse_min_ps:
11003     case Intrinsic::x86_sse2_min_pd:
11004     case Intrinsic::x86_avx_min_ps_256:
11005     case Intrinsic::x86_avx_min_pd_256:
11006       Opcode = X86ISD::FMIN;
11007       break;
11008     }
11009     return DAG.getNode(Opcode, dl, Op.getValueType(),
11010                        Op.getOperand(1), Op.getOperand(2));
11011   }
11012
11013   // AVX2 variable shift intrinsics
11014   case Intrinsic::x86_avx2_psllv_d:
11015   case Intrinsic::x86_avx2_psllv_q:
11016   case Intrinsic::x86_avx2_psllv_d_256:
11017   case Intrinsic::x86_avx2_psllv_q_256:
11018   case Intrinsic::x86_avx2_psrlv_d:
11019   case Intrinsic::x86_avx2_psrlv_q:
11020   case Intrinsic::x86_avx2_psrlv_d_256:
11021   case Intrinsic::x86_avx2_psrlv_q_256:
11022   case Intrinsic::x86_avx2_psrav_d:
11023   case Intrinsic::x86_avx2_psrav_d_256: {
11024     unsigned Opcode;
11025     switch (IntNo) {
11026     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11027     case Intrinsic::x86_avx2_psllv_d:
11028     case Intrinsic::x86_avx2_psllv_q:
11029     case Intrinsic::x86_avx2_psllv_d_256:
11030     case Intrinsic::x86_avx2_psllv_q_256:
11031       Opcode = ISD::SHL;
11032       break;
11033     case Intrinsic::x86_avx2_psrlv_d:
11034     case Intrinsic::x86_avx2_psrlv_q:
11035     case Intrinsic::x86_avx2_psrlv_d_256:
11036     case Intrinsic::x86_avx2_psrlv_q_256:
11037       Opcode = ISD::SRL;
11038       break;
11039     case Intrinsic::x86_avx2_psrav_d:
11040     case Intrinsic::x86_avx2_psrav_d_256:
11041       Opcode = ISD::SRA;
11042       break;
11043     }
11044     return DAG.getNode(Opcode, dl, Op.getValueType(),
11045                        Op.getOperand(1), Op.getOperand(2));
11046   }
11047
11048   case Intrinsic::x86_ssse3_pshuf_b_128:
11049   case Intrinsic::x86_avx2_pshuf_b:
11050     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11051                        Op.getOperand(1), Op.getOperand(2));
11052
11053   case Intrinsic::x86_ssse3_psign_b_128:
11054   case Intrinsic::x86_ssse3_psign_w_128:
11055   case Intrinsic::x86_ssse3_psign_d_128:
11056   case Intrinsic::x86_avx2_psign_b:
11057   case Intrinsic::x86_avx2_psign_w:
11058   case Intrinsic::x86_avx2_psign_d:
11059     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11060                        Op.getOperand(1), Op.getOperand(2));
11061
11062   case Intrinsic::x86_sse41_insertps:
11063     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11064                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11065
11066   case Intrinsic::x86_avx_vperm2f128_ps_256:
11067   case Intrinsic::x86_avx_vperm2f128_pd_256:
11068   case Intrinsic::x86_avx_vperm2f128_si_256:
11069   case Intrinsic::x86_avx2_vperm2i128:
11070     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11071                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11072
11073   case Intrinsic::x86_avx2_permd:
11074   case Intrinsic::x86_avx2_permps:
11075     // Operands intentionally swapped. Mask is last operand to intrinsic,
11076     // but second operand for node/intruction.
11077     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11078                        Op.getOperand(2), Op.getOperand(1));
11079
11080   case Intrinsic::x86_sse_sqrt_ps:
11081   case Intrinsic::x86_sse2_sqrt_pd:
11082   case Intrinsic::x86_avx_sqrt_ps_256:
11083   case Intrinsic::x86_avx_sqrt_pd_256:
11084     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11085
11086   // ptest and testp intrinsics. The intrinsic these come from are designed to
11087   // return an integer value, not just an instruction so lower it to the ptest
11088   // or testp pattern and a setcc for the result.
11089   case Intrinsic::x86_sse41_ptestz:
11090   case Intrinsic::x86_sse41_ptestc:
11091   case Intrinsic::x86_sse41_ptestnzc:
11092   case Intrinsic::x86_avx_ptestz_256:
11093   case Intrinsic::x86_avx_ptestc_256:
11094   case Intrinsic::x86_avx_ptestnzc_256:
11095   case Intrinsic::x86_avx_vtestz_ps:
11096   case Intrinsic::x86_avx_vtestc_ps:
11097   case Intrinsic::x86_avx_vtestnzc_ps:
11098   case Intrinsic::x86_avx_vtestz_pd:
11099   case Intrinsic::x86_avx_vtestc_pd:
11100   case Intrinsic::x86_avx_vtestnzc_pd:
11101   case Intrinsic::x86_avx_vtestz_ps_256:
11102   case Intrinsic::x86_avx_vtestc_ps_256:
11103   case Intrinsic::x86_avx_vtestnzc_ps_256:
11104   case Intrinsic::x86_avx_vtestz_pd_256:
11105   case Intrinsic::x86_avx_vtestc_pd_256:
11106   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11107     bool IsTestPacked = false;
11108     unsigned X86CC;
11109     switch (IntNo) {
11110     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11111     case Intrinsic::x86_avx_vtestz_ps:
11112     case Intrinsic::x86_avx_vtestz_pd:
11113     case Intrinsic::x86_avx_vtestz_ps_256:
11114     case Intrinsic::x86_avx_vtestz_pd_256:
11115       IsTestPacked = true; // Fallthrough
11116     case Intrinsic::x86_sse41_ptestz:
11117     case Intrinsic::x86_avx_ptestz_256:
11118       // ZF = 1
11119       X86CC = X86::COND_E;
11120       break;
11121     case Intrinsic::x86_avx_vtestc_ps:
11122     case Intrinsic::x86_avx_vtestc_pd:
11123     case Intrinsic::x86_avx_vtestc_ps_256:
11124     case Intrinsic::x86_avx_vtestc_pd_256:
11125       IsTestPacked = true; // Fallthrough
11126     case Intrinsic::x86_sse41_ptestc:
11127     case Intrinsic::x86_avx_ptestc_256:
11128       // CF = 1
11129       X86CC = X86::COND_B;
11130       break;
11131     case Intrinsic::x86_avx_vtestnzc_ps:
11132     case Intrinsic::x86_avx_vtestnzc_pd:
11133     case Intrinsic::x86_avx_vtestnzc_ps_256:
11134     case Intrinsic::x86_avx_vtestnzc_pd_256:
11135       IsTestPacked = true; // Fallthrough
11136     case Intrinsic::x86_sse41_ptestnzc:
11137     case Intrinsic::x86_avx_ptestnzc_256:
11138       // ZF and CF = 0
11139       X86CC = X86::COND_A;
11140       break;
11141     }
11142
11143     SDValue LHS = Op.getOperand(1);
11144     SDValue RHS = Op.getOperand(2);
11145     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11146     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11147     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11148     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11149     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11150   }
11151
11152   // SSE/AVX shift intrinsics
11153   case Intrinsic::x86_sse2_psll_w:
11154   case Intrinsic::x86_sse2_psll_d:
11155   case Intrinsic::x86_sse2_psll_q:
11156   case Intrinsic::x86_avx2_psll_w:
11157   case Intrinsic::x86_avx2_psll_d:
11158   case Intrinsic::x86_avx2_psll_q:
11159   case Intrinsic::x86_sse2_psrl_w:
11160   case Intrinsic::x86_sse2_psrl_d:
11161   case Intrinsic::x86_sse2_psrl_q:
11162   case Intrinsic::x86_avx2_psrl_w:
11163   case Intrinsic::x86_avx2_psrl_d:
11164   case Intrinsic::x86_avx2_psrl_q:
11165   case Intrinsic::x86_sse2_psra_w:
11166   case Intrinsic::x86_sse2_psra_d:
11167   case Intrinsic::x86_avx2_psra_w:
11168   case Intrinsic::x86_avx2_psra_d: {
11169     unsigned Opcode;
11170     switch (IntNo) {
11171     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11172     case Intrinsic::x86_sse2_psll_w:
11173     case Intrinsic::x86_sse2_psll_d:
11174     case Intrinsic::x86_sse2_psll_q:
11175     case Intrinsic::x86_avx2_psll_w:
11176     case Intrinsic::x86_avx2_psll_d:
11177     case Intrinsic::x86_avx2_psll_q:
11178       Opcode = X86ISD::VSHL;
11179       break;
11180     case Intrinsic::x86_sse2_psrl_w:
11181     case Intrinsic::x86_sse2_psrl_d:
11182     case Intrinsic::x86_sse2_psrl_q:
11183     case Intrinsic::x86_avx2_psrl_w:
11184     case Intrinsic::x86_avx2_psrl_d:
11185     case Intrinsic::x86_avx2_psrl_q:
11186       Opcode = X86ISD::VSRL;
11187       break;
11188     case Intrinsic::x86_sse2_psra_w:
11189     case Intrinsic::x86_sse2_psra_d:
11190     case Intrinsic::x86_avx2_psra_w:
11191     case Intrinsic::x86_avx2_psra_d:
11192       Opcode = X86ISD::VSRA;
11193       break;
11194     }
11195     return DAG.getNode(Opcode, dl, Op.getValueType(),
11196                        Op.getOperand(1), Op.getOperand(2));
11197   }
11198
11199   // SSE/AVX immediate shift intrinsics
11200   case Intrinsic::x86_sse2_pslli_w:
11201   case Intrinsic::x86_sse2_pslli_d:
11202   case Intrinsic::x86_sse2_pslli_q:
11203   case Intrinsic::x86_avx2_pslli_w:
11204   case Intrinsic::x86_avx2_pslli_d:
11205   case Intrinsic::x86_avx2_pslli_q:
11206   case Intrinsic::x86_sse2_psrli_w:
11207   case Intrinsic::x86_sse2_psrli_d:
11208   case Intrinsic::x86_sse2_psrli_q:
11209   case Intrinsic::x86_avx2_psrli_w:
11210   case Intrinsic::x86_avx2_psrli_d:
11211   case Intrinsic::x86_avx2_psrli_q:
11212   case Intrinsic::x86_sse2_psrai_w:
11213   case Intrinsic::x86_sse2_psrai_d:
11214   case Intrinsic::x86_avx2_psrai_w:
11215   case Intrinsic::x86_avx2_psrai_d: {
11216     unsigned Opcode;
11217     switch (IntNo) {
11218     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11219     case Intrinsic::x86_sse2_pslli_w:
11220     case Intrinsic::x86_sse2_pslli_d:
11221     case Intrinsic::x86_sse2_pslli_q:
11222     case Intrinsic::x86_avx2_pslli_w:
11223     case Intrinsic::x86_avx2_pslli_d:
11224     case Intrinsic::x86_avx2_pslli_q:
11225       Opcode = X86ISD::VSHLI;
11226       break;
11227     case Intrinsic::x86_sse2_psrli_w:
11228     case Intrinsic::x86_sse2_psrli_d:
11229     case Intrinsic::x86_sse2_psrli_q:
11230     case Intrinsic::x86_avx2_psrli_w:
11231     case Intrinsic::x86_avx2_psrli_d:
11232     case Intrinsic::x86_avx2_psrli_q:
11233       Opcode = X86ISD::VSRLI;
11234       break;
11235     case Intrinsic::x86_sse2_psrai_w:
11236     case Intrinsic::x86_sse2_psrai_d:
11237     case Intrinsic::x86_avx2_psrai_w:
11238     case Intrinsic::x86_avx2_psrai_d:
11239       Opcode = X86ISD::VSRAI;
11240       break;
11241     }
11242     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11243                                Op.getOperand(1), Op.getOperand(2), DAG);
11244   }
11245
11246   case Intrinsic::x86_sse42_pcmpistria128:
11247   case Intrinsic::x86_sse42_pcmpestria128:
11248   case Intrinsic::x86_sse42_pcmpistric128:
11249   case Intrinsic::x86_sse42_pcmpestric128:
11250   case Intrinsic::x86_sse42_pcmpistrio128:
11251   case Intrinsic::x86_sse42_pcmpestrio128:
11252   case Intrinsic::x86_sse42_pcmpistris128:
11253   case Intrinsic::x86_sse42_pcmpestris128:
11254   case Intrinsic::x86_sse42_pcmpistriz128:
11255   case Intrinsic::x86_sse42_pcmpestriz128: {
11256     unsigned Opcode;
11257     unsigned X86CC;
11258     switch (IntNo) {
11259     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11260     case Intrinsic::x86_sse42_pcmpistria128:
11261       Opcode = X86ISD::PCMPISTRI;
11262       X86CC = X86::COND_A;
11263       break;
11264     case Intrinsic::x86_sse42_pcmpestria128:
11265       Opcode = X86ISD::PCMPESTRI;
11266       X86CC = X86::COND_A;
11267       break;
11268     case Intrinsic::x86_sse42_pcmpistric128:
11269       Opcode = X86ISD::PCMPISTRI;
11270       X86CC = X86::COND_B;
11271       break;
11272     case Intrinsic::x86_sse42_pcmpestric128:
11273       Opcode = X86ISD::PCMPESTRI;
11274       X86CC = X86::COND_B;
11275       break;
11276     case Intrinsic::x86_sse42_pcmpistrio128:
11277       Opcode = X86ISD::PCMPISTRI;
11278       X86CC = X86::COND_O;
11279       break;
11280     case Intrinsic::x86_sse42_pcmpestrio128:
11281       Opcode = X86ISD::PCMPESTRI;
11282       X86CC = X86::COND_O;
11283       break;
11284     case Intrinsic::x86_sse42_pcmpistris128:
11285       Opcode = X86ISD::PCMPISTRI;
11286       X86CC = X86::COND_S;
11287       break;
11288     case Intrinsic::x86_sse42_pcmpestris128:
11289       Opcode = X86ISD::PCMPESTRI;
11290       X86CC = X86::COND_S;
11291       break;
11292     case Intrinsic::x86_sse42_pcmpistriz128:
11293       Opcode = X86ISD::PCMPISTRI;
11294       X86CC = X86::COND_E;
11295       break;
11296     case Intrinsic::x86_sse42_pcmpestriz128:
11297       Opcode = X86ISD::PCMPESTRI;
11298       X86CC = X86::COND_E;
11299       break;
11300     }
11301     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11302     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11303     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11304     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11305                                 DAG.getConstant(X86CC, MVT::i8),
11306                                 SDValue(PCMP.getNode(), 1));
11307     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11308   }
11309
11310   case Intrinsic::x86_sse42_pcmpistri128:
11311   case Intrinsic::x86_sse42_pcmpestri128: {
11312     unsigned Opcode;
11313     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11314       Opcode = X86ISD::PCMPISTRI;
11315     else
11316       Opcode = X86ISD::PCMPESTRI;
11317
11318     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11319     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11320     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11321   }
11322   case Intrinsic::x86_fma_vfmadd_ps:
11323   case Intrinsic::x86_fma_vfmadd_pd:
11324   case Intrinsic::x86_fma_vfmsub_ps:
11325   case Intrinsic::x86_fma_vfmsub_pd:
11326   case Intrinsic::x86_fma_vfnmadd_ps:
11327   case Intrinsic::x86_fma_vfnmadd_pd:
11328   case Intrinsic::x86_fma_vfnmsub_ps:
11329   case Intrinsic::x86_fma_vfnmsub_pd:
11330   case Intrinsic::x86_fma_vfmaddsub_ps:
11331   case Intrinsic::x86_fma_vfmaddsub_pd:
11332   case Intrinsic::x86_fma_vfmsubadd_ps:
11333   case Intrinsic::x86_fma_vfmsubadd_pd:
11334   case Intrinsic::x86_fma_vfmadd_ps_256:
11335   case Intrinsic::x86_fma_vfmadd_pd_256:
11336   case Intrinsic::x86_fma_vfmsub_ps_256:
11337   case Intrinsic::x86_fma_vfmsub_pd_256:
11338   case Intrinsic::x86_fma_vfnmadd_ps_256:
11339   case Intrinsic::x86_fma_vfnmadd_pd_256:
11340   case Intrinsic::x86_fma_vfnmsub_ps_256:
11341   case Intrinsic::x86_fma_vfnmsub_pd_256:
11342   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11343   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11344   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11345   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11346     unsigned Opc;
11347     switch (IntNo) {
11348     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11349     case Intrinsic::x86_fma_vfmadd_ps:
11350     case Intrinsic::x86_fma_vfmadd_pd:
11351     case Intrinsic::x86_fma_vfmadd_ps_256:
11352     case Intrinsic::x86_fma_vfmadd_pd_256:
11353       Opc = X86ISD::FMADD;
11354       break;
11355     case Intrinsic::x86_fma_vfmsub_ps:
11356     case Intrinsic::x86_fma_vfmsub_pd:
11357     case Intrinsic::x86_fma_vfmsub_ps_256:
11358     case Intrinsic::x86_fma_vfmsub_pd_256:
11359       Opc = X86ISD::FMSUB;
11360       break;
11361     case Intrinsic::x86_fma_vfnmadd_ps:
11362     case Intrinsic::x86_fma_vfnmadd_pd:
11363     case Intrinsic::x86_fma_vfnmadd_ps_256:
11364     case Intrinsic::x86_fma_vfnmadd_pd_256:
11365       Opc = X86ISD::FNMADD;
11366       break;
11367     case Intrinsic::x86_fma_vfnmsub_ps:
11368     case Intrinsic::x86_fma_vfnmsub_pd:
11369     case Intrinsic::x86_fma_vfnmsub_ps_256:
11370     case Intrinsic::x86_fma_vfnmsub_pd_256:
11371       Opc = X86ISD::FNMSUB;
11372       break;
11373     case Intrinsic::x86_fma_vfmaddsub_ps:
11374     case Intrinsic::x86_fma_vfmaddsub_pd:
11375     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11376     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11377       Opc = X86ISD::FMADDSUB;
11378       break;
11379     case Intrinsic::x86_fma_vfmsubadd_ps:
11380     case Intrinsic::x86_fma_vfmsubadd_pd:
11381     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11382     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11383       Opc = X86ISD::FMSUBADD;
11384       break;
11385     }
11386
11387     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11388                        Op.getOperand(2), Op.getOperand(3));
11389   }
11390   }
11391 }
11392
11393 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11394   SDLoc dl(Op);
11395   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11396   switch (IntNo) {
11397   default: return SDValue();    // Don't custom lower most intrinsics.
11398
11399   // RDRAND/RDSEED intrinsics.
11400   case Intrinsic::x86_rdrand_16:
11401   case Intrinsic::x86_rdrand_32:
11402   case Intrinsic::x86_rdrand_64:
11403   case Intrinsic::x86_rdseed_16:
11404   case Intrinsic::x86_rdseed_32:
11405   case Intrinsic::x86_rdseed_64: {
11406     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11407                        IntNo == Intrinsic::x86_rdseed_32 ||
11408                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11409                                                             X86ISD::RDRAND;
11410     // Emit the node with the right value type.
11411     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11412     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11413
11414     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11415     // Otherwise return the value from Rand, which is always 0, casted to i32.
11416     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11417                       DAG.getConstant(1, Op->getValueType(1)),
11418                       DAG.getConstant(X86::COND_B, MVT::i32),
11419                       SDValue(Result.getNode(), 1) };
11420     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11421                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11422                                   Ops, array_lengthof(Ops));
11423
11424     // Return { result, isValid, chain }.
11425     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11426                        SDValue(Result.getNode(), 2));
11427   }
11428
11429   // XTEST intrinsics.
11430   case Intrinsic::x86_xtest: {
11431     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11432     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11433     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11434                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11435                                 InTrans);
11436     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11437     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11438                        Ret, SDValue(InTrans.getNode(), 1));
11439   }
11440   }
11441 }
11442
11443 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11444                                            SelectionDAG &DAG) const {
11445   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11446   MFI->setReturnAddressIsTaken(true);
11447
11448   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11449   SDLoc dl(Op);
11450   EVT PtrVT = getPointerTy();
11451
11452   if (Depth > 0) {
11453     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11454     const X86RegisterInfo *RegInfo =
11455       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11456     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11457     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11458                        DAG.getNode(ISD::ADD, dl, PtrVT,
11459                                    FrameAddr, Offset),
11460                        MachinePointerInfo(), false, false, false, 0);
11461   }
11462
11463   // Just load the return address.
11464   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11465   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11466                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11467 }
11468
11469 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11470   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11471   MFI->setFrameAddressIsTaken(true);
11472
11473   EVT VT = Op.getValueType();
11474   SDLoc dl(Op);  // FIXME probably not meaningful
11475   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11476   const X86RegisterInfo *RegInfo =
11477     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11478   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11479   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11480           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11481          "Invalid Frame Register!");
11482   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11483   while (Depth--)
11484     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11485                             MachinePointerInfo(),
11486                             false, false, false, 0);
11487   return FrameAddr;
11488 }
11489
11490 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11491                                                      SelectionDAG &DAG) const {
11492   const X86RegisterInfo *RegInfo =
11493     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11494   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11495 }
11496
11497 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11498   SDValue Chain     = Op.getOperand(0);
11499   SDValue Offset    = Op.getOperand(1);
11500   SDValue Handler   = Op.getOperand(2);
11501   SDLoc dl      (Op);
11502
11503   EVT PtrVT = getPointerTy();
11504   const X86RegisterInfo *RegInfo =
11505     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11506   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11507   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11508           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11509          "Invalid Frame Register!");
11510   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11511   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11512
11513   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11514                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11515   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11516   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11517                        false, false, 0);
11518   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11519
11520   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11521                      DAG.getRegister(StoreAddrReg, PtrVT));
11522 }
11523
11524 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11525                                                SelectionDAG &DAG) const {
11526   SDLoc DL(Op);
11527   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11528                      DAG.getVTList(MVT::i32, MVT::Other),
11529                      Op.getOperand(0), Op.getOperand(1));
11530 }
11531
11532 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11533                                                 SelectionDAG &DAG) const {
11534   SDLoc DL(Op);
11535   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11536                      Op.getOperand(0), Op.getOperand(1));
11537 }
11538
11539 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11540   return Op.getOperand(0);
11541 }
11542
11543 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11544                                                 SelectionDAG &DAG) const {
11545   SDValue Root = Op.getOperand(0);
11546   SDValue Trmp = Op.getOperand(1); // trampoline
11547   SDValue FPtr = Op.getOperand(2); // nested function
11548   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11549   SDLoc dl (Op);
11550
11551   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11552   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11553
11554   if (Subtarget->is64Bit()) {
11555     SDValue OutChains[6];
11556
11557     // Large code-model.
11558     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11559     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11560
11561     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11562     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11563
11564     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11565
11566     // Load the pointer to the nested function into R11.
11567     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11568     SDValue Addr = Trmp;
11569     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11570                                 Addr, MachinePointerInfo(TrmpAddr),
11571                                 false, false, 0);
11572
11573     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11574                        DAG.getConstant(2, MVT::i64));
11575     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11576                                 MachinePointerInfo(TrmpAddr, 2),
11577                                 false, false, 2);
11578
11579     // Load the 'nest' parameter value into R10.
11580     // R10 is specified in X86CallingConv.td
11581     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11582     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11583                        DAG.getConstant(10, MVT::i64));
11584     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11585                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11586                                 false, false, 0);
11587
11588     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11589                        DAG.getConstant(12, MVT::i64));
11590     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11591                                 MachinePointerInfo(TrmpAddr, 12),
11592                                 false, false, 2);
11593
11594     // Jump to the nested function.
11595     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11596     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11597                        DAG.getConstant(20, MVT::i64));
11598     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11599                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11600                                 false, false, 0);
11601
11602     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11603     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11604                        DAG.getConstant(22, MVT::i64));
11605     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11606                                 MachinePointerInfo(TrmpAddr, 22),
11607                                 false, false, 0);
11608
11609     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11610   } else {
11611     const Function *Func =
11612       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11613     CallingConv::ID CC = Func->getCallingConv();
11614     unsigned NestReg;
11615
11616     switch (CC) {
11617     default:
11618       llvm_unreachable("Unsupported calling convention");
11619     case CallingConv::C:
11620     case CallingConv::X86_StdCall: {
11621       // Pass 'nest' parameter in ECX.
11622       // Must be kept in sync with X86CallingConv.td
11623       NestReg = X86::ECX;
11624
11625       // Check that ECX wasn't needed by an 'inreg' parameter.
11626       FunctionType *FTy = Func->getFunctionType();
11627       const AttributeSet &Attrs = Func->getAttributes();
11628
11629       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11630         unsigned InRegCount = 0;
11631         unsigned Idx = 1;
11632
11633         for (FunctionType::param_iterator I = FTy->param_begin(),
11634              E = FTy->param_end(); I != E; ++I, ++Idx)
11635           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11636             // FIXME: should only count parameters that are lowered to integers.
11637             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11638
11639         if (InRegCount > 2) {
11640           report_fatal_error("Nest register in use - reduce number of inreg"
11641                              " parameters!");
11642         }
11643       }
11644       break;
11645     }
11646     case CallingConv::X86_FastCall:
11647     case CallingConv::X86_ThisCall:
11648     case CallingConv::Fast:
11649       // Pass 'nest' parameter in EAX.
11650       // Must be kept in sync with X86CallingConv.td
11651       NestReg = X86::EAX;
11652       break;
11653     }
11654
11655     SDValue OutChains[4];
11656     SDValue Addr, Disp;
11657
11658     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11659                        DAG.getConstant(10, MVT::i32));
11660     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11661
11662     // This is storing the opcode for MOV32ri.
11663     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11664     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11665     OutChains[0] = DAG.getStore(Root, dl,
11666                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11667                                 Trmp, MachinePointerInfo(TrmpAddr),
11668                                 false, false, 0);
11669
11670     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11671                        DAG.getConstant(1, MVT::i32));
11672     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11673                                 MachinePointerInfo(TrmpAddr, 1),
11674                                 false, false, 1);
11675
11676     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11677     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11678                        DAG.getConstant(5, MVT::i32));
11679     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11680                                 MachinePointerInfo(TrmpAddr, 5),
11681                                 false, false, 1);
11682
11683     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11684                        DAG.getConstant(6, MVT::i32));
11685     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11686                                 MachinePointerInfo(TrmpAddr, 6),
11687                                 false, false, 1);
11688
11689     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11690   }
11691 }
11692
11693 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11694                                             SelectionDAG &DAG) const {
11695   /*
11696    The rounding mode is in bits 11:10 of FPSR, and has the following
11697    settings:
11698      00 Round to nearest
11699      01 Round to -inf
11700      10 Round to +inf
11701      11 Round to 0
11702
11703   FLT_ROUNDS, on the other hand, expects the following:
11704     -1 Undefined
11705      0 Round to 0
11706      1 Round to nearest
11707      2 Round to +inf
11708      3 Round to -inf
11709
11710   To perform the conversion, we do:
11711     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11712   */
11713
11714   MachineFunction &MF = DAG.getMachineFunction();
11715   const TargetMachine &TM = MF.getTarget();
11716   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11717   unsigned StackAlignment = TFI.getStackAlignment();
11718   EVT VT = Op.getValueType();
11719   SDLoc DL(Op);
11720
11721   // Save FP Control Word to stack slot
11722   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11723   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11724
11725   MachineMemOperand *MMO =
11726    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11727                            MachineMemOperand::MOStore, 2, 2);
11728
11729   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11730   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11731                                           DAG.getVTList(MVT::Other),
11732                                           Ops, array_lengthof(Ops), MVT::i16,
11733                                           MMO);
11734
11735   // Load FP Control Word from stack slot
11736   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11737                             MachinePointerInfo(), false, false, false, 0);
11738
11739   // Transform as necessary
11740   SDValue CWD1 =
11741     DAG.getNode(ISD::SRL, DL, MVT::i16,
11742                 DAG.getNode(ISD::AND, DL, MVT::i16,
11743                             CWD, DAG.getConstant(0x800, MVT::i16)),
11744                 DAG.getConstant(11, MVT::i8));
11745   SDValue CWD2 =
11746     DAG.getNode(ISD::SRL, DL, MVT::i16,
11747                 DAG.getNode(ISD::AND, DL, MVT::i16,
11748                             CWD, DAG.getConstant(0x400, MVT::i16)),
11749                 DAG.getConstant(9, MVT::i8));
11750
11751   SDValue RetVal =
11752     DAG.getNode(ISD::AND, DL, MVT::i16,
11753                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11754                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11755                             DAG.getConstant(1, MVT::i16)),
11756                 DAG.getConstant(3, MVT::i16));
11757
11758   return DAG.getNode((VT.getSizeInBits() < 16 ?
11759                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11760 }
11761
11762 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11763   EVT VT = Op.getValueType();
11764   EVT OpVT = VT;
11765   unsigned NumBits = VT.getSizeInBits();
11766   SDLoc dl(Op);
11767
11768   Op = Op.getOperand(0);
11769   if (VT == MVT::i8) {
11770     // Zero extend to i32 since there is not an i8 bsr.
11771     OpVT = MVT::i32;
11772     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11773   }
11774
11775   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11776   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11777   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11778
11779   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11780   SDValue Ops[] = {
11781     Op,
11782     DAG.getConstant(NumBits+NumBits-1, OpVT),
11783     DAG.getConstant(X86::COND_E, MVT::i8),
11784     Op.getValue(1)
11785   };
11786   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11787
11788   // Finally xor with NumBits-1.
11789   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11790
11791   if (VT == MVT::i8)
11792     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11793   return Op;
11794 }
11795
11796 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11797   EVT VT = Op.getValueType();
11798   EVT OpVT = VT;
11799   unsigned NumBits = VT.getSizeInBits();
11800   SDLoc dl(Op);
11801
11802   Op = Op.getOperand(0);
11803   if (VT == MVT::i8) {
11804     // Zero extend to i32 since there is not an i8 bsr.
11805     OpVT = MVT::i32;
11806     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11807   }
11808
11809   // Issue a bsr (scan bits in reverse).
11810   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11811   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11812
11813   // And xor with NumBits-1.
11814   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11815
11816   if (VT == MVT::i8)
11817     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11818   return Op;
11819 }
11820
11821 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11822   EVT VT = Op.getValueType();
11823   unsigned NumBits = VT.getSizeInBits();
11824   SDLoc dl(Op);
11825   Op = Op.getOperand(0);
11826
11827   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11828   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11829   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11830
11831   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11832   SDValue Ops[] = {
11833     Op,
11834     DAG.getConstant(NumBits, VT),
11835     DAG.getConstant(X86::COND_E, MVT::i8),
11836     Op.getValue(1)
11837   };
11838   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11839 }
11840
11841 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11842 // ones, and then concatenate the result back.
11843 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11844   EVT VT = Op.getValueType();
11845
11846   assert(VT.is256BitVector() && VT.isInteger() &&
11847          "Unsupported value type for operation");
11848
11849   unsigned NumElems = VT.getVectorNumElements();
11850   SDLoc dl(Op);
11851
11852   // Extract the LHS vectors
11853   SDValue LHS = Op.getOperand(0);
11854   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11855   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11856
11857   // Extract the RHS vectors
11858   SDValue RHS = Op.getOperand(1);
11859   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11860   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11861
11862   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11863   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11864
11865   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11866                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11867                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11868 }
11869
11870 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11871   assert(Op.getValueType().is256BitVector() &&
11872          Op.getValueType().isInteger() &&
11873          "Only handle AVX 256-bit vector integer operation");
11874   return Lower256IntArith(Op, DAG);
11875 }
11876
11877 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11878   assert(Op.getValueType().is256BitVector() &&
11879          Op.getValueType().isInteger() &&
11880          "Only handle AVX 256-bit vector integer operation");
11881   return Lower256IntArith(Op, DAG);
11882 }
11883
11884 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11885                         SelectionDAG &DAG) {
11886   SDLoc dl(Op);
11887   EVT VT = Op.getValueType();
11888
11889   // Decompose 256-bit ops into smaller 128-bit ops.
11890   if (VT.is256BitVector() && !Subtarget->hasInt256())
11891     return Lower256IntArith(Op, DAG);
11892
11893   SDValue A = Op.getOperand(0);
11894   SDValue B = Op.getOperand(1);
11895
11896   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11897   if (VT == MVT::v4i32) {
11898     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11899            "Should not custom lower when pmuldq is available!");
11900
11901     // Extract the odd parts.
11902     static const int UnpackMask[] = { 1, -1, 3, -1 };
11903     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11904     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11905
11906     // Multiply the even parts.
11907     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11908     // Now multiply odd parts.
11909     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11910
11911     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11912     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11913
11914     // Merge the two vectors back together with a shuffle. This expands into 2
11915     // shuffles.
11916     static const int ShufMask[] = { 0, 4, 2, 6 };
11917     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11918   }
11919
11920   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11921          "Only know how to lower V2I64/V4I64 multiply");
11922
11923   //  Ahi = psrlqi(a, 32);
11924   //  Bhi = psrlqi(b, 32);
11925   //
11926   //  AloBlo = pmuludq(a, b);
11927   //  AloBhi = pmuludq(a, Bhi);
11928   //  AhiBlo = pmuludq(Ahi, b);
11929
11930   //  AloBhi = psllqi(AloBhi, 32);
11931   //  AhiBlo = psllqi(AhiBlo, 32);
11932   //  return AloBlo + AloBhi + AhiBlo;
11933
11934   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11935
11936   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11937   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11938
11939   // Bit cast to 32-bit vectors for MULUDQ
11940   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11941   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11942   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11943   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11944   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11945
11946   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11947   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11948   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11949
11950   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11951   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11952
11953   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11954   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11955 }
11956
11957 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11958   EVT VT = Op.getValueType();
11959   EVT EltTy = VT.getVectorElementType();
11960   unsigned NumElts = VT.getVectorNumElements();
11961   SDValue N0 = Op.getOperand(0);
11962   SDLoc dl(Op);
11963
11964   // Lower sdiv X, pow2-const.
11965   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11966   if (!C)
11967     return SDValue();
11968
11969   APInt SplatValue, SplatUndef;
11970   unsigned SplatBitSize;
11971   bool HasAnyUndefs;
11972   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11973                           HasAnyUndefs) ||
11974       EltTy.getSizeInBits() < SplatBitSize)
11975     return SDValue();
11976
11977   if ((SplatValue != 0) &&
11978       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11979     unsigned lg2 = SplatValue.countTrailingZeros();
11980     // Splat the sign bit.
11981     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11982     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11983     // Add (N0 < 0) ? abs2 - 1 : 0;
11984     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11985     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11986     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11987     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11988     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11989
11990     // If we're dividing by a positive value, we're done.  Otherwise, we must
11991     // negate the result.
11992     if (SplatValue.isNonNegative())
11993       return SRA;
11994
11995     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11996     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11997     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11998   }
11999   return SDValue();
12000 }
12001
12002 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12003                                          const X86Subtarget *Subtarget) {
12004   EVT VT = Op.getValueType();
12005   SDLoc dl(Op);
12006   SDValue R = Op.getOperand(0);
12007   SDValue Amt = Op.getOperand(1);
12008
12009   // Optimize shl/srl/sra with constant shift amount.
12010   if (isSplatVector(Amt.getNode())) {
12011     SDValue SclrAmt = Amt->getOperand(0);
12012     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12013       uint64_t ShiftAmt = C->getZExtValue();
12014
12015       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12016           (Subtarget->hasInt256() &&
12017            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
12018         if (Op.getOpcode() == ISD::SHL)
12019           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12020                              DAG.getConstant(ShiftAmt, MVT::i32));
12021         if (Op.getOpcode() == ISD::SRL)
12022           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12023                              DAG.getConstant(ShiftAmt, MVT::i32));
12024         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12025           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12026                              DAG.getConstant(ShiftAmt, MVT::i32));
12027       }
12028
12029       if (VT == MVT::v16i8) {
12030         if (Op.getOpcode() == ISD::SHL) {
12031           // Make a large shift.
12032           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
12033                                     DAG.getConstant(ShiftAmt, MVT::i32));
12034           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12035           // Zero out the rightmost bits.
12036           SmallVector<SDValue, 16> V(16,
12037                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12038                                                      MVT::i8));
12039           return DAG.getNode(ISD::AND, dl, VT, SHL,
12040                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12041         }
12042         if (Op.getOpcode() == ISD::SRL) {
12043           // Make a large shift.
12044           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
12045                                     DAG.getConstant(ShiftAmt, MVT::i32));
12046           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12047           // Zero out the leftmost bits.
12048           SmallVector<SDValue, 16> V(16,
12049                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12050                                                      MVT::i8));
12051           return DAG.getNode(ISD::AND, dl, VT, SRL,
12052                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12053         }
12054         if (Op.getOpcode() == ISD::SRA) {
12055           if (ShiftAmt == 7) {
12056             // R s>> 7  ===  R s< 0
12057             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12058             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12059           }
12060
12061           // R s>> a === ((R u>> a) ^ m) - m
12062           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12063           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12064                                                          MVT::i8));
12065           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12066           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12067           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12068           return Res;
12069         }
12070         llvm_unreachable("Unknown shift opcode.");
12071       }
12072
12073       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12074         if (Op.getOpcode() == ISD::SHL) {
12075           // Make a large shift.
12076           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
12077                                     DAG.getConstant(ShiftAmt, MVT::i32));
12078           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12079           // Zero out the rightmost bits.
12080           SmallVector<SDValue, 32> V(32,
12081                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12082                                                      MVT::i8));
12083           return DAG.getNode(ISD::AND, dl, VT, SHL,
12084                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12085         }
12086         if (Op.getOpcode() == ISD::SRL) {
12087           // Make a large shift.
12088           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
12089                                     DAG.getConstant(ShiftAmt, MVT::i32));
12090           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12091           // Zero out the leftmost bits.
12092           SmallVector<SDValue, 32> V(32,
12093                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12094                                                      MVT::i8));
12095           return DAG.getNode(ISD::AND, dl, VT, SRL,
12096                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12097         }
12098         if (Op.getOpcode() == ISD::SRA) {
12099           if (ShiftAmt == 7) {
12100             // R s>> 7  ===  R s< 0
12101             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12102             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12103           }
12104
12105           // R s>> a === ((R u>> a) ^ m) - m
12106           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12107           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12108                                                          MVT::i8));
12109           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12110           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12111           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12112           return Res;
12113         }
12114         llvm_unreachable("Unknown shift opcode.");
12115       }
12116     }
12117   }
12118
12119   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12120   if (!Subtarget->is64Bit() &&
12121       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12122       Amt.getOpcode() == ISD::BITCAST &&
12123       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12124     Amt = Amt.getOperand(0);
12125     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12126                      VT.getVectorNumElements();
12127     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12128     uint64_t ShiftAmt = 0;
12129     for (unsigned i = 0; i != Ratio; ++i) {
12130       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12131       if (C == 0)
12132         return SDValue();
12133       // 6 == Log2(64)
12134       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12135     }
12136     // Check remaining shift amounts.
12137     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12138       uint64_t ShAmt = 0;
12139       for (unsigned j = 0; j != Ratio; ++j) {
12140         ConstantSDNode *C =
12141           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12142         if (C == 0)
12143           return SDValue();
12144         // 6 == Log2(64)
12145         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12146       }
12147       if (ShAmt != ShiftAmt)
12148         return SDValue();
12149     }
12150     switch (Op.getOpcode()) {
12151     default:
12152       llvm_unreachable("Unknown shift opcode!");
12153     case ISD::SHL:
12154       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12155                          DAG.getConstant(ShiftAmt, MVT::i32));
12156     case ISD::SRL:
12157       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12158                          DAG.getConstant(ShiftAmt, MVT::i32));
12159     case ISD::SRA:
12160       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12161                          DAG.getConstant(ShiftAmt, MVT::i32));
12162     }
12163   }
12164
12165   return SDValue();
12166 }
12167
12168 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12169                                         const X86Subtarget* Subtarget) {
12170   EVT VT = Op.getValueType();
12171   SDLoc dl(Op);
12172   SDValue R = Op.getOperand(0);
12173   SDValue Amt = Op.getOperand(1);
12174
12175   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12176       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12177       (Subtarget->hasInt256() &&
12178        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12179         VT == MVT::v8i32 || VT == MVT::v16i16))) {
12180     SDValue BaseShAmt;
12181     EVT EltVT = VT.getVectorElementType();
12182
12183     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12184       unsigned NumElts = VT.getVectorNumElements();
12185       unsigned i, j;
12186       for (i = 0; i != NumElts; ++i) {
12187         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12188           continue;
12189         break;
12190       }
12191       for (j = i; j != NumElts; ++j) {
12192         SDValue Arg = Amt.getOperand(j);
12193         if (Arg.getOpcode() == ISD::UNDEF) continue;
12194         if (Arg != Amt.getOperand(i))
12195           break;
12196       }
12197       if (i != NumElts && j == NumElts)
12198         BaseShAmt = Amt.getOperand(i);
12199     } else {
12200       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12201         Amt = Amt.getOperand(0);
12202       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12203                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12204         SDValue InVec = Amt.getOperand(0);
12205         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12206           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12207           unsigned i = 0;
12208           for (; i != NumElts; ++i) {
12209             SDValue Arg = InVec.getOperand(i);
12210             if (Arg.getOpcode() == ISD::UNDEF) continue;
12211             BaseShAmt = Arg;
12212             break;
12213           }
12214         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12215            if (ConstantSDNode *C =
12216                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12217              unsigned SplatIdx =
12218                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12219              if (C->getZExtValue() == SplatIdx)
12220                BaseShAmt = InVec.getOperand(1);
12221            }
12222         }
12223         if (BaseShAmt.getNode() == 0)
12224           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12225                                   DAG.getIntPtrConstant(0));
12226       }
12227     }
12228
12229     if (BaseShAmt.getNode()) {
12230       if (EltVT.bitsGT(MVT::i32))
12231         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12232       else if (EltVT.bitsLT(MVT::i32))
12233         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12234
12235       switch (Op.getOpcode()) {
12236       default:
12237         llvm_unreachable("Unknown shift opcode!");
12238       case ISD::SHL:
12239         switch (VT.getSimpleVT().SimpleTy) {
12240         default: return SDValue();
12241         case MVT::v2i64:
12242         case MVT::v4i32:
12243         case MVT::v8i16:
12244         case MVT::v4i64:
12245         case MVT::v8i32:
12246         case MVT::v16i16:
12247           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12248         }
12249       case ISD::SRA:
12250         switch (VT.getSimpleVT().SimpleTy) {
12251         default: return SDValue();
12252         case MVT::v4i32:
12253         case MVT::v8i16:
12254         case MVT::v8i32:
12255         case MVT::v16i16:
12256           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12257         }
12258       case ISD::SRL:
12259         switch (VT.getSimpleVT().SimpleTy) {
12260         default: return SDValue();
12261         case MVT::v2i64:
12262         case MVT::v4i32:
12263         case MVT::v8i16:
12264         case MVT::v4i64:
12265         case MVT::v8i32:
12266         case MVT::v16i16:
12267           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12268         }
12269       }
12270     }
12271   }
12272
12273   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12274   if (!Subtarget->is64Bit() &&
12275       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12276       Amt.getOpcode() == ISD::BITCAST &&
12277       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12278     Amt = Amt.getOperand(0);
12279     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12280                      VT.getVectorNumElements();
12281     std::vector<SDValue> Vals(Ratio);
12282     for (unsigned i = 0; i != Ratio; ++i)
12283       Vals[i] = Amt.getOperand(i);
12284     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12285       for (unsigned j = 0; j != Ratio; ++j)
12286         if (Vals[j] != Amt.getOperand(i + j))
12287           return SDValue();
12288     }
12289     switch (Op.getOpcode()) {
12290     default:
12291       llvm_unreachable("Unknown shift opcode!");
12292     case ISD::SHL:
12293       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12294     case ISD::SRL:
12295       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12296     case ISD::SRA:
12297       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12298     }
12299   }
12300
12301   return SDValue();
12302 }
12303
12304 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
12305
12306   EVT VT = Op.getValueType();
12307   SDLoc dl(Op);
12308   SDValue R = Op.getOperand(0);
12309   SDValue Amt = Op.getOperand(1);
12310   SDValue V;
12311
12312   if (!Subtarget->hasSSE2())
12313     return SDValue();
12314
12315   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12316   if (V.getNode())
12317     return V;
12318
12319   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12320   if (V.getNode())
12321       return V;
12322
12323   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12324   if (Subtarget->hasInt256()) {
12325     if (Op.getOpcode() == ISD::SRL &&
12326         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12327          VT == MVT::v4i64 || VT == MVT::v8i32))
12328       return Op;
12329     if (Op.getOpcode() == ISD::SHL &&
12330         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12331          VT == MVT::v4i64 || VT == MVT::v8i32))
12332       return Op;
12333     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12334       return Op;
12335   }
12336
12337   // Lower SHL with variable shift amount.
12338   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12339     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12340
12341     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12342     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12343     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12344     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12345   }
12346   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12347     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12348
12349     // a = a << 5;
12350     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12351     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12352
12353     // Turn 'a' into a mask suitable for VSELECT
12354     SDValue VSelM = DAG.getConstant(0x80, VT);
12355     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12356     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12357
12358     SDValue CM1 = DAG.getConstant(0x0f, VT);
12359     SDValue CM2 = DAG.getConstant(0x3f, VT);
12360
12361     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12362     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12363     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12364                             DAG.getConstant(4, MVT::i32), DAG);
12365     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12366     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12367
12368     // a += a
12369     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12370     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12371     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12372
12373     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12374     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12375     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12376                             DAG.getConstant(2, MVT::i32), DAG);
12377     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12378     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12379
12380     // a += a
12381     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12382     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12383     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12384
12385     // return VSELECT(r, r+r, a);
12386     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12387                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12388     return R;
12389   }
12390
12391   // Decompose 256-bit shifts into smaller 128-bit shifts.
12392   if (VT.is256BitVector()) {
12393     unsigned NumElems = VT.getVectorNumElements();
12394     MVT EltVT = VT.getVectorElementType().getSimpleVT();
12395     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12396
12397     // Extract the two vectors
12398     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12399     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12400
12401     // Recreate the shift amount vectors
12402     SDValue Amt1, Amt2;
12403     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12404       // Constant shift amount
12405       SmallVector<SDValue, 4> Amt1Csts;
12406       SmallVector<SDValue, 4> Amt2Csts;
12407       for (unsigned i = 0; i != NumElems/2; ++i)
12408         Amt1Csts.push_back(Amt->getOperand(i));
12409       for (unsigned i = NumElems/2; i != NumElems; ++i)
12410         Amt2Csts.push_back(Amt->getOperand(i));
12411
12412       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12413                                  &Amt1Csts[0], NumElems/2);
12414       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12415                                  &Amt2Csts[0], NumElems/2);
12416     } else {
12417       // Variable shift amount
12418       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12419       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12420     }
12421
12422     // Issue new vector shifts for the smaller types
12423     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12424     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12425
12426     // Concatenate the result back
12427     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12428   }
12429
12430   return SDValue();
12431 }
12432
12433 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12434   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12435   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12436   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12437   // has only one use.
12438   SDNode *N = Op.getNode();
12439   SDValue LHS = N->getOperand(0);
12440   SDValue RHS = N->getOperand(1);
12441   unsigned BaseOp = 0;
12442   unsigned Cond = 0;
12443   SDLoc DL(Op);
12444   switch (Op.getOpcode()) {
12445   default: llvm_unreachable("Unknown ovf instruction!");
12446   case ISD::SADDO:
12447     // A subtract of one will be selected as a INC. Note that INC doesn't
12448     // set CF, so we can't do this for UADDO.
12449     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12450       if (C->isOne()) {
12451         BaseOp = X86ISD::INC;
12452         Cond = X86::COND_O;
12453         break;
12454       }
12455     BaseOp = X86ISD::ADD;
12456     Cond = X86::COND_O;
12457     break;
12458   case ISD::UADDO:
12459     BaseOp = X86ISD::ADD;
12460     Cond = X86::COND_B;
12461     break;
12462   case ISD::SSUBO:
12463     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12464     // set CF, so we can't do this for USUBO.
12465     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12466       if (C->isOne()) {
12467         BaseOp = X86ISD::DEC;
12468         Cond = X86::COND_O;
12469         break;
12470       }
12471     BaseOp = X86ISD::SUB;
12472     Cond = X86::COND_O;
12473     break;
12474   case ISD::USUBO:
12475     BaseOp = X86ISD::SUB;
12476     Cond = X86::COND_B;
12477     break;
12478   case ISD::SMULO:
12479     BaseOp = X86ISD::SMUL;
12480     Cond = X86::COND_O;
12481     break;
12482   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12483     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12484                                  MVT::i32);
12485     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12486
12487     SDValue SetCC =
12488       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12489                   DAG.getConstant(X86::COND_O, MVT::i32),
12490                   SDValue(Sum.getNode(), 2));
12491
12492     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12493   }
12494   }
12495
12496   // Also sets EFLAGS.
12497   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12498   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12499
12500   SDValue SetCC =
12501     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12502                 DAG.getConstant(Cond, MVT::i32),
12503                 SDValue(Sum.getNode(), 1));
12504
12505   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12506 }
12507
12508 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12509                                                   SelectionDAG &DAG) const {
12510   SDLoc dl(Op);
12511   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12512   EVT VT = Op.getValueType();
12513
12514   if (!Subtarget->hasSSE2() || !VT.isVector())
12515     return SDValue();
12516
12517   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12518                       ExtraVT.getScalarType().getSizeInBits();
12519   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12520
12521   switch (VT.getSimpleVT().SimpleTy) {
12522     default: return SDValue();
12523     case MVT::v8i32:
12524     case MVT::v16i16:
12525       if (!Subtarget->hasFp256())
12526         return SDValue();
12527       if (!Subtarget->hasInt256()) {
12528         // needs to be split
12529         unsigned NumElems = VT.getVectorNumElements();
12530
12531         // Extract the LHS vectors
12532         SDValue LHS = Op.getOperand(0);
12533         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12534         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12535
12536         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12537         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12538
12539         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12540         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12541         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12542                                    ExtraNumElems/2);
12543         SDValue Extra = DAG.getValueType(ExtraVT);
12544
12545         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12546         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12547
12548         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12549       }
12550       // fall through
12551     case MVT::v4i32:
12552     case MVT::v8i16: {
12553       // (sext (vzext x)) -> (vsext x)
12554       SDValue Op0 = Op.getOperand(0);
12555       SDValue Op00 = Op0.getOperand(0);
12556       SDValue Tmp1;
12557       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12558       if (Op0.getOpcode() == ISD::BITCAST &&
12559           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12560         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12561       if (Tmp1.getNode()) {
12562         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12563         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12564                "This optimization is invalid without a VZEXT.");
12565         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12566       }
12567
12568       // If the above didn't work, then just use Shift-Left + Shift-Right.
12569       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12570       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12571     }
12572   }
12573 }
12574
12575 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12576                                  SelectionDAG &DAG) {
12577   SDLoc dl(Op);
12578   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12579     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12580   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12581     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12582
12583   // The only fence that needs an instruction is a sequentially-consistent
12584   // cross-thread fence.
12585   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12586     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12587     // no-sse2). There isn't any reason to disable it if the target processor
12588     // supports it.
12589     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12590       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12591
12592     SDValue Chain = Op.getOperand(0);
12593     SDValue Zero = DAG.getConstant(0, MVT::i32);
12594     SDValue Ops[] = {
12595       DAG.getRegister(X86::ESP, MVT::i32), // Base
12596       DAG.getTargetConstant(1, MVT::i8),   // Scale
12597       DAG.getRegister(0, MVT::i32),        // Index
12598       DAG.getTargetConstant(0, MVT::i32),  // Disp
12599       DAG.getRegister(0, MVT::i32),        // Segment.
12600       Zero,
12601       Chain
12602     };
12603     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12604     return SDValue(Res, 0);
12605   }
12606
12607   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12608   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12609 }
12610
12611 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12612                              SelectionDAG &DAG) {
12613   EVT T = Op.getValueType();
12614   SDLoc DL(Op);
12615   unsigned Reg = 0;
12616   unsigned size = 0;
12617   switch(T.getSimpleVT().SimpleTy) {
12618   default: llvm_unreachable("Invalid value type!");
12619   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12620   case MVT::i16: Reg = X86::AX;  size = 2; break;
12621   case MVT::i32: Reg = X86::EAX; size = 4; break;
12622   case MVT::i64:
12623     assert(Subtarget->is64Bit() && "Node not type legal!");
12624     Reg = X86::RAX; size = 8;
12625     break;
12626   }
12627   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12628                                     Op.getOperand(2), SDValue());
12629   SDValue Ops[] = { cpIn.getValue(0),
12630                     Op.getOperand(1),
12631                     Op.getOperand(3),
12632                     DAG.getTargetConstant(size, MVT::i8),
12633                     cpIn.getValue(1) };
12634   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12635   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12636   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12637                                            Ops, array_lengthof(Ops), T, MMO);
12638   SDValue cpOut =
12639     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12640   return cpOut;
12641 }
12642
12643 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12644                                      SelectionDAG &DAG) {
12645   assert(Subtarget->is64Bit() && "Result not type legalized?");
12646   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12647   SDValue TheChain = Op.getOperand(0);
12648   SDLoc dl(Op);
12649   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12650   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12651   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12652                                    rax.getValue(2));
12653   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12654                             DAG.getConstant(32, MVT::i8));
12655   SDValue Ops[] = {
12656     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12657     rdx.getValue(1)
12658   };
12659   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12660 }
12661
12662 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12663   EVT SrcVT = Op.getOperand(0).getValueType();
12664   EVT DstVT = Op.getValueType();
12665   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12666          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12667   assert((DstVT == MVT::i64 ||
12668           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12669          "Unexpected custom BITCAST");
12670   // i64 <=> MMX conversions are Legal.
12671   if (SrcVT==MVT::i64 && DstVT.isVector())
12672     return Op;
12673   if (DstVT==MVT::i64 && SrcVT.isVector())
12674     return Op;
12675   // MMX <=> MMX conversions are Legal.
12676   if (SrcVT.isVector() && DstVT.isVector())
12677     return Op;
12678   // All other conversions need to be expanded.
12679   return SDValue();
12680 }
12681
12682 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12683   SDNode *Node = Op.getNode();
12684   SDLoc dl(Node);
12685   EVT T = Node->getValueType(0);
12686   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12687                               DAG.getConstant(0, T), Node->getOperand(2));
12688   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12689                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12690                        Node->getOperand(0),
12691                        Node->getOperand(1), negOp,
12692                        cast<AtomicSDNode>(Node)->getSrcValue(),
12693                        cast<AtomicSDNode>(Node)->getAlignment(),
12694                        cast<AtomicSDNode>(Node)->getOrdering(),
12695                        cast<AtomicSDNode>(Node)->getSynchScope());
12696 }
12697
12698 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12699   SDNode *Node = Op.getNode();
12700   SDLoc dl(Node);
12701   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12702
12703   // Convert seq_cst store -> xchg
12704   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12705   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12706   //        (The only way to get a 16-byte store is cmpxchg16b)
12707   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12708   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12709       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12710     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12711                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12712                                  Node->getOperand(0),
12713                                  Node->getOperand(1), Node->getOperand(2),
12714                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12715                                  cast<AtomicSDNode>(Node)->getOrdering(),
12716                                  cast<AtomicSDNode>(Node)->getSynchScope());
12717     return Swap.getValue(1);
12718   }
12719   // Other atomic stores have a simple pattern.
12720   return Op;
12721 }
12722
12723 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12724   EVT VT = Op.getNode()->getValueType(0);
12725
12726   // Let legalize expand this if it isn't a legal type yet.
12727   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12728     return SDValue();
12729
12730   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12731
12732   unsigned Opc;
12733   bool ExtraOp = false;
12734   switch (Op.getOpcode()) {
12735   default: llvm_unreachable("Invalid code");
12736   case ISD::ADDC: Opc = X86ISD::ADD; break;
12737   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12738   case ISD::SUBC: Opc = X86ISD::SUB; break;
12739   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12740   }
12741
12742   if (!ExtraOp)
12743     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12744                        Op.getOperand(1));
12745   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12746                      Op.getOperand(1), Op.getOperand(2));
12747 }
12748
12749 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12750   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12751
12752   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12753   // which returns the values as { float, float } (in XMM0) or
12754   // { double, double } (which is returned in XMM0, XMM1).
12755   SDLoc dl(Op);
12756   SDValue Arg = Op.getOperand(0);
12757   EVT ArgVT = Arg.getValueType();
12758   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12759
12760   ArgListTy Args;
12761   ArgListEntry Entry;
12762
12763   Entry.Node = Arg;
12764   Entry.Ty = ArgTy;
12765   Entry.isSExt = false;
12766   Entry.isZExt = false;
12767   Args.push_back(Entry);
12768
12769   bool isF64 = ArgVT == MVT::f64;
12770   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12771   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12772   // the results are returned via SRet in memory.
12773   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12774   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12775
12776   Type *RetTy = isF64
12777     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12778     : (Type*)VectorType::get(ArgTy, 4);
12779   TargetLowering::
12780     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12781                          false, false, false, false, 0,
12782                          CallingConv::C, /*isTaillCall=*/false,
12783                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12784                          Callee, Args, DAG, dl);
12785   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12786
12787   if (isF64)
12788     // Returned in xmm0 and xmm1.
12789     return CallResult.first;
12790
12791   // Returned in bits 0:31 and 32:64 xmm0.
12792   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12793                                CallResult.first, DAG.getIntPtrConstant(0));
12794   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12795                                CallResult.first, DAG.getIntPtrConstant(1));
12796   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12797   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12798 }
12799
12800 /// LowerOperation - Provide custom lowering hooks for some operations.
12801 ///
12802 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12803   switch (Op.getOpcode()) {
12804   default: llvm_unreachable("Should not custom lower this!");
12805   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12806   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12807   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12808   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12809   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12810   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12811   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12812   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12813   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12814   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12815   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12816   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12817   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12818   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12819   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12820   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12821   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12822   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12823   case ISD::SHL_PARTS:
12824   case ISD::SRA_PARTS:
12825   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12826   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12827   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12828   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12829   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12830   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12831   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12832   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12833   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12834   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12835   case ISD::FABS:               return LowerFABS(Op, DAG);
12836   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12837   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12838   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12839   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12840   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12841   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12842   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12843   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12844   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12845   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12846   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12847   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12848   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12849   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12850   case ISD::FRAME_TO_ARGS_OFFSET:
12851                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12852   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12853   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12854   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12855   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12856   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12857   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12858   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12859   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12860   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12861   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12862   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12863   case ISD::SRA:
12864   case ISD::SRL:
12865   case ISD::SHL:                return LowerShift(Op, DAG);
12866   case ISD::SADDO:
12867   case ISD::UADDO:
12868   case ISD::SSUBO:
12869   case ISD::USUBO:
12870   case ISD::SMULO:
12871   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12872   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12873   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12874   case ISD::ADDC:
12875   case ISD::ADDE:
12876   case ISD::SUBC:
12877   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12878   case ISD::ADD:                return LowerADD(Op, DAG);
12879   case ISD::SUB:                return LowerSUB(Op, DAG);
12880   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12881   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12882   }
12883 }
12884
12885 static void ReplaceATOMIC_LOAD(SDNode *Node,
12886                                   SmallVectorImpl<SDValue> &Results,
12887                                   SelectionDAG &DAG) {
12888   SDLoc dl(Node);
12889   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12890
12891   // Convert wide load -> cmpxchg8b/cmpxchg16b
12892   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12893   //        (The only way to get a 16-byte load is cmpxchg16b)
12894   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12895   SDValue Zero = DAG.getConstant(0, VT);
12896   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12897                                Node->getOperand(0),
12898                                Node->getOperand(1), Zero, Zero,
12899                                cast<AtomicSDNode>(Node)->getMemOperand(),
12900                                cast<AtomicSDNode>(Node)->getOrdering(),
12901                                cast<AtomicSDNode>(Node)->getSynchScope());
12902   Results.push_back(Swap.getValue(0));
12903   Results.push_back(Swap.getValue(1));
12904 }
12905
12906 static void
12907 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12908                         SelectionDAG &DAG, unsigned NewOp) {
12909   SDLoc dl(Node);
12910   assert (Node->getValueType(0) == MVT::i64 &&
12911           "Only know how to expand i64 atomics");
12912
12913   SDValue Chain = Node->getOperand(0);
12914   SDValue In1 = Node->getOperand(1);
12915   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12916                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12917   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12918                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12919   SDValue Ops[] = { Chain, In1, In2L, In2H };
12920   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12921   SDValue Result =
12922     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12923                             cast<MemSDNode>(Node)->getMemOperand());
12924   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12925   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12926   Results.push_back(Result.getValue(2));
12927 }
12928
12929 /// ReplaceNodeResults - Replace a node with an illegal result type
12930 /// with a new node built out of custom code.
12931 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12932                                            SmallVectorImpl<SDValue>&Results,
12933                                            SelectionDAG &DAG) const {
12934   SDLoc dl(N);
12935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12936   switch (N->getOpcode()) {
12937   default:
12938     llvm_unreachable("Do not know how to custom type legalize this operation!");
12939   case ISD::SIGN_EXTEND_INREG:
12940   case ISD::ADDC:
12941   case ISD::ADDE:
12942   case ISD::SUBC:
12943   case ISD::SUBE:
12944     // We don't want to expand or promote these.
12945     return;
12946   case ISD::FP_TO_SINT:
12947   case ISD::FP_TO_UINT: {
12948     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12949
12950     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12951       return;
12952
12953     std::pair<SDValue,SDValue> Vals =
12954         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12955     SDValue FIST = Vals.first, StackSlot = Vals.second;
12956     if (FIST.getNode() != 0) {
12957       EVT VT = N->getValueType(0);
12958       // Return a load from the stack slot.
12959       if (StackSlot.getNode() != 0)
12960         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12961                                       MachinePointerInfo(),
12962                                       false, false, false, 0));
12963       else
12964         Results.push_back(FIST);
12965     }
12966     return;
12967   }
12968   case ISD::UINT_TO_FP: {
12969     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12970     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12971         N->getValueType(0) != MVT::v2f32)
12972       return;
12973     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12974                                  N->getOperand(0));
12975     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12976                                      MVT::f64);
12977     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12978     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12979                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12980     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12981     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12982     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12983     return;
12984   }
12985   case ISD::FP_ROUND: {
12986     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12987         return;
12988     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12989     Results.push_back(V);
12990     return;
12991   }
12992   case ISD::READCYCLECOUNTER: {
12993     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12994     SDValue TheChain = N->getOperand(0);
12995     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12996     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12997                                      rd.getValue(1));
12998     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12999                                      eax.getValue(2));
13000     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13001     SDValue Ops[] = { eax, edx };
13002     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13003                                   array_lengthof(Ops)));
13004     Results.push_back(edx.getValue(1));
13005     return;
13006   }
13007   case ISD::ATOMIC_CMP_SWAP: {
13008     EVT T = N->getValueType(0);
13009     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13010     bool Regs64bit = T == MVT::i128;
13011     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13012     SDValue cpInL, cpInH;
13013     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13014                         DAG.getConstant(0, HalfT));
13015     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13016                         DAG.getConstant(1, HalfT));
13017     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13018                              Regs64bit ? X86::RAX : X86::EAX,
13019                              cpInL, SDValue());
13020     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13021                              Regs64bit ? X86::RDX : X86::EDX,
13022                              cpInH, cpInL.getValue(1));
13023     SDValue swapInL, swapInH;
13024     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13025                           DAG.getConstant(0, HalfT));
13026     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13027                           DAG.getConstant(1, HalfT));
13028     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13029                                Regs64bit ? X86::RBX : X86::EBX,
13030                                swapInL, cpInH.getValue(1));
13031     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13032                                Regs64bit ? X86::RCX : X86::ECX,
13033                                swapInH, swapInL.getValue(1));
13034     SDValue Ops[] = { swapInH.getValue(0),
13035                       N->getOperand(1),
13036                       swapInH.getValue(1) };
13037     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13038     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13039     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13040                                   X86ISD::LCMPXCHG8_DAG;
13041     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13042                                              Ops, array_lengthof(Ops), T, MMO);
13043     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13044                                         Regs64bit ? X86::RAX : X86::EAX,
13045                                         HalfT, Result.getValue(1));
13046     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13047                                         Regs64bit ? X86::RDX : X86::EDX,
13048                                         HalfT, cpOutL.getValue(2));
13049     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13050     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13051     Results.push_back(cpOutH.getValue(1));
13052     return;
13053   }
13054   case ISD::ATOMIC_LOAD_ADD:
13055   case ISD::ATOMIC_LOAD_AND:
13056   case ISD::ATOMIC_LOAD_NAND:
13057   case ISD::ATOMIC_LOAD_OR:
13058   case ISD::ATOMIC_LOAD_SUB:
13059   case ISD::ATOMIC_LOAD_XOR:
13060   case ISD::ATOMIC_LOAD_MAX:
13061   case ISD::ATOMIC_LOAD_MIN:
13062   case ISD::ATOMIC_LOAD_UMAX:
13063   case ISD::ATOMIC_LOAD_UMIN:
13064   case ISD::ATOMIC_SWAP: {
13065     unsigned Opc;
13066     switch (N->getOpcode()) {
13067     default: llvm_unreachable("Unexpected opcode");
13068     case ISD::ATOMIC_LOAD_ADD:
13069       Opc = X86ISD::ATOMADD64_DAG;
13070       break;
13071     case ISD::ATOMIC_LOAD_AND:
13072       Opc = X86ISD::ATOMAND64_DAG;
13073       break;
13074     case ISD::ATOMIC_LOAD_NAND:
13075       Opc = X86ISD::ATOMNAND64_DAG;
13076       break;
13077     case ISD::ATOMIC_LOAD_OR:
13078       Opc = X86ISD::ATOMOR64_DAG;
13079       break;
13080     case ISD::ATOMIC_LOAD_SUB:
13081       Opc = X86ISD::ATOMSUB64_DAG;
13082       break;
13083     case ISD::ATOMIC_LOAD_XOR:
13084       Opc = X86ISD::ATOMXOR64_DAG;
13085       break;
13086     case ISD::ATOMIC_LOAD_MAX:
13087       Opc = X86ISD::ATOMMAX64_DAG;
13088       break;
13089     case ISD::ATOMIC_LOAD_MIN:
13090       Opc = X86ISD::ATOMMIN64_DAG;
13091       break;
13092     case ISD::ATOMIC_LOAD_UMAX:
13093       Opc = X86ISD::ATOMUMAX64_DAG;
13094       break;
13095     case ISD::ATOMIC_LOAD_UMIN:
13096       Opc = X86ISD::ATOMUMIN64_DAG;
13097       break;
13098     case ISD::ATOMIC_SWAP:
13099       Opc = X86ISD::ATOMSWAP64_DAG;
13100       break;
13101     }
13102     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13103     return;
13104   }
13105   case ISD::ATOMIC_LOAD:
13106     ReplaceATOMIC_LOAD(N, Results, DAG);
13107   }
13108 }
13109
13110 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13111   switch (Opcode) {
13112   default: return NULL;
13113   case X86ISD::BSF:                return "X86ISD::BSF";
13114   case X86ISD::BSR:                return "X86ISD::BSR";
13115   case X86ISD::SHLD:               return "X86ISD::SHLD";
13116   case X86ISD::SHRD:               return "X86ISD::SHRD";
13117   case X86ISD::FAND:               return "X86ISD::FAND";
13118   case X86ISD::FANDN:              return "X86ISD::FANDN";
13119   case X86ISD::FOR:                return "X86ISD::FOR";
13120   case X86ISD::FXOR:               return "X86ISD::FXOR";
13121   case X86ISD::FSRL:               return "X86ISD::FSRL";
13122   case X86ISD::FILD:               return "X86ISD::FILD";
13123   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13124   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13125   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13126   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13127   case X86ISD::FLD:                return "X86ISD::FLD";
13128   case X86ISD::FST:                return "X86ISD::FST";
13129   case X86ISD::CALL:               return "X86ISD::CALL";
13130   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13131   case X86ISD::BT:                 return "X86ISD::BT";
13132   case X86ISD::CMP:                return "X86ISD::CMP";
13133   case X86ISD::COMI:               return "X86ISD::COMI";
13134   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13135   case X86ISD::SETCC:              return "X86ISD::SETCC";
13136   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13137   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
13138   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
13139   case X86ISD::CMOV:               return "X86ISD::CMOV";
13140   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13141   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13142   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13143   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13144   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13145   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13146   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13147   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13148   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13149   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13150   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13151   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13152   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13153   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13154   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13155   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13156   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13157   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13158   case X86ISD::HADD:               return "X86ISD::HADD";
13159   case X86ISD::HSUB:               return "X86ISD::HSUB";
13160   case X86ISD::FHADD:              return "X86ISD::FHADD";
13161   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13162   case X86ISD::UMAX:               return "X86ISD::UMAX";
13163   case X86ISD::UMIN:               return "X86ISD::UMIN";
13164   case X86ISD::SMAX:               return "X86ISD::SMAX";
13165   case X86ISD::SMIN:               return "X86ISD::SMIN";
13166   case X86ISD::FMAX:               return "X86ISD::FMAX";
13167   case X86ISD::FMIN:               return "X86ISD::FMIN";
13168   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13169   case X86ISD::FMINC:              return "X86ISD::FMINC";
13170   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13171   case X86ISD::FRCP:               return "X86ISD::FRCP";
13172   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13173   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13174   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13175   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13176   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13177   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13178   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13179   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13180   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13181   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13182   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13183   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13184   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13185   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13186   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13187   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13188   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13189   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13190   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13191   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13192   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13193   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13194   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13195   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13196   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13197   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13198   case X86ISD::VSHL:               return "X86ISD::VSHL";
13199   case X86ISD::VSRL:               return "X86ISD::VSRL";
13200   case X86ISD::VSRA:               return "X86ISD::VSRA";
13201   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13202   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13203   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13204   case X86ISD::CMPP:               return "X86ISD::CMPP";
13205   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13206   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13207   case X86ISD::ADD:                return "X86ISD::ADD";
13208   case X86ISD::SUB:                return "X86ISD::SUB";
13209   case X86ISD::ADC:                return "X86ISD::ADC";
13210   case X86ISD::SBB:                return "X86ISD::SBB";
13211   case X86ISD::SMUL:               return "X86ISD::SMUL";
13212   case X86ISD::UMUL:               return "X86ISD::UMUL";
13213   case X86ISD::INC:                return "X86ISD::INC";
13214   case X86ISD::DEC:                return "X86ISD::DEC";
13215   case X86ISD::OR:                 return "X86ISD::OR";
13216   case X86ISD::XOR:                return "X86ISD::XOR";
13217   case X86ISD::AND:                return "X86ISD::AND";
13218   case X86ISD::BLSI:               return "X86ISD::BLSI";
13219   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13220   case X86ISD::BLSR:               return "X86ISD::BLSR";
13221   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13222   case X86ISD::PTEST:              return "X86ISD::PTEST";
13223   case X86ISD::TESTP:              return "X86ISD::TESTP";
13224   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13225   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13226   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13227   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13228   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13229   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13230   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13231   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13232   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13233   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13234   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13235   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13236   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13237   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13238   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13239   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13240   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13241   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13242   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13243   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13244   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13245   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13246   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13247   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13248   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13249   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13250   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13251   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13252   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13253   case X86ISD::SAHF:               return "X86ISD::SAHF";
13254   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13255   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13256   case X86ISD::FMADD:              return "X86ISD::FMADD";
13257   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13258   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13259   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13260   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13261   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13262   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13263   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13264   case X86ISD::XTEST:              return "X86ISD::XTEST";
13265   }
13266 }
13267
13268 // isLegalAddressingMode - Return true if the addressing mode represented
13269 // by AM is legal for this target, for a load/store of the specified type.
13270 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13271                                               Type *Ty) const {
13272   // X86 supports extremely general addressing modes.
13273   CodeModel::Model M = getTargetMachine().getCodeModel();
13274   Reloc::Model R = getTargetMachine().getRelocationModel();
13275
13276   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13277   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13278     return false;
13279
13280   if (AM.BaseGV) {
13281     unsigned GVFlags =
13282       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13283
13284     // If a reference to this global requires an extra load, we can't fold it.
13285     if (isGlobalStubReference(GVFlags))
13286       return false;
13287
13288     // If BaseGV requires a register for the PIC base, we cannot also have a
13289     // BaseReg specified.
13290     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13291       return false;
13292
13293     // If lower 4G is not available, then we must use rip-relative addressing.
13294     if ((M != CodeModel::Small || R != Reloc::Static) &&
13295         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13296       return false;
13297   }
13298
13299   switch (AM.Scale) {
13300   case 0:
13301   case 1:
13302   case 2:
13303   case 4:
13304   case 8:
13305     // These scales always work.
13306     break;
13307   case 3:
13308   case 5:
13309   case 9:
13310     // These scales are formed with basereg+scalereg.  Only accept if there is
13311     // no basereg yet.
13312     if (AM.HasBaseReg)
13313       return false;
13314     break;
13315   default:  // Other stuff never works.
13316     return false;
13317   }
13318
13319   return true;
13320 }
13321
13322 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13323   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13324     return false;
13325   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13326   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13327   return NumBits1 > NumBits2;
13328 }
13329
13330 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13331   return isInt<32>(Imm);
13332 }
13333
13334 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13335   // Can also use sub to handle negated immediates.
13336   return isInt<32>(Imm);
13337 }
13338
13339 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13340   if (!VT1.isInteger() || !VT2.isInteger())
13341     return false;
13342   unsigned NumBits1 = VT1.getSizeInBits();
13343   unsigned NumBits2 = VT2.getSizeInBits();
13344   return NumBits1 > NumBits2;
13345 }
13346
13347 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13348   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13349   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13350 }
13351
13352 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13353   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13354   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13355 }
13356
13357 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13358   EVT VT1 = Val.getValueType();
13359   if (isZExtFree(VT1, VT2))
13360     return true;
13361
13362   if (Val.getOpcode() != ISD::LOAD)
13363     return false;
13364
13365   if (!VT1.isSimple() || !VT1.isInteger() ||
13366       !VT2.isSimple() || !VT2.isInteger())
13367     return false;
13368
13369   switch (VT1.getSimpleVT().SimpleTy) {
13370   default: break;
13371   case MVT::i8:
13372   case MVT::i16:
13373   case MVT::i32:
13374     // X86 has 8, 16, and 32-bit zero-extending loads.
13375     return true;
13376   }
13377
13378   return false;
13379 }
13380
13381 bool
13382 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13383   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13384     return false;
13385
13386   VT = VT.getScalarType();
13387
13388   if (!VT.isSimple())
13389     return false;
13390
13391   switch (VT.getSimpleVT().SimpleTy) {
13392   case MVT::f32:
13393   case MVT::f64:
13394     return true;
13395   default:
13396     break;
13397   }
13398
13399   return false;
13400 }
13401
13402 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13403   // i16 instructions are longer (0x66 prefix) and potentially slower.
13404   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13405 }
13406
13407 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13408 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13409 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13410 /// are assumed to be legal.
13411 bool
13412 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13413                                       EVT VT) const {
13414   // Very little shuffling can be done for 64-bit vectors right now.
13415   if (VT.getSizeInBits() == 64)
13416     return false;
13417
13418   // FIXME: pshufb, blends, shifts.
13419   return (VT.getVectorNumElements() == 2 ||
13420           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13421           isMOVLMask(M, VT) ||
13422           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13423           isPSHUFDMask(M, VT) ||
13424           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13425           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13426           isPALIGNRMask(M, VT, Subtarget) ||
13427           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13428           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13429           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13430           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13431 }
13432
13433 bool
13434 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13435                                           EVT VT) const {
13436   unsigned NumElts = VT.getVectorNumElements();
13437   // FIXME: This collection of masks seems suspect.
13438   if (NumElts == 2)
13439     return true;
13440   if (NumElts == 4 && VT.is128BitVector()) {
13441     return (isMOVLMask(Mask, VT)  ||
13442             isCommutedMOVLMask(Mask, VT, true) ||
13443             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13444             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13445   }
13446   return false;
13447 }
13448
13449 //===----------------------------------------------------------------------===//
13450 //                           X86 Scheduler Hooks
13451 //===----------------------------------------------------------------------===//
13452
13453 /// Utility function to emit xbegin specifying the start of an RTM region.
13454 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13455                                      const TargetInstrInfo *TII) {
13456   DebugLoc DL = MI->getDebugLoc();
13457
13458   const BasicBlock *BB = MBB->getBasicBlock();
13459   MachineFunction::iterator I = MBB;
13460   ++I;
13461
13462   // For the v = xbegin(), we generate
13463   //
13464   // thisMBB:
13465   //  xbegin sinkMBB
13466   //
13467   // mainMBB:
13468   //  eax = -1
13469   //
13470   // sinkMBB:
13471   //  v = eax
13472
13473   MachineBasicBlock *thisMBB = MBB;
13474   MachineFunction *MF = MBB->getParent();
13475   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13476   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13477   MF->insert(I, mainMBB);
13478   MF->insert(I, sinkMBB);
13479
13480   // Transfer the remainder of BB and its successor edges to sinkMBB.
13481   sinkMBB->splice(sinkMBB->begin(), MBB,
13482                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13483   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13484
13485   // thisMBB:
13486   //  xbegin sinkMBB
13487   //  # fallthrough to mainMBB
13488   //  # abortion to sinkMBB
13489   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13490   thisMBB->addSuccessor(mainMBB);
13491   thisMBB->addSuccessor(sinkMBB);
13492
13493   // mainMBB:
13494   //  EAX = -1
13495   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13496   mainMBB->addSuccessor(sinkMBB);
13497
13498   // sinkMBB:
13499   // EAX is live into the sinkMBB
13500   sinkMBB->addLiveIn(X86::EAX);
13501   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13502           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13503     .addReg(X86::EAX);
13504
13505   MI->eraseFromParent();
13506   return sinkMBB;
13507 }
13508
13509 // Get CMPXCHG opcode for the specified data type.
13510 static unsigned getCmpXChgOpcode(EVT VT) {
13511   switch (VT.getSimpleVT().SimpleTy) {
13512   case MVT::i8:  return X86::LCMPXCHG8;
13513   case MVT::i16: return X86::LCMPXCHG16;
13514   case MVT::i32: return X86::LCMPXCHG32;
13515   case MVT::i64: return X86::LCMPXCHG64;
13516   default:
13517     break;
13518   }
13519   llvm_unreachable("Invalid operand size!");
13520 }
13521
13522 // Get LOAD opcode for the specified data type.
13523 static unsigned getLoadOpcode(EVT VT) {
13524   switch (VT.getSimpleVT().SimpleTy) {
13525   case MVT::i8:  return X86::MOV8rm;
13526   case MVT::i16: return X86::MOV16rm;
13527   case MVT::i32: return X86::MOV32rm;
13528   case MVT::i64: return X86::MOV64rm;
13529   default:
13530     break;
13531   }
13532   llvm_unreachable("Invalid operand size!");
13533 }
13534
13535 // Get opcode of the non-atomic one from the specified atomic instruction.
13536 static unsigned getNonAtomicOpcode(unsigned Opc) {
13537   switch (Opc) {
13538   case X86::ATOMAND8:  return X86::AND8rr;
13539   case X86::ATOMAND16: return X86::AND16rr;
13540   case X86::ATOMAND32: return X86::AND32rr;
13541   case X86::ATOMAND64: return X86::AND64rr;
13542   case X86::ATOMOR8:   return X86::OR8rr;
13543   case X86::ATOMOR16:  return X86::OR16rr;
13544   case X86::ATOMOR32:  return X86::OR32rr;
13545   case X86::ATOMOR64:  return X86::OR64rr;
13546   case X86::ATOMXOR8:  return X86::XOR8rr;
13547   case X86::ATOMXOR16: return X86::XOR16rr;
13548   case X86::ATOMXOR32: return X86::XOR32rr;
13549   case X86::ATOMXOR64: return X86::XOR64rr;
13550   }
13551   llvm_unreachable("Unhandled atomic-load-op opcode!");
13552 }
13553
13554 // Get opcode of the non-atomic one from the specified atomic instruction with
13555 // extra opcode.
13556 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13557                                                unsigned &ExtraOpc) {
13558   switch (Opc) {
13559   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13560   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13561   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13562   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13563   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13564   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13565   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13566   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13567   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13568   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13569   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13570   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13571   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13572   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13573   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13574   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13575   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13576   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13577   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13578   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13579   }
13580   llvm_unreachable("Unhandled atomic-load-op opcode!");
13581 }
13582
13583 // Get opcode of the non-atomic one from the specified atomic instruction for
13584 // 64-bit data type on 32-bit target.
13585 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13586   switch (Opc) {
13587   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13588   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13589   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13590   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13591   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13592   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13593   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13594   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13595   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13596   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13597   }
13598   llvm_unreachable("Unhandled atomic-load-op opcode!");
13599 }
13600
13601 // Get opcode of the non-atomic one from the specified atomic instruction for
13602 // 64-bit data type on 32-bit target with extra opcode.
13603 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13604                                                    unsigned &HiOpc,
13605                                                    unsigned &ExtraOpc) {
13606   switch (Opc) {
13607   case X86::ATOMNAND6432:
13608     ExtraOpc = X86::NOT32r;
13609     HiOpc = X86::AND32rr;
13610     return X86::AND32rr;
13611   }
13612   llvm_unreachable("Unhandled atomic-load-op opcode!");
13613 }
13614
13615 // Get pseudo CMOV opcode from the specified data type.
13616 static unsigned getPseudoCMOVOpc(EVT VT) {
13617   switch (VT.getSimpleVT().SimpleTy) {
13618   case MVT::i8:  return X86::CMOV_GR8;
13619   case MVT::i16: return X86::CMOV_GR16;
13620   case MVT::i32: return X86::CMOV_GR32;
13621   default:
13622     break;
13623   }
13624   llvm_unreachable("Unknown CMOV opcode!");
13625 }
13626
13627 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13628 // They will be translated into a spin-loop or compare-exchange loop from
13629 //
13630 //    ...
13631 //    dst = atomic-fetch-op MI.addr, MI.val
13632 //    ...
13633 //
13634 // to
13635 //
13636 //    ...
13637 //    t1 = LOAD MI.addr
13638 // loop:
13639 //    t4 = phi(t1, t3 / loop)
13640 //    t2 = OP MI.val, t4
13641 //    EAX = t4
13642 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13643 //    t3 = EAX
13644 //    JNE loop
13645 // sink:
13646 //    dst = t3
13647 //    ...
13648 MachineBasicBlock *
13649 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13650                                        MachineBasicBlock *MBB) const {
13651   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13652   DebugLoc DL = MI->getDebugLoc();
13653
13654   MachineFunction *MF = MBB->getParent();
13655   MachineRegisterInfo &MRI = MF->getRegInfo();
13656
13657   const BasicBlock *BB = MBB->getBasicBlock();
13658   MachineFunction::iterator I = MBB;
13659   ++I;
13660
13661   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13662          "Unexpected number of operands");
13663
13664   assert(MI->hasOneMemOperand() &&
13665          "Expected atomic-load-op to have one memoperand");
13666
13667   // Memory Reference
13668   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13669   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13670
13671   unsigned DstReg, SrcReg;
13672   unsigned MemOpndSlot;
13673
13674   unsigned CurOp = 0;
13675
13676   DstReg = MI->getOperand(CurOp++).getReg();
13677   MemOpndSlot = CurOp;
13678   CurOp += X86::AddrNumOperands;
13679   SrcReg = MI->getOperand(CurOp++).getReg();
13680
13681   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13682   MVT::SimpleValueType VT = *RC->vt_begin();
13683   unsigned t1 = MRI.createVirtualRegister(RC);
13684   unsigned t2 = MRI.createVirtualRegister(RC);
13685   unsigned t3 = MRI.createVirtualRegister(RC);
13686   unsigned t4 = MRI.createVirtualRegister(RC);
13687   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13688
13689   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13690   unsigned LOADOpc = getLoadOpcode(VT);
13691
13692   // For the atomic load-arith operator, we generate
13693   //
13694   //  thisMBB:
13695   //    t1 = LOAD [MI.addr]
13696   //  mainMBB:
13697   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13698   //    t1 = OP MI.val, EAX
13699   //    EAX = t4
13700   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13701   //    t3 = EAX
13702   //    JNE mainMBB
13703   //  sinkMBB:
13704   //    dst = t3
13705
13706   MachineBasicBlock *thisMBB = MBB;
13707   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13708   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13709   MF->insert(I, mainMBB);
13710   MF->insert(I, sinkMBB);
13711
13712   MachineInstrBuilder MIB;
13713
13714   // Transfer the remainder of BB and its successor edges to sinkMBB.
13715   sinkMBB->splice(sinkMBB->begin(), MBB,
13716                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13717   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13718
13719   // thisMBB:
13720   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13721   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13722     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13723     if (NewMO.isReg())
13724       NewMO.setIsKill(false);
13725     MIB.addOperand(NewMO);
13726   }
13727   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13728     unsigned flags = (*MMOI)->getFlags();
13729     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13730     MachineMemOperand *MMO =
13731       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13732                                (*MMOI)->getSize(),
13733                                (*MMOI)->getBaseAlignment(),
13734                                (*MMOI)->getTBAAInfo(),
13735                                (*MMOI)->getRanges());
13736     MIB.addMemOperand(MMO);
13737   }
13738
13739   thisMBB->addSuccessor(mainMBB);
13740
13741   // mainMBB:
13742   MachineBasicBlock *origMainMBB = mainMBB;
13743
13744   // Add a PHI.
13745   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13746                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13747
13748   unsigned Opc = MI->getOpcode();
13749   switch (Opc) {
13750   default:
13751     llvm_unreachable("Unhandled atomic-load-op opcode!");
13752   case X86::ATOMAND8:
13753   case X86::ATOMAND16:
13754   case X86::ATOMAND32:
13755   case X86::ATOMAND64:
13756   case X86::ATOMOR8:
13757   case X86::ATOMOR16:
13758   case X86::ATOMOR32:
13759   case X86::ATOMOR64:
13760   case X86::ATOMXOR8:
13761   case X86::ATOMXOR16:
13762   case X86::ATOMXOR32:
13763   case X86::ATOMXOR64: {
13764     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13765     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13766       .addReg(t4);
13767     break;
13768   }
13769   case X86::ATOMNAND8:
13770   case X86::ATOMNAND16:
13771   case X86::ATOMNAND32:
13772   case X86::ATOMNAND64: {
13773     unsigned Tmp = MRI.createVirtualRegister(RC);
13774     unsigned NOTOpc;
13775     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13776     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13777       .addReg(t4);
13778     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13779     break;
13780   }
13781   case X86::ATOMMAX8:
13782   case X86::ATOMMAX16:
13783   case X86::ATOMMAX32:
13784   case X86::ATOMMAX64:
13785   case X86::ATOMMIN8:
13786   case X86::ATOMMIN16:
13787   case X86::ATOMMIN32:
13788   case X86::ATOMMIN64:
13789   case X86::ATOMUMAX8:
13790   case X86::ATOMUMAX16:
13791   case X86::ATOMUMAX32:
13792   case X86::ATOMUMAX64:
13793   case X86::ATOMUMIN8:
13794   case X86::ATOMUMIN16:
13795   case X86::ATOMUMIN32:
13796   case X86::ATOMUMIN64: {
13797     unsigned CMPOpc;
13798     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13799
13800     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13801       .addReg(SrcReg)
13802       .addReg(t4);
13803
13804     if (Subtarget->hasCMov()) {
13805       if (VT != MVT::i8) {
13806         // Native support
13807         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13808           .addReg(SrcReg)
13809           .addReg(t4);
13810       } else {
13811         // Promote i8 to i32 to use CMOV32
13812         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13813         const TargetRegisterClass *RC32 =
13814           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13815         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13816         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13817         unsigned Tmp = MRI.createVirtualRegister(RC32);
13818
13819         unsigned Undef = MRI.createVirtualRegister(RC32);
13820         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13821
13822         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13823           .addReg(Undef)
13824           .addReg(SrcReg)
13825           .addImm(X86::sub_8bit);
13826         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13827           .addReg(Undef)
13828           .addReg(t4)
13829           .addImm(X86::sub_8bit);
13830
13831         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13832           .addReg(SrcReg32)
13833           .addReg(AccReg32);
13834
13835         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13836           .addReg(Tmp, 0, X86::sub_8bit);
13837       }
13838     } else {
13839       // Use pseudo select and lower them.
13840       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13841              "Invalid atomic-load-op transformation!");
13842       unsigned SelOpc = getPseudoCMOVOpc(VT);
13843       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13844       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13845       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13846               .addReg(SrcReg).addReg(t4)
13847               .addImm(CC);
13848       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13849       // Replace the original PHI node as mainMBB is changed after CMOV
13850       // lowering.
13851       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13852         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13853       Phi->eraseFromParent();
13854     }
13855     break;
13856   }
13857   }
13858
13859   // Copy PhyReg back from virtual register.
13860   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13861     .addReg(t4);
13862
13863   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13864   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13865     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13866     if (NewMO.isReg())
13867       NewMO.setIsKill(false);
13868     MIB.addOperand(NewMO);
13869   }
13870   MIB.addReg(t2);
13871   MIB.setMemRefs(MMOBegin, MMOEnd);
13872
13873   // Copy PhyReg back to virtual register.
13874   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13875     .addReg(PhyReg);
13876
13877   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13878
13879   mainMBB->addSuccessor(origMainMBB);
13880   mainMBB->addSuccessor(sinkMBB);
13881
13882   // sinkMBB:
13883   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13884           TII->get(TargetOpcode::COPY), DstReg)
13885     .addReg(t3);
13886
13887   MI->eraseFromParent();
13888   return sinkMBB;
13889 }
13890
13891 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13892 // instructions. They will be translated into a spin-loop or compare-exchange
13893 // loop from
13894 //
13895 //    ...
13896 //    dst = atomic-fetch-op MI.addr, MI.val
13897 //    ...
13898 //
13899 // to
13900 //
13901 //    ...
13902 //    t1L = LOAD [MI.addr + 0]
13903 //    t1H = LOAD [MI.addr + 4]
13904 // loop:
13905 //    t4L = phi(t1L, t3L / loop)
13906 //    t4H = phi(t1H, t3H / loop)
13907 //    t2L = OP MI.val.lo, t4L
13908 //    t2H = OP MI.val.hi, t4H
13909 //    EAX = t4L
13910 //    EDX = t4H
13911 //    EBX = t2L
13912 //    ECX = t2H
13913 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13914 //    t3L = EAX
13915 //    t3H = EDX
13916 //    JNE loop
13917 // sink:
13918 //    dstL = t3L
13919 //    dstH = t3H
13920 //    ...
13921 MachineBasicBlock *
13922 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13923                                            MachineBasicBlock *MBB) const {
13924   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13925   DebugLoc DL = MI->getDebugLoc();
13926
13927   MachineFunction *MF = MBB->getParent();
13928   MachineRegisterInfo &MRI = MF->getRegInfo();
13929
13930   const BasicBlock *BB = MBB->getBasicBlock();
13931   MachineFunction::iterator I = MBB;
13932   ++I;
13933
13934   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13935          "Unexpected number of operands");
13936
13937   assert(MI->hasOneMemOperand() &&
13938          "Expected atomic-load-op32 to have one memoperand");
13939
13940   // Memory Reference
13941   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13942   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13943
13944   unsigned DstLoReg, DstHiReg;
13945   unsigned SrcLoReg, SrcHiReg;
13946   unsigned MemOpndSlot;
13947
13948   unsigned CurOp = 0;
13949
13950   DstLoReg = MI->getOperand(CurOp++).getReg();
13951   DstHiReg = MI->getOperand(CurOp++).getReg();
13952   MemOpndSlot = CurOp;
13953   CurOp += X86::AddrNumOperands;
13954   SrcLoReg = MI->getOperand(CurOp++).getReg();
13955   SrcHiReg = MI->getOperand(CurOp++).getReg();
13956
13957   const TargetRegisterClass *RC = &X86::GR32RegClass;
13958   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13959
13960   unsigned t1L = MRI.createVirtualRegister(RC);
13961   unsigned t1H = MRI.createVirtualRegister(RC);
13962   unsigned t2L = MRI.createVirtualRegister(RC);
13963   unsigned t2H = MRI.createVirtualRegister(RC);
13964   unsigned t3L = MRI.createVirtualRegister(RC);
13965   unsigned t3H = MRI.createVirtualRegister(RC);
13966   unsigned t4L = MRI.createVirtualRegister(RC);
13967   unsigned t4H = MRI.createVirtualRegister(RC);
13968
13969   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13970   unsigned LOADOpc = X86::MOV32rm;
13971
13972   // For the atomic load-arith operator, we generate
13973   //
13974   //  thisMBB:
13975   //    t1L = LOAD [MI.addr + 0]
13976   //    t1H = LOAD [MI.addr + 4]
13977   //  mainMBB:
13978   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13979   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13980   //    t2L = OP MI.val.lo, t4L
13981   //    t2H = OP MI.val.hi, t4H
13982   //    EBX = t2L
13983   //    ECX = t2H
13984   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13985   //    t3L = EAX
13986   //    t3H = EDX
13987   //    JNE loop
13988   //  sinkMBB:
13989   //    dstL = t3L
13990   //    dstH = t3H
13991
13992   MachineBasicBlock *thisMBB = MBB;
13993   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13994   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13995   MF->insert(I, mainMBB);
13996   MF->insert(I, sinkMBB);
13997
13998   MachineInstrBuilder MIB;
13999
14000   // Transfer the remainder of BB and its successor edges to sinkMBB.
14001   sinkMBB->splice(sinkMBB->begin(), MBB,
14002                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14003   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14004
14005   // thisMBB:
14006   // Lo
14007   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14008   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14009     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14010     if (NewMO.isReg())
14011       NewMO.setIsKill(false);
14012     MIB.addOperand(NewMO);
14013   }
14014   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14015     unsigned flags = (*MMOI)->getFlags();
14016     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14017     MachineMemOperand *MMO =
14018       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14019                                (*MMOI)->getSize(),
14020                                (*MMOI)->getBaseAlignment(),
14021                                (*MMOI)->getTBAAInfo(),
14022                                (*MMOI)->getRanges());
14023     MIB.addMemOperand(MMO);
14024   };
14025   MachineInstr *LowMI = MIB;
14026
14027   // Hi
14028   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14029   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14030     if (i == X86::AddrDisp) {
14031       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14032     } else {
14033       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14034       if (NewMO.isReg())
14035         NewMO.setIsKill(false);
14036       MIB.addOperand(NewMO);
14037     }
14038   }
14039   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14040
14041   thisMBB->addSuccessor(mainMBB);
14042
14043   // mainMBB:
14044   MachineBasicBlock *origMainMBB = mainMBB;
14045
14046   // Add PHIs.
14047   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14048                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14049   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14050                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14051
14052   unsigned Opc = MI->getOpcode();
14053   switch (Opc) {
14054   default:
14055     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14056   case X86::ATOMAND6432:
14057   case X86::ATOMOR6432:
14058   case X86::ATOMXOR6432:
14059   case X86::ATOMADD6432:
14060   case X86::ATOMSUB6432: {
14061     unsigned HiOpc;
14062     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14063     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14064       .addReg(SrcLoReg);
14065     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14066       .addReg(SrcHiReg);
14067     break;
14068   }
14069   case X86::ATOMNAND6432: {
14070     unsigned HiOpc, NOTOpc;
14071     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14072     unsigned TmpL = MRI.createVirtualRegister(RC);
14073     unsigned TmpH = MRI.createVirtualRegister(RC);
14074     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14075       .addReg(t4L);
14076     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14077       .addReg(t4H);
14078     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14079     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14080     break;
14081   }
14082   case X86::ATOMMAX6432:
14083   case X86::ATOMMIN6432:
14084   case X86::ATOMUMAX6432:
14085   case X86::ATOMUMIN6432: {
14086     unsigned HiOpc;
14087     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14088     unsigned cL = MRI.createVirtualRegister(RC8);
14089     unsigned cH = MRI.createVirtualRegister(RC8);
14090     unsigned cL32 = MRI.createVirtualRegister(RC);
14091     unsigned cH32 = MRI.createVirtualRegister(RC);
14092     unsigned cc = MRI.createVirtualRegister(RC);
14093     // cl := cmp src_lo, lo
14094     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14095       .addReg(SrcLoReg).addReg(t4L);
14096     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14097     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14098     // ch := cmp src_hi, hi
14099     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14100       .addReg(SrcHiReg).addReg(t4H);
14101     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14102     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14103     // cc := if (src_hi == hi) ? cl : ch;
14104     if (Subtarget->hasCMov()) {
14105       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14106         .addReg(cH32).addReg(cL32);
14107     } else {
14108       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14109               .addReg(cH32).addReg(cL32)
14110               .addImm(X86::COND_E);
14111       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14112     }
14113     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14114     if (Subtarget->hasCMov()) {
14115       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14116         .addReg(SrcLoReg).addReg(t4L);
14117       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14118         .addReg(SrcHiReg).addReg(t4H);
14119     } else {
14120       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14121               .addReg(SrcLoReg).addReg(t4L)
14122               .addImm(X86::COND_NE);
14123       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14124       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14125       // 2nd CMOV lowering.
14126       mainMBB->addLiveIn(X86::EFLAGS);
14127       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14128               .addReg(SrcHiReg).addReg(t4H)
14129               .addImm(X86::COND_NE);
14130       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14131       // Replace the original PHI node as mainMBB is changed after CMOV
14132       // lowering.
14133       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14134         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14135       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14136         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14137       PhiL->eraseFromParent();
14138       PhiH->eraseFromParent();
14139     }
14140     break;
14141   }
14142   case X86::ATOMSWAP6432: {
14143     unsigned HiOpc;
14144     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14145     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14146     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14147     break;
14148   }
14149   }
14150
14151   // Copy EDX:EAX back from HiReg:LoReg
14152   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14153   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14154   // Copy ECX:EBX from t1H:t1L
14155   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14156   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14157
14158   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14159   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14160     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14161     if (NewMO.isReg())
14162       NewMO.setIsKill(false);
14163     MIB.addOperand(NewMO);
14164   }
14165   MIB.setMemRefs(MMOBegin, MMOEnd);
14166
14167   // Copy EDX:EAX back to t3H:t3L
14168   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14169   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14170
14171   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14172
14173   mainMBB->addSuccessor(origMainMBB);
14174   mainMBB->addSuccessor(sinkMBB);
14175
14176   // sinkMBB:
14177   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14178           TII->get(TargetOpcode::COPY), DstLoReg)
14179     .addReg(t3L);
14180   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14181           TII->get(TargetOpcode::COPY), DstHiReg)
14182     .addReg(t3H);
14183
14184   MI->eraseFromParent();
14185   return sinkMBB;
14186 }
14187
14188 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14189 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14190 // in the .td file.
14191 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14192                                        const TargetInstrInfo *TII) {
14193   unsigned Opc;
14194   switch (MI->getOpcode()) {
14195   default: llvm_unreachable("illegal opcode!");
14196   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14197   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14198   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14199   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14200   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14201   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14202   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14203   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14204   }
14205
14206   DebugLoc dl = MI->getDebugLoc();
14207   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14208
14209   unsigned NumArgs = MI->getNumOperands();
14210   for (unsigned i = 1; i < NumArgs; ++i) {
14211     MachineOperand &Op = MI->getOperand(i);
14212     if (!(Op.isReg() && Op.isImplicit()))
14213       MIB.addOperand(Op);
14214   }
14215   if (MI->hasOneMemOperand())
14216     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14217
14218   BuildMI(*BB, MI, dl,
14219     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14220     .addReg(X86::XMM0);
14221
14222   MI->eraseFromParent();
14223   return BB;
14224 }
14225
14226 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14227 // defs in an instruction pattern
14228 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14229                                        const TargetInstrInfo *TII) {
14230   unsigned Opc;
14231   switch (MI->getOpcode()) {
14232   default: llvm_unreachable("illegal opcode!");
14233   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14234   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14235   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14236   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14237   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14238   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14239   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14240   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14241   }
14242
14243   DebugLoc dl = MI->getDebugLoc();
14244   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14245
14246   unsigned NumArgs = MI->getNumOperands(); // remove the results
14247   for (unsigned i = 1; i < NumArgs; ++i) {
14248     MachineOperand &Op = MI->getOperand(i);
14249     if (!(Op.isReg() && Op.isImplicit()))
14250       MIB.addOperand(Op);
14251   }
14252   if (MI->hasOneMemOperand())
14253     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14254
14255   BuildMI(*BB, MI, dl,
14256     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14257     .addReg(X86::ECX);
14258
14259   MI->eraseFromParent();
14260   return BB;
14261 }
14262
14263 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14264                                        const TargetInstrInfo *TII,
14265                                        const X86Subtarget* Subtarget) {
14266   DebugLoc dl = MI->getDebugLoc();
14267
14268   // Address into RAX/EAX, other two args into ECX, EDX.
14269   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14270   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14271   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14272   for (int i = 0; i < X86::AddrNumOperands; ++i)
14273     MIB.addOperand(MI->getOperand(i));
14274
14275   unsigned ValOps = X86::AddrNumOperands;
14276   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14277     .addReg(MI->getOperand(ValOps).getReg());
14278   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14279     .addReg(MI->getOperand(ValOps+1).getReg());
14280
14281   // The instruction doesn't actually take any operands though.
14282   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14283
14284   MI->eraseFromParent(); // The pseudo is gone now.
14285   return BB;
14286 }
14287
14288 MachineBasicBlock *
14289 X86TargetLowering::EmitVAARG64WithCustomInserter(
14290                    MachineInstr *MI,
14291                    MachineBasicBlock *MBB) const {
14292   // Emit va_arg instruction on X86-64.
14293
14294   // Operands to this pseudo-instruction:
14295   // 0  ) Output        : destination address (reg)
14296   // 1-5) Input         : va_list address (addr, i64mem)
14297   // 6  ) ArgSize       : Size (in bytes) of vararg type
14298   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14299   // 8  ) Align         : Alignment of type
14300   // 9  ) EFLAGS (implicit-def)
14301
14302   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14303   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14304
14305   unsigned DestReg = MI->getOperand(0).getReg();
14306   MachineOperand &Base = MI->getOperand(1);
14307   MachineOperand &Scale = MI->getOperand(2);
14308   MachineOperand &Index = MI->getOperand(3);
14309   MachineOperand &Disp = MI->getOperand(4);
14310   MachineOperand &Segment = MI->getOperand(5);
14311   unsigned ArgSize = MI->getOperand(6).getImm();
14312   unsigned ArgMode = MI->getOperand(7).getImm();
14313   unsigned Align = MI->getOperand(8).getImm();
14314
14315   // Memory Reference
14316   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14317   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14318   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14319
14320   // Machine Information
14321   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14322   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14323   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14324   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14325   DebugLoc DL = MI->getDebugLoc();
14326
14327   // struct va_list {
14328   //   i32   gp_offset
14329   //   i32   fp_offset
14330   //   i64   overflow_area (address)
14331   //   i64   reg_save_area (address)
14332   // }
14333   // sizeof(va_list) = 24
14334   // alignment(va_list) = 8
14335
14336   unsigned TotalNumIntRegs = 6;
14337   unsigned TotalNumXMMRegs = 8;
14338   bool UseGPOffset = (ArgMode == 1);
14339   bool UseFPOffset = (ArgMode == 2);
14340   unsigned MaxOffset = TotalNumIntRegs * 8 +
14341                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14342
14343   /* Align ArgSize to a multiple of 8 */
14344   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14345   bool NeedsAlign = (Align > 8);
14346
14347   MachineBasicBlock *thisMBB = MBB;
14348   MachineBasicBlock *overflowMBB;
14349   MachineBasicBlock *offsetMBB;
14350   MachineBasicBlock *endMBB;
14351
14352   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
14353   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
14354   unsigned OffsetReg = 0;
14355
14356   if (!UseGPOffset && !UseFPOffset) {
14357     // If we only pull from the overflow region, we don't create a branch.
14358     // We don't need to alter control flow.
14359     OffsetDestReg = 0; // unused
14360     OverflowDestReg = DestReg;
14361
14362     offsetMBB = NULL;
14363     overflowMBB = thisMBB;
14364     endMBB = thisMBB;
14365   } else {
14366     // First emit code to check if gp_offset (or fp_offset) is below the bound.
14367     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14368     // If not, pull from overflow_area. (branch to overflowMBB)
14369     //
14370     //       thisMBB
14371     //         |     .
14372     //         |        .
14373     //     offsetMBB   overflowMBB
14374     //         |        .
14375     //         |     .
14376     //        endMBB
14377
14378     // Registers for the PHI in endMBB
14379     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14380     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14381
14382     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14383     MachineFunction *MF = MBB->getParent();
14384     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14385     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14386     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14387
14388     MachineFunction::iterator MBBIter = MBB;
14389     ++MBBIter;
14390
14391     // Insert the new basic blocks
14392     MF->insert(MBBIter, offsetMBB);
14393     MF->insert(MBBIter, overflowMBB);
14394     MF->insert(MBBIter, endMBB);
14395
14396     // Transfer the remainder of MBB and its successor edges to endMBB.
14397     endMBB->splice(endMBB->begin(), thisMBB,
14398                     llvm::next(MachineBasicBlock::iterator(MI)),
14399                     thisMBB->end());
14400     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14401
14402     // Make offsetMBB and overflowMBB successors of thisMBB
14403     thisMBB->addSuccessor(offsetMBB);
14404     thisMBB->addSuccessor(overflowMBB);
14405
14406     // endMBB is a successor of both offsetMBB and overflowMBB
14407     offsetMBB->addSuccessor(endMBB);
14408     overflowMBB->addSuccessor(endMBB);
14409
14410     // Load the offset value into a register
14411     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14412     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14413       .addOperand(Base)
14414       .addOperand(Scale)
14415       .addOperand(Index)
14416       .addDisp(Disp, UseFPOffset ? 4 : 0)
14417       .addOperand(Segment)
14418       .setMemRefs(MMOBegin, MMOEnd);
14419
14420     // Check if there is enough room left to pull this argument.
14421     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14422       .addReg(OffsetReg)
14423       .addImm(MaxOffset + 8 - ArgSizeA8);
14424
14425     // Branch to "overflowMBB" if offset >= max
14426     // Fall through to "offsetMBB" otherwise
14427     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14428       .addMBB(overflowMBB);
14429   }
14430
14431   // In offsetMBB, emit code to use the reg_save_area.
14432   if (offsetMBB) {
14433     assert(OffsetReg != 0);
14434
14435     // Read the reg_save_area address.
14436     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14437     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14438       .addOperand(Base)
14439       .addOperand(Scale)
14440       .addOperand(Index)
14441       .addDisp(Disp, 16)
14442       .addOperand(Segment)
14443       .setMemRefs(MMOBegin, MMOEnd);
14444
14445     // Zero-extend the offset
14446     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14447       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14448         .addImm(0)
14449         .addReg(OffsetReg)
14450         .addImm(X86::sub_32bit);
14451
14452     // Add the offset to the reg_save_area to get the final address.
14453     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14454       .addReg(OffsetReg64)
14455       .addReg(RegSaveReg);
14456
14457     // Compute the offset for the next argument
14458     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14459     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14460       .addReg(OffsetReg)
14461       .addImm(UseFPOffset ? 16 : 8);
14462
14463     // Store it back into the va_list.
14464     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14465       .addOperand(Base)
14466       .addOperand(Scale)
14467       .addOperand(Index)
14468       .addDisp(Disp, UseFPOffset ? 4 : 0)
14469       .addOperand(Segment)
14470       .addReg(NextOffsetReg)
14471       .setMemRefs(MMOBegin, MMOEnd);
14472
14473     // Jump to endMBB
14474     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14475       .addMBB(endMBB);
14476   }
14477
14478   //
14479   // Emit code to use overflow area
14480   //
14481
14482   // Load the overflow_area address into a register.
14483   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14484   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14485     .addOperand(Base)
14486     .addOperand(Scale)
14487     .addOperand(Index)
14488     .addDisp(Disp, 8)
14489     .addOperand(Segment)
14490     .setMemRefs(MMOBegin, MMOEnd);
14491
14492   // If we need to align it, do so. Otherwise, just copy the address
14493   // to OverflowDestReg.
14494   if (NeedsAlign) {
14495     // Align the overflow address
14496     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14497     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14498
14499     // aligned_addr = (addr + (align-1)) & ~(align-1)
14500     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14501       .addReg(OverflowAddrReg)
14502       .addImm(Align-1);
14503
14504     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14505       .addReg(TmpReg)
14506       .addImm(~(uint64_t)(Align-1));
14507   } else {
14508     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14509       .addReg(OverflowAddrReg);
14510   }
14511
14512   // Compute the next overflow address after this argument.
14513   // (the overflow address should be kept 8-byte aligned)
14514   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14515   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14516     .addReg(OverflowDestReg)
14517     .addImm(ArgSizeA8);
14518
14519   // Store the new overflow address.
14520   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14521     .addOperand(Base)
14522     .addOperand(Scale)
14523     .addOperand(Index)
14524     .addDisp(Disp, 8)
14525     .addOperand(Segment)
14526     .addReg(NextAddrReg)
14527     .setMemRefs(MMOBegin, MMOEnd);
14528
14529   // If we branched, emit the PHI to the front of endMBB.
14530   if (offsetMBB) {
14531     BuildMI(*endMBB, endMBB->begin(), DL,
14532             TII->get(X86::PHI), DestReg)
14533       .addReg(OffsetDestReg).addMBB(offsetMBB)
14534       .addReg(OverflowDestReg).addMBB(overflowMBB);
14535   }
14536
14537   // Erase the pseudo instruction
14538   MI->eraseFromParent();
14539
14540   return endMBB;
14541 }
14542
14543 MachineBasicBlock *
14544 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14545                                                  MachineInstr *MI,
14546                                                  MachineBasicBlock *MBB) const {
14547   // Emit code to save XMM registers to the stack. The ABI says that the
14548   // number of registers to save is given in %al, so it's theoretically
14549   // possible to do an indirect jump trick to avoid saving all of them,
14550   // however this code takes a simpler approach and just executes all
14551   // of the stores if %al is non-zero. It's less code, and it's probably
14552   // easier on the hardware branch predictor, and stores aren't all that
14553   // expensive anyway.
14554
14555   // Create the new basic blocks. One block contains all the XMM stores,
14556   // and one block is the final destination regardless of whether any
14557   // stores were performed.
14558   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14559   MachineFunction *F = MBB->getParent();
14560   MachineFunction::iterator MBBIter = MBB;
14561   ++MBBIter;
14562   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14563   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14564   F->insert(MBBIter, XMMSaveMBB);
14565   F->insert(MBBIter, EndMBB);
14566
14567   // Transfer the remainder of MBB and its successor edges to EndMBB.
14568   EndMBB->splice(EndMBB->begin(), MBB,
14569                  llvm::next(MachineBasicBlock::iterator(MI)),
14570                  MBB->end());
14571   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14572
14573   // The original block will now fall through to the XMM save block.
14574   MBB->addSuccessor(XMMSaveMBB);
14575   // The XMMSaveMBB will fall through to the end block.
14576   XMMSaveMBB->addSuccessor(EndMBB);
14577
14578   // Now add the instructions.
14579   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14580   DebugLoc DL = MI->getDebugLoc();
14581
14582   unsigned CountReg = MI->getOperand(0).getReg();
14583   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14584   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14585
14586   if (!Subtarget->isTargetWin64()) {
14587     // If %al is 0, branch around the XMM save block.
14588     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14589     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14590     MBB->addSuccessor(EndMBB);
14591   }
14592
14593   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14594   // In the XMM save block, save all the XMM argument registers.
14595   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14596     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14597     MachineMemOperand *MMO =
14598       F->getMachineMemOperand(
14599           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14600         MachineMemOperand::MOStore,
14601         /*Size=*/16, /*Align=*/16);
14602     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14603       .addFrameIndex(RegSaveFrameIndex)
14604       .addImm(/*Scale=*/1)
14605       .addReg(/*IndexReg=*/0)
14606       .addImm(/*Disp=*/Offset)
14607       .addReg(/*Segment=*/0)
14608       .addReg(MI->getOperand(i).getReg())
14609       .addMemOperand(MMO);
14610   }
14611
14612   MI->eraseFromParent();   // The pseudo instruction is gone now.
14613
14614   return EndMBB;
14615 }
14616
14617 // The EFLAGS operand of SelectItr might be missing a kill marker
14618 // because there were multiple uses of EFLAGS, and ISel didn't know
14619 // which to mark. Figure out whether SelectItr should have had a
14620 // kill marker, and set it if it should. Returns the correct kill
14621 // marker value.
14622 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14623                                      MachineBasicBlock* BB,
14624                                      const TargetRegisterInfo* TRI) {
14625   // Scan forward through BB for a use/def of EFLAGS.
14626   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14627   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14628     const MachineInstr& mi = *miI;
14629     if (mi.readsRegister(X86::EFLAGS))
14630       return false;
14631     if (mi.definesRegister(X86::EFLAGS))
14632       break; // Should have kill-flag - update below.
14633   }
14634
14635   // If we hit the end of the block, check whether EFLAGS is live into a
14636   // successor.
14637   if (miI == BB->end()) {
14638     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14639                                           sEnd = BB->succ_end();
14640          sItr != sEnd; ++sItr) {
14641       MachineBasicBlock* succ = *sItr;
14642       if (succ->isLiveIn(X86::EFLAGS))
14643         return false;
14644     }
14645   }
14646
14647   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14648   // out. SelectMI should have a kill flag on EFLAGS.
14649   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14650   return true;
14651 }
14652
14653 MachineBasicBlock *
14654 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14655                                      MachineBasicBlock *BB) const {
14656   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14657   DebugLoc DL = MI->getDebugLoc();
14658
14659   // To "insert" a SELECT_CC instruction, we actually have to insert the
14660   // diamond control-flow pattern.  The incoming instruction knows the
14661   // destination vreg to set, the condition code register to branch on, the
14662   // true/false values to select between, and a branch opcode to use.
14663   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14664   MachineFunction::iterator It = BB;
14665   ++It;
14666
14667   //  thisMBB:
14668   //  ...
14669   //   TrueVal = ...
14670   //   cmpTY ccX, r1, r2
14671   //   bCC copy1MBB
14672   //   fallthrough --> copy0MBB
14673   MachineBasicBlock *thisMBB = BB;
14674   MachineFunction *F = BB->getParent();
14675   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14676   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14677   F->insert(It, copy0MBB);
14678   F->insert(It, sinkMBB);
14679
14680   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14681   // live into the sink and copy blocks.
14682   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14683   if (!MI->killsRegister(X86::EFLAGS) &&
14684       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14685     copy0MBB->addLiveIn(X86::EFLAGS);
14686     sinkMBB->addLiveIn(X86::EFLAGS);
14687   }
14688
14689   // Transfer the remainder of BB and its successor edges to sinkMBB.
14690   sinkMBB->splice(sinkMBB->begin(), BB,
14691                   llvm::next(MachineBasicBlock::iterator(MI)),
14692                   BB->end());
14693   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14694
14695   // Add the true and fallthrough blocks as its successors.
14696   BB->addSuccessor(copy0MBB);
14697   BB->addSuccessor(sinkMBB);
14698
14699   // Create the conditional branch instruction.
14700   unsigned Opc =
14701     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14702   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14703
14704   //  copy0MBB:
14705   //   %FalseValue = ...
14706   //   # fallthrough to sinkMBB
14707   copy0MBB->addSuccessor(sinkMBB);
14708
14709   //  sinkMBB:
14710   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14711   //  ...
14712   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14713           TII->get(X86::PHI), MI->getOperand(0).getReg())
14714     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14715     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14716
14717   MI->eraseFromParent();   // The pseudo instruction is gone now.
14718   return sinkMBB;
14719 }
14720
14721 MachineBasicBlock *
14722 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14723                                         bool Is64Bit) const {
14724   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14725   DebugLoc DL = MI->getDebugLoc();
14726   MachineFunction *MF = BB->getParent();
14727   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14728
14729   assert(getTargetMachine().Options.EnableSegmentedStacks);
14730
14731   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14732   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14733
14734   // BB:
14735   //  ... [Till the alloca]
14736   // If stacklet is not large enough, jump to mallocMBB
14737   //
14738   // bumpMBB:
14739   //  Allocate by subtracting from RSP
14740   //  Jump to continueMBB
14741   //
14742   // mallocMBB:
14743   //  Allocate by call to runtime
14744   //
14745   // continueMBB:
14746   //  ...
14747   //  [rest of original BB]
14748   //
14749
14750   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14751   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14752   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14753
14754   MachineRegisterInfo &MRI = MF->getRegInfo();
14755   const TargetRegisterClass *AddrRegClass =
14756     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14757
14758   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14759     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14760     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14761     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14762     sizeVReg = MI->getOperand(1).getReg(),
14763     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14764
14765   MachineFunction::iterator MBBIter = BB;
14766   ++MBBIter;
14767
14768   MF->insert(MBBIter, bumpMBB);
14769   MF->insert(MBBIter, mallocMBB);
14770   MF->insert(MBBIter, continueMBB);
14771
14772   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14773                       (MachineBasicBlock::iterator(MI)), BB->end());
14774   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14775
14776   // Add code to the main basic block to check if the stack limit has been hit,
14777   // and if so, jump to mallocMBB otherwise to bumpMBB.
14778   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14779   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14780     .addReg(tmpSPVReg).addReg(sizeVReg);
14781   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14782     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14783     .addReg(SPLimitVReg);
14784   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14785
14786   // bumpMBB simply decreases the stack pointer, since we know the current
14787   // stacklet has enough space.
14788   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14789     .addReg(SPLimitVReg);
14790   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14791     .addReg(SPLimitVReg);
14792   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14793
14794   // Calls into a routine in libgcc to allocate more space from the heap.
14795   const uint32_t *RegMask =
14796     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14797   if (Is64Bit) {
14798     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14799       .addReg(sizeVReg);
14800     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14801       .addExternalSymbol("__morestack_allocate_stack_space")
14802       .addRegMask(RegMask)
14803       .addReg(X86::RDI, RegState::Implicit)
14804       .addReg(X86::RAX, RegState::ImplicitDefine);
14805   } else {
14806     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14807       .addImm(12);
14808     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14809     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14810       .addExternalSymbol("__morestack_allocate_stack_space")
14811       .addRegMask(RegMask)
14812       .addReg(X86::EAX, RegState::ImplicitDefine);
14813   }
14814
14815   if (!Is64Bit)
14816     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14817       .addImm(16);
14818
14819   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14820     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14821   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14822
14823   // Set up the CFG correctly.
14824   BB->addSuccessor(bumpMBB);
14825   BB->addSuccessor(mallocMBB);
14826   mallocMBB->addSuccessor(continueMBB);
14827   bumpMBB->addSuccessor(continueMBB);
14828
14829   // Take care of the PHI nodes.
14830   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14831           MI->getOperand(0).getReg())
14832     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14833     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14834
14835   // Delete the original pseudo instruction.
14836   MI->eraseFromParent();
14837
14838   // And we're done.
14839   return continueMBB;
14840 }
14841
14842 MachineBasicBlock *
14843 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14844                                           MachineBasicBlock *BB) const {
14845   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14846   DebugLoc DL = MI->getDebugLoc();
14847
14848   assert(!Subtarget->isTargetEnvMacho());
14849
14850   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14851   // non-trivial part is impdef of ESP.
14852
14853   if (Subtarget->isTargetWin64()) {
14854     if (Subtarget->isTargetCygMing()) {
14855       // ___chkstk(Mingw64):
14856       // Clobbers R10, R11, RAX and EFLAGS.
14857       // Updates RSP.
14858       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14859         .addExternalSymbol("___chkstk")
14860         .addReg(X86::RAX, RegState::Implicit)
14861         .addReg(X86::RSP, RegState::Implicit)
14862         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14863         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14864         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14865     } else {
14866       // __chkstk(MSVCRT): does not update stack pointer.
14867       // Clobbers R10, R11 and EFLAGS.
14868       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14869         .addExternalSymbol("__chkstk")
14870         .addReg(X86::RAX, RegState::Implicit)
14871         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14872       // RAX has the offset to be subtracted from RSP.
14873       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14874         .addReg(X86::RSP)
14875         .addReg(X86::RAX);
14876     }
14877   } else {
14878     const char *StackProbeSymbol =
14879       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14880
14881     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14882       .addExternalSymbol(StackProbeSymbol)
14883       .addReg(X86::EAX, RegState::Implicit)
14884       .addReg(X86::ESP, RegState::Implicit)
14885       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14886       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14887       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14888   }
14889
14890   MI->eraseFromParent();   // The pseudo instruction is gone now.
14891   return BB;
14892 }
14893
14894 MachineBasicBlock *
14895 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14896                                       MachineBasicBlock *BB) const {
14897   // This is pretty easy.  We're taking the value that we received from
14898   // our load from the relocation, sticking it in either RDI (x86-64)
14899   // or EAX and doing an indirect call.  The return value will then
14900   // be in the normal return register.
14901   const X86InstrInfo *TII
14902     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14903   DebugLoc DL = MI->getDebugLoc();
14904   MachineFunction *F = BB->getParent();
14905
14906   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14907   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14908
14909   // Get a register mask for the lowered call.
14910   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14911   // proper register mask.
14912   const uint32_t *RegMask =
14913     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14914   if (Subtarget->is64Bit()) {
14915     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14916                                       TII->get(X86::MOV64rm), X86::RDI)
14917     .addReg(X86::RIP)
14918     .addImm(0).addReg(0)
14919     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14920                       MI->getOperand(3).getTargetFlags())
14921     .addReg(0);
14922     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14923     addDirectMem(MIB, X86::RDI);
14924     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14925   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14926     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14927                                       TII->get(X86::MOV32rm), X86::EAX)
14928     .addReg(0)
14929     .addImm(0).addReg(0)
14930     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14931                       MI->getOperand(3).getTargetFlags())
14932     .addReg(0);
14933     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14934     addDirectMem(MIB, X86::EAX);
14935     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14936   } else {
14937     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14938                                       TII->get(X86::MOV32rm), X86::EAX)
14939     .addReg(TII->getGlobalBaseReg(F))
14940     .addImm(0).addReg(0)
14941     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14942                       MI->getOperand(3).getTargetFlags())
14943     .addReg(0);
14944     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14945     addDirectMem(MIB, X86::EAX);
14946     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14947   }
14948
14949   MI->eraseFromParent(); // The pseudo instruction is gone now.
14950   return BB;
14951 }
14952
14953 MachineBasicBlock *
14954 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14955                                     MachineBasicBlock *MBB) const {
14956   DebugLoc DL = MI->getDebugLoc();
14957   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14958
14959   MachineFunction *MF = MBB->getParent();
14960   MachineRegisterInfo &MRI = MF->getRegInfo();
14961
14962   const BasicBlock *BB = MBB->getBasicBlock();
14963   MachineFunction::iterator I = MBB;
14964   ++I;
14965
14966   // Memory Reference
14967   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14968   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14969
14970   unsigned DstReg;
14971   unsigned MemOpndSlot = 0;
14972
14973   unsigned CurOp = 0;
14974
14975   DstReg = MI->getOperand(CurOp++).getReg();
14976   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14977   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14978   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14979   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14980
14981   MemOpndSlot = CurOp;
14982
14983   MVT PVT = getPointerTy();
14984   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14985          "Invalid Pointer Size!");
14986
14987   // For v = setjmp(buf), we generate
14988   //
14989   // thisMBB:
14990   //  buf[LabelOffset] = restoreMBB
14991   //  SjLjSetup restoreMBB
14992   //
14993   // mainMBB:
14994   //  v_main = 0
14995   //
14996   // sinkMBB:
14997   //  v = phi(main, restore)
14998   //
14999   // restoreMBB:
15000   //  v_restore = 1
15001
15002   MachineBasicBlock *thisMBB = MBB;
15003   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15004   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15005   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15006   MF->insert(I, mainMBB);
15007   MF->insert(I, sinkMBB);
15008   MF->push_back(restoreMBB);
15009
15010   MachineInstrBuilder MIB;
15011
15012   // Transfer the remainder of BB and its successor edges to sinkMBB.
15013   sinkMBB->splice(sinkMBB->begin(), MBB,
15014                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15015   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15016
15017   // thisMBB:
15018   unsigned PtrStoreOpc = 0;
15019   unsigned LabelReg = 0;
15020   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15021   Reloc::Model RM = getTargetMachine().getRelocationModel();
15022   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15023                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15024
15025   // Prepare IP either in reg or imm.
15026   if (!UseImmLabel) {
15027     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15028     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15029     LabelReg = MRI.createVirtualRegister(PtrRC);
15030     if (Subtarget->is64Bit()) {
15031       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15032               .addReg(X86::RIP)
15033               .addImm(0)
15034               .addReg(0)
15035               .addMBB(restoreMBB)
15036               .addReg(0);
15037     } else {
15038       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15039       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15040               .addReg(XII->getGlobalBaseReg(MF))
15041               .addImm(0)
15042               .addReg(0)
15043               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15044               .addReg(0);
15045     }
15046   } else
15047     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15048   // Store IP
15049   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15050   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15051     if (i == X86::AddrDisp)
15052       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15053     else
15054       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15055   }
15056   if (!UseImmLabel)
15057     MIB.addReg(LabelReg);
15058   else
15059     MIB.addMBB(restoreMBB);
15060   MIB.setMemRefs(MMOBegin, MMOEnd);
15061   // Setup
15062   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15063           .addMBB(restoreMBB);
15064
15065   const X86RegisterInfo *RegInfo =
15066     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15067   MIB.addRegMask(RegInfo->getNoPreservedMask());
15068   thisMBB->addSuccessor(mainMBB);
15069   thisMBB->addSuccessor(restoreMBB);
15070
15071   // mainMBB:
15072   //  EAX = 0
15073   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15074   mainMBB->addSuccessor(sinkMBB);
15075
15076   // sinkMBB:
15077   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15078           TII->get(X86::PHI), DstReg)
15079     .addReg(mainDstReg).addMBB(mainMBB)
15080     .addReg(restoreDstReg).addMBB(restoreMBB);
15081
15082   // restoreMBB:
15083   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15084   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15085   restoreMBB->addSuccessor(sinkMBB);
15086
15087   MI->eraseFromParent();
15088   return sinkMBB;
15089 }
15090
15091 MachineBasicBlock *
15092 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15093                                      MachineBasicBlock *MBB) const {
15094   DebugLoc DL = MI->getDebugLoc();
15095   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15096
15097   MachineFunction *MF = MBB->getParent();
15098   MachineRegisterInfo &MRI = MF->getRegInfo();
15099
15100   // Memory Reference
15101   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15102   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15103
15104   MVT PVT = getPointerTy();
15105   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15106          "Invalid Pointer Size!");
15107
15108   const TargetRegisterClass *RC =
15109     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15110   unsigned Tmp = MRI.createVirtualRegister(RC);
15111   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15112   const X86RegisterInfo *RegInfo =
15113     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15114   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15115   unsigned SP = RegInfo->getStackRegister();
15116
15117   MachineInstrBuilder MIB;
15118
15119   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15120   const int64_t SPOffset = 2 * PVT.getStoreSize();
15121
15122   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15123   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15124
15125   // Reload FP
15126   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15127   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15128     MIB.addOperand(MI->getOperand(i));
15129   MIB.setMemRefs(MMOBegin, MMOEnd);
15130   // Reload IP
15131   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15132   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15133     if (i == X86::AddrDisp)
15134       MIB.addDisp(MI->getOperand(i), LabelOffset);
15135     else
15136       MIB.addOperand(MI->getOperand(i));
15137   }
15138   MIB.setMemRefs(MMOBegin, MMOEnd);
15139   // Reload SP
15140   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15141   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15142     if (i == X86::AddrDisp)
15143       MIB.addDisp(MI->getOperand(i), SPOffset);
15144     else
15145       MIB.addOperand(MI->getOperand(i));
15146   }
15147   MIB.setMemRefs(MMOBegin, MMOEnd);
15148   // Jump
15149   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15150
15151   MI->eraseFromParent();
15152   return MBB;
15153 }
15154
15155 MachineBasicBlock *
15156 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15157                                                MachineBasicBlock *BB) const {
15158   switch (MI->getOpcode()) {
15159   default: llvm_unreachable("Unexpected instr type to insert");
15160   case X86::TAILJMPd64:
15161   case X86::TAILJMPr64:
15162   case X86::TAILJMPm64:
15163     llvm_unreachable("TAILJMP64 would not be touched here.");
15164   case X86::TCRETURNdi64:
15165   case X86::TCRETURNri64:
15166   case X86::TCRETURNmi64:
15167     return BB;
15168   case X86::WIN_ALLOCA:
15169     return EmitLoweredWinAlloca(MI, BB);
15170   case X86::SEG_ALLOCA_32:
15171     return EmitLoweredSegAlloca(MI, BB, false);
15172   case X86::SEG_ALLOCA_64:
15173     return EmitLoweredSegAlloca(MI, BB, true);
15174   case X86::TLSCall_32:
15175   case X86::TLSCall_64:
15176     return EmitLoweredTLSCall(MI, BB);
15177   case X86::CMOV_GR8:
15178   case X86::CMOV_FR32:
15179   case X86::CMOV_FR64:
15180   case X86::CMOV_V4F32:
15181   case X86::CMOV_V2F64:
15182   case X86::CMOV_V2I64:
15183   case X86::CMOV_V8F32:
15184   case X86::CMOV_V4F64:
15185   case X86::CMOV_V4I64:
15186   case X86::CMOV_GR16:
15187   case X86::CMOV_GR32:
15188   case X86::CMOV_RFP32:
15189   case X86::CMOV_RFP64:
15190   case X86::CMOV_RFP80:
15191     return EmitLoweredSelect(MI, BB);
15192
15193   case X86::FP32_TO_INT16_IN_MEM:
15194   case X86::FP32_TO_INT32_IN_MEM:
15195   case X86::FP32_TO_INT64_IN_MEM:
15196   case X86::FP64_TO_INT16_IN_MEM:
15197   case X86::FP64_TO_INT32_IN_MEM:
15198   case X86::FP64_TO_INT64_IN_MEM:
15199   case X86::FP80_TO_INT16_IN_MEM:
15200   case X86::FP80_TO_INT32_IN_MEM:
15201   case X86::FP80_TO_INT64_IN_MEM: {
15202     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15203     DebugLoc DL = MI->getDebugLoc();
15204
15205     // Change the floating point control register to use "round towards zero"
15206     // mode when truncating to an integer value.
15207     MachineFunction *F = BB->getParent();
15208     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15209     addFrameReference(BuildMI(*BB, MI, DL,
15210                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15211
15212     // Load the old value of the high byte of the control word...
15213     unsigned OldCW =
15214       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15215     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15216                       CWFrameIdx);
15217
15218     // Set the high part to be round to zero...
15219     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15220       .addImm(0xC7F);
15221
15222     // Reload the modified control word now...
15223     addFrameReference(BuildMI(*BB, MI, DL,
15224                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15225
15226     // Restore the memory image of control word to original value
15227     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15228       .addReg(OldCW);
15229
15230     // Get the X86 opcode to use.
15231     unsigned Opc;
15232     switch (MI->getOpcode()) {
15233     default: llvm_unreachable("illegal opcode!");
15234     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15235     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15236     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15237     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15238     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15239     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15240     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15241     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15242     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15243     }
15244
15245     X86AddressMode AM;
15246     MachineOperand &Op = MI->getOperand(0);
15247     if (Op.isReg()) {
15248       AM.BaseType = X86AddressMode::RegBase;
15249       AM.Base.Reg = Op.getReg();
15250     } else {
15251       AM.BaseType = X86AddressMode::FrameIndexBase;
15252       AM.Base.FrameIndex = Op.getIndex();
15253     }
15254     Op = MI->getOperand(1);
15255     if (Op.isImm())
15256       AM.Scale = Op.getImm();
15257     Op = MI->getOperand(2);
15258     if (Op.isImm())
15259       AM.IndexReg = Op.getImm();
15260     Op = MI->getOperand(3);
15261     if (Op.isGlobal()) {
15262       AM.GV = Op.getGlobal();
15263     } else {
15264       AM.Disp = Op.getImm();
15265     }
15266     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15267                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15268
15269     // Reload the original control word now.
15270     addFrameReference(BuildMI(*BB, MI, DL,
15271                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15272
15273     MI->eraseFromParent();   // The pseudo instruction is gone now.
15274     return BB;
15275   }
15276     // String/text processing lowering.
15277   case X86::PCMPISTRM128REG:
15278   case X86::VPCMPISTRM128REG:
15279   case X86::PCMPISTRM128MEM:
15280   case X86::VPCMPISTRM128MEM:
15281   case X86::PCMPESTRM128REG:
15282   case X86::VPCMPESTRM128REG:
15283   case X86::PCMPESTRM128MEM:
15284   case X86::VPCMPESTRM128MEM:
15285     assert(Subtarget->hasSSE42() &&
15286            "Target must have SSE4.2 or AVX features enabled");
15287     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15288
15289   // String/text processing lowering.
15290   case X86::PCMPISTRIREG:
15291   case X86::VPCMPISTRIREG:
15292   case X86::PCMPISTRIMEM:
15293   case X86::VPCMPISTRIMEM:
15294   case X86::PCMPESTRIREG:
15295   case X86::VPCMPESTRIREG:
15296   case X86::PCMPESTRIMEM:
15297   case X86::VPCMPESTRIMEM:
15298     assert(Subtarget->hasSSE42() &&
15299            "Target must have SSE4.2 or AVX features enabled");
15300     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15301
15302   // Thread synchronization.
15303   case X86::MONITOR:
15304     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15305
15306   // xbegin
15307   case X86::XBEGIN:
15308     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15309
15310   // Atomic Lowering.
15311   case X86::ATOMAND8:
15312   case X86::ATOMAND16:
15313   case X86::ATOMAND32:
15314   case X86::ATOMAND64:
15315     // Fall through
15316   case X86::ATOMOR8:
15317   case X86::ATOMOR16:
15318   case X86::ATOMOR32:
15319   case X86::ATOMOR64:
15320     // Fall through
15321   case X86::ATOMXOR16:
15322   case X86::ATOMXOR8:
15323   case X86::ATOMXOR32:
15324   case X86::ATOMXOR64:
15325     // Fall through
15326   case X86::ATOMNAND8:
15327   case X86::ATOMNAND16:
15328   case X86::ATOMNAND32:
15329   case X86::ATOMNAND64:
15330     // Fall through
15331   case X86::ATOMMAX8:
15332   case X86::ATOMMAX16:
15333   case X86::ATOMMAX32:
15334   case X86::ATOMMAX64:
15335     // Fall through
15336   case X86::ATOMMIN8:
15337   case X86::ATOMMIN16:
15338   case X86::ATOMMIN32:
15339   case X86::ATOMMIN64:
15340     // Fall through
15341   case X86::ATOMUMAX8:
15342   case X86::ATOMUMAX16:
15343   case X86::ATOMUMAX32:
15344   case X86::ATOMUMAX64:
15345     // Fall through
15346   case X86::ATOMUMIN8:
15347   case X86::ATOMUMIN16:
15348   case X86::ATOMUMIN32:
15349   case X86::ATOMUMIN64:
15350     return EmitAtomicLoadArith(MI, BB);
15351
15352   // This group does 64-bit operations on a 32-bit host.
15353   case X86::ATOMAND6432:
15354   case X86::ATOMOR6432:
15355   case X86::ATOMXOR6432:
15356   case X86::ATOMNAND6432:
15357   case X86::ATOMADD6432:
15358   case X86::ATOMSUB6432:
15359   case X86::ATOMMAX6432:
15360   case X86::ATOMMIN6432:
15361   case X86::ATOMUMAX6432:
15362   case X86::ATOMUMIN6432:
15363   case X86::ATOMSWAP6432:
15364     return EmitAtomicLoadArith6432(MI, BB);
15365
15366   case X86::VASTART_SAVE_XMM_REGS:
15367     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15368
15369   case X86::VAARG_64:
15370     return EmitVAARG64WithCustomInserter(MI, BB);
15371
15372   case X86::EH_SjLj_SetJmp32:
15373   case X86::EH_SjLj_SetJmp64:
15374     return emitEHSjLjSetJmp(MI, BB);
15375
15376   case X86::EH_SjLj_LongJmp32:
15377   case X86::EH_SjLj_LongJmp64:
15378     return emitEHSjLjLongJmp(MI, BB);
15379   }
15380 }
15381
15382 //===----------------------------------------------------------------------===//
15383 //                           X86 Optimization Hooks
15384 //===----------------------------------------------------------------------===//
15385
15386 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15387                                                        APInt &KnownZero,
15388                                                        APInt &KnownOne,
15389                                                        const SelectionDAG &DAG,
15390                                                        unsigned Depth) const {
15391   unsigned BitWidth = KnownZero.getBitWidth();
15392   unsigned Opc = Op.getOpcode();
15393   assert((Opc >= ISD::BUILTIN_OP_END ||
15394           Opc == ISD::INTRINSIC_WO_CHAIN ||
15395           Opc == ISD::INTRINSIC_W_CHAIN ||
15396           Opc == ISD::INTRINSIC_VOID) &&
15397          "Should use MaskedValueIsZero if you don't know whether Op"
15398          " is a target node!");
15399
15400   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
15401   switch (Opc) {
15402   default: break;
15403   case X86ISD::ADD:
15404   case X86ISD::SUB:
15405   case X86ISD::ADC:
15406   case X86ISD::SBB:
15407   case X86ISD::SMUL:
15408   case X86ISD::UMUL:
15409   case X86ISD::INC:
15410   case X86ISD::DEC:
15411   case X86ISD::OR:
15412   case X86ISD::XOR:
15413   case X86ISD::AND:
15414     // These nodes' second result is a boolean.
15415     if (Op.getResNo() == 0)
15416       break;
15417     // Fallthrough
15418   case X86ISD::SETCC:
15419     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15420     break;
15421   case ISD::INTRINSIC_WO_CHAIN: {
15422     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15423     unsigned NumLoBits = 0;
15424     switch (IntId) {
15425     default: break;
15426     case Intrinsic::x86_sse_movmsk_ps:
15427     case Intrinsic::x86_avx_movmsk_ps_256:
15428     case Intrinsic::x86_sse2_movmsk_pd:
15429     case Intrinsic::x86_avx_movmsk_pd_256:
15430     case Intrinsic::x86_mmx_pmovmskb:
15431     case Intrinsic::x86_sse2_pmovmskb_128:
15432     case Intrinsic::x86_avx2_pmovmskb: {
15433       // High bits of movmskp{s|d}, pmovmskb are known zero.
15434       switch (IntId) {
15435         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15436         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15437         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15438         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15439         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15440         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15441         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15442         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15443       }
15444       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15445       break;
15446     }
15447     }
15448     break;
15449   }
15450   }
15451 }
15452
15453 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15454                                                          unsigned Depth) const {
15455   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15456   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15457     return Op.getValueType().getScalarType().getSizeInBits();
15458
15459   // Fallback case.
15460   return 1;
15461 }
15462
15463 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15464 /// node is a GlobalAddress + offset.
15465 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15466                                        const GlobalValue* &GA,
15467                                        int64_t &Offset) const {
15468   if (N->getOpcode() == X86ISD::Wrapper) {
15469     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15470       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15471       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15472       return true;
15473     }
15474   }
15475   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15476 }
15477
15478 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15479 /// same as extracting the high 128-bit part of 256-bit vector and then
15480 /// inserting the result into the low part of a new 256-bit vector
15481 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15482   EVT VT = SVOp->getValueType(0);
15483   unsigned NumElems = VT.getVectorNumElements();
15484
15485   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15486   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15487     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15488         SVOp->getMaskElt(j) >= 0)
15489       return false;
15490
15491   return true;
15492 }
15493
15494 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15495 /// same as extracting the low 128-bit part of 256-bit vector and then
15496 /// inserting the result into the high part of a new 256-bit vector
15497 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15498   EVT VT = SVOp->getValueType(0);
15499   unsigned NumElems = VT.getVectorNumElements();
15500
15501   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15502   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15503     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15504         SVOp->getMaskElt(j) >= 0)
15505       return false;
15506
15507   return true;
15508 }
15509
15510 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15511 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15512                                         TargetLowering::DAGCombinerInfo &DCI,
15513                                         const X86Subtarget* Subtarget) {
15514   SDLoc dl(N);
15515   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15516   SDValue V1 = SVOp->getOperand(0);
15517   SDValue V2 = SVOp->getOperand(1);
15518   EVT VT = SVOp->getValueType(0);
15519   unsigned NumElems = VT.getVectorNumElements();
15520
15521   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15522       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15523     //
15524     //                   0,0,0,...
15525     //                      |
15526     //    V      UNDEF    BUILD_VECTOR    UNDEF
15527     //     \      /           \           /
15528     //  CONCAT_VECTOR         CONCAT_VECTOR
15529     //         \                  /
15530     //          \                /
15531     //          RESULT: V + zero extended
15532     //
15533     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15534         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15535         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15536       return SDValue();
15537
15538     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15539       return SDValue();
15540
15541     // To match the shuffle mask, the first half of the mask should
15542     // be exactly the first vector, and all the rest a splat with the
15543     // first element of the second one.
15544     for (unsigned i = 0; i != NumElems/2; ++i)
15545       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15546           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15547         return SDValue();
15548
15549     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15550     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15551       if (Ld->hasNUsesOfValue(1, 0)) {
15552         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15553         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15554         SDValue ResNode =
15555           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15556                                   array_lengthof(Ops),
15557                                   Ld->getMemoryVT(),
15558                                   Ld->getPointerInfo(),
15559                                   Ld->getAlignment(),
15560                                   false/*isVolatile*/, true/*ReadMem*/,
15561                                   false/*WriteMem*/);
15562
15563         // Make sure the newly-created LOAD is in the same position as Ld in
15564         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15565         // and update uses of Ld's output chain to use the TokenFactor.
15566         if (Ld->hasAnyUseOfValue(1)) {
15567           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15568                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15569           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15570           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15571                                  SDValue(ResNode.getNode(), 1));
15572         }
15573
15574         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15575       }
15576     }
15577
15578     // Emit a zeroed vector and insert the desired subvector on its
15579     // first half.
15580     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15581     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15582     return DCI.CombineTo(N, InsV);
15583   }
15584
15585   //===--------------------------------------------------------------------===//
15586   // Combine some shuffles into subvector extracts and inserts:
15587   //
15588
15589   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15590   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15591     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15592     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15593     return DCI.CombineTo(N, InsV);
15594   }
15595
15596   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15597   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15598     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15599     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15600     return DCI.CombineTo(N, InsV);
15601   }
15602
15603   return SDValue();
15604 }
15605
15606 /// PerformShuffleCombine - Performs several different shuffle combines.
15607 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15608                                      TargetLowering::DAGCombinerInfo &DCI,
15609                                      const X86Subtarget *Subtarget) {
15610   SDLoc dl(N);
15611   EVT VT = N->getValueType(0);
15612
15613   // Don't create instructions with illegal types after legalize types has run.
15614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15615   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15616     return SDValue();
15617
15618   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15619   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15620       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15621     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15622
15623   // Only handle 128 wide vector from here on.
15624   if (!VT.is128BitVector())
15625     return SDValue();
15626
15627   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15628   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15629   // consecutive, non-overlapping, and in the right order.
15630   SmallVector<SDValue, 16> Elts;
15631   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15632     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15633
15634   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15635 }
15636
15637 /// PerformTruncateCombine - Converts truncate operation to
15638 /// a sequence of vector shuffle operations.
15639 /// It is possible when we truncate 256-bit vector to 128-bit vector
15640 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15641                                       TargetLowering::DAGCombinerInfo &DCI,
15642                                       const X86Subtarget *Subtarget)  {
15643   return SDValue();
15644 }
15645
15646 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15647 /// specific shuffle of a load can be folded into a single element load.
15648 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15649 /// shuffles have been customed lowered so we need to handle those here.
15650 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15651                                          TargetLowering::DAGCombinerInfo &DCI) {
15652   if (DCI.isBeforeLegalizeOps())
15653     return SDValue();
15654
15655   SDValue InVec = N->getOperand(0);
15656   SDValue EltNo = N->getOperand(1);
15657
15658   if (!isa<ConstantSDNode>(EltNo))
15659     return SDValue();
15660
15661   EVT VT = InVec.getValueType();
15662
15663   bool HasShuffleIntoBitcast = false;
15664   if (InVec.getOpcode() == ISD::BITCAST) {
15665     // Don't duplicate a load with other uses.
15666     if (!InVec.hasOneUse())
15667       return SDValue();
15668     EVT BCVT = InVec.getOperand(0).getValueType();
15669     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15670       return SDValue();
15671     InVec = InVec.getOperand(0);
15672     HasShuffleIntoBitcast = true;
15673   }
15674
15675   if (!isTargetShuffle(InVec.getOpcode()))
15676     return SDValue();
15677
15678   // Don't duplicate a load with other uses.
15679   if (!InVec.hasOneUse())
15680     return SDValue();
15681
15682   SmallVector<int, 16> ShuffleMask;
15683   bool UnaryShuffle;
15684   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15685                             UnaryShuffle))
15686     return SDValue();
15687
15688   // Select the input vector, guarding against out of range extract vector.
15689   unsigned NumElems = VT.getVectorNumElements();
15690   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15691   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15692   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15693                                          : InVec.getOperand(1);
15694
15695   // If inputs to shuffle are the same for both ops, then allow 2 uses
15696   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15697
15698   if (LdNode.getOpcode() == ISD::BITCAST) {
15699     // Don't duplicate a load with other uses.
15700     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15701       return SDValue();
15702
15703     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15704     LdNode = LdNode.getOperand(0);
15705   }
15706
15707   if (!ISD::isNormalLoad(LdNode.getNode()))
15708     return SDValue();
15709
15710   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15711
15712   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15713     return SDValue();
15714
15715   if (HasShuffleIntoBitcast) {
15716     // If there's a bitcast before the shuffle, check if the load type and
15717     // alignment is valid.
15718     unsigned Align = LN0->getAlignment();
15719     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15720     unsigned NewAlign = TLI.getDataLayout()->
15721       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15722
15723     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15724       return SDValue();
15725   }
15726
15727   // All checks match so transform back to vector_shuffle so that DAG combiner
15728   // can finish the job
15729   SDLoc dl(N);
15730
15731   // Create shuffle node taking into account the case that its a unary shuffle
15732   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15733   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15734                                  InVec.getOperand(0), Shuffle,
15735                                  &ShuffleMask[0]);
15736   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15737   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15738                      EltNo);
15739 }
15740
15741 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15742 /// generation and convert it from being a bunch of shuffles and extracts
15743 /// to a simple store and scalar loads to extract the elements.
15744 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15745                                          TargetLowering::DAGCombinerInfo &DCI) {
15746   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15747   if (NewOp.getNode())
15748     return NewOp;
15749
15750   SDValue InputVector = N->getOperand(0);
15751   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15752   // from mmx to v2i32 has a single usage.
15753   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15754       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15755       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15756     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15757                        N->getValueType(0),
15758                        InputVector.getNode()->getOperand(0));
15759
15760   // Only operate on vectors of 4 elements, where the alternative shuffling
15761   // gets to be more expensive.
15762   if (InputVector.getValueType() != MVT::v4i32)
15763     return SDValue();
15764
15765   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15766   // single use which is a sign-extend or zero-extend, and all elements are
15767   // used.
15768   SmallVector<SDNode *, 4> Uses;
15769   unsigned ExtractedElements = 0;
15770   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15771        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15772     if (UI.getUse().getResNo() != InputVector.getResNo())
15773       return SDValue();
15774
15775     SDNode *Extract = *UI;
15776     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15777       return SDValue();
15778
15779     if (Extract->getValueType(0) != MVT::i32)
15780       return SDValue();
15781     if (!Extract->hasOneUse())
15782       return SDValue();
15783     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15784         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15785       return SDValue();
15786     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15787       return SDValue();
15788
15789     // Record which element was extracted.
15790     ExtractedElements |=
15791       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15792
15793     Uses.push_back(Extract);
15794   }
15795
15796   // If not all the elements were used, this may not be worthwhile.
15797   if (ExtractedElements != 15)
15798     return SDValue();
15799
15800   // Ok, we've now decided to do the transformation.
15801   SDLoc dl(InputVector);
15802
15803   // Store the value to a temporary stack slot.
15804   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15805   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15806                             MachinePointerInfo(), false, false, 0);
15807
15808   // Replace each use (extract) with a load of the appropriate element.
15809   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15810        UE = Uses.end(); UI != UE; ++UI) {
15811     SDNode *Extract = *UI;
15812
15813     // cOMpute the element's address.
15814     SDValue Idx = Extract->getOperand(1);
15815     unsigned EltSize =
15816         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15817     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15818     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15819     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15820
15821     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15822                                      StackPtr, OffsetVal);
15823
15824     // Load the scalar.
15825     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15826                                      ScalarAddr, MachinePointerInfo(),
15827                                      false, false, false, 0);
15828
15829     // Replace the exact with the load.
15830     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15831   }
15832
15833   // The replacement was made in place; don't return anything.
15834   return SDValue();
15835 }
15836
15837 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15838 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15839                                    SDValue RHS, SelectionDAG &DAG,
15840                                    const X86Subtarget *Subtarget) {
15841   if (!VT.isVector())
15842     return 0;
15843
15844   switch (VT.getSimpleVT().SimpleTy) {
15845   default: return 0;
15846   case MVT::v32i8:
15847   case MVT::v16i16:
15848   case MVT::v8i32:
15849     if (!Subtarget->hasAVX2())
15850       return 0;
15851   case MVT::v16i8:
15852   case MVT::v8i16:
15853   case MVT::v4i32:
15854     if (!Subtarget->hasSSE2())
15855       return 0;
15856   }
15857
15858   // SSE2 has only a small subset of the operations.
15859   bool hasUnsigned = Subtarget->hasSSE41() ||
15860                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15861   bool hasSigned = Subtarget->hasSSE41() ||
15862                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15863
15864   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15865
15866   // Check for x CC y ? x : y.
15867   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15868       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15869     switch (CC) {
15870     default: break;
15871     case ISD::SETULT:
15872     case ISD::SETULE:
15873       return hasUnsigned ? X86ISD::UMIN : 0;
15874     case ISD::SETUGT:
15875     case ISD::SETUGE:
15876       return hasUnsigned ? X86ISD::UMAX : 0;
15877     case ISD::SETLT:
15878     case ISD::SETLE:
15879       return hasSigned ? X86ISD::SMIN : 0;
15880     case ISD::SETGT:
15881     case ISD::SETGE:
15882       return hasSigned ? X86ISD::SMAX : 0;
15883     }
15884   // Check for x CC y ? y : x -- a min/max with reversed arms.
15885   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15886              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15887     switch (CC) {
15888     default: break;
15889     case ISD::SETULT:
15890     case ISD::SETULE:
15891       return hasUnsigned ? X86ISD::UMAX : 0;
15892     case ISD::SETUGT:
15893     case ISD::SETUGE:
15894       return hasUnsigned ? X86ISD::UMIN : 0;
15895     case ISD::SETLT:
15896     case ISD::SETLE:
15897       return hasSigned ? X86ISD::SMAX : 0;
15898     case ISD::SETGT:
15899     case ISD::SETGE:
15900       return hasSigned ? X86ISD::SMIN : 0;
15901     }
15902   }
15903
15904   return 0;
15905 }
15906
15907 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15908 /// nodes.
15909 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15910                                     TargetLowering::DAGCombinerInfo &DCI,
15911                                     const X86Subtarget *Subtarget) {
15912   SDLoc DL(N);
15913   SDValue Cond = N->getOperand(0);
15914   // Get the LHS/RHS of the select.
15915   SDValue LHS = N->getOperand(1);
15916   SDValue RHS = N->getOperand(2);
15917   EVT VT = LHS.getValueType();
15918
15919   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15920   // instructions match the semantics of the common C idiom x<y?x:y but not
15921   // x<=y?x:y, because of how they handle negative zero (which can be
15922   // ignored in unsafe-math mode).
15923   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15924       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15925       (Subtarget->hasSSE2() ||
15926        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15927     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15928
15929     unsigned Opcode = 0;
15930     // Check for x CC y ? x : y.
15931     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15932         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15933       switch (CC) {
15934       default: break;
15935       case ISD::SETULT:
15936         // Converting this to a min would handle NaNs incorrectly, and swapping
15937         // the operands would cause it to handle comparisons between positive
15938         // and negative zero incorrectly.
15939         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15940           if (!DAG.getTarget().Options.UnsafeFPMath &&
15941               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15942             break;
15943           std::swap(LHS, RHS);
15944         }
15945         Opcode = X86ISD::FMIN;
15946         break;
15947       case ISD::SETOLE:
15948         // Converting this to a min would handle comparisons between positive
15949         // and negative zero incorrectly.
15950         if (!DAG.getTarget().Options.UnsafeFPMath &&
15951             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15952           break;
15953         Opcode = X86ISD::FMIN;
15954         break;
15955       case ISD::SETULE:
15956         // Converting this to a min would handle both negative zeros and NaNs
15957         // incorrectly, but we can swap the operands to fix both.
15958         std::swap(LHS, RHS);
15959       case ISD::SETOLT:
15960       case ISD::SETLT:
15961       case ISD::SETLE:
15962         Opcode = X86ISD::FMIN;
15963         break;
15964
15965       case ISD::SETOGE:
15966         // Converting this to a max would handle comparisons between positive
15967         // and negative zero incorrectly.
15968         if (!DAG.getTarget().Options.UnsafeFPMath &&
15969             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15970           break;
15971         Opcode = X86ISD::FMAX;
15972         break;
15973       case ISD::SETUGT:
15974         // Converting this to a max would handle NaNs incorrectly, and swapping
15975         // the operands would cause it to handle comparisons between positive
15976         // and negative zero incorrectly.
15977         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15978           if (!DAG.getTarget().Options.UnsafeFPMath &&
15979               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15980             break;
15981           std::swap(LHS, RHS);
15982         }
15983         Opcode = X86ISD::FMAX;
15984         break;
15985       case ISD::SETUGE:
15986         // Converting this to a max would handle both negative zeros and NaNs
15987         // incorrectly, but we can swap the operands to fix both.
15988         std::swap(LHS, RHS);
15989       case ISD::SETOGT:
15990       case ISD::SETGT:
15991       case ISD::SETGE:
15992         Opcode = X86ISD::FMAX;
15993         break;
15994       }
15995     // Check for x CC y ? y : x -- a min/max with reversed arms.
15996     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15997                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15998       switch (CC) {
15999       default: break;
16000       case ISD::SETOGE:
16001         // Converting this to a min would handle comparisons between positive
16002         // and negative zero incorrectly, and swapping the operands would
16003         // cause it to handle NaNs incorrectly.
16004         if (!DAG.getTarget().Options.UnsafeFPMath &&
16005             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16006           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16007             break;
16008           std::swap(LHS, RHS);
16009         }
16010         Opcode = X86ISD::FMIN;
16011         break;
16012       case ISD::SETUGT:
16013         // Converting this to a min would handle NaNs incorrectly.
16014         if (!DAG.getTarget().Options.UnsafeFPMath &&
16015             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16016           break;
16017         Opcode = X86ISD::FMIN;
16018         break;
16019       case ISD::SETUGE:
16020         // Converting this to a min would handle both negative zeros and NaNs
16021         // incorrectly, but we can swap the operands to fix both.
16022         std::swap(LHS, RHS);
16023       case ISD::SETOGT:
16024       case ISD::SETGT:
16025       case ISD::SETGE:
16026         Opcode = X86ISD::FMIN;
16027         break;
16028
16029       case ISD::SETULT:
16030         // Converting this to a max would handle NaNs incorrectly.
16031         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16032           break;
16033         Opcode = X86ISD::FMAX;
16034         break;
16035       case ISD::SETOLE:
16036         // Converting this to a max would handle comparisons between positive
16037         // and negative zero incorrectly, and swapping the operands would
16038         // cause it to handle NaNs incorrectly.
16039         if (!DAG.getTarget().Options.UnsafeFPMath &&
16040             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16041           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16042             break;
16043           std::swap(LHS, RHS);
16044         }
16045         Opcode = X86ISD::FMAX;
16046         break;
16047       case ISD::SETULE:
16048         // Converting this to a max would handle both negative zeros and NaNs
16049         // incorrectly, but we can swap the operands to fix both.
16050         std::swap(LHS, RHS);
16051       case ISD::SETOLT:
16052       case ISD::SETLT:
16053       case ISD::SETLE:
16054         Opcode = X86ISD::FMAX;
16055         break;
16056       }
16057     }
16058
16059     if (Opcode)
16060       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16061   }
16062
16063   // If this is a select between two integer constants, try to do some
16064   // optimizations.
16065   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16066     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16067       // Don't do this for crazy integer types.
16068       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16069         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16070         // so that TrueC (the true value) is larger than FalseC.
16071         bool NeedsCondInvert = false;
16072
16073         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16074             // Efficiently invertible.
16075             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16076              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16077               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16078           NeedsCondInvert = true;
16079           std::swap(TrueC, FalseC);
16080         }
16081
16082         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16083         if (FalseC->getAPIntValue() == 0 &&
16084             TrueC->getAPIntValue().isPowerOf2()) {
16085           if (NeedsCondInvert) // Invert the condition if needed.
16086             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16087                                DAG.getConstant(1, Cond.getValueType()));
16088
16089           // Zero extend the condition if needed.
16090           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16091
16092           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16093           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16094                              DAG.getConstant(ShAmt, MVT::i8));
16095         }
16096
16097         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16098         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16099           if (NeedsCondInvert) // Invert the condition if needed.
16100             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16101                                DAG.getConstant(1, Cond.getValueType()));
16102
16103           // Zero extend the condition if needed.
16104           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16105                              FalseC->getValueType(0), Cond);
16106           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16107                              SDValue(FalseC, 0));
16108         }
16109
16110         // Optimize cases that will turn into an LEA instruction.  This requires
16111         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16112         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16113           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16114           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16115
16116           bool isFastMultiplier = false;
16117           if (Diff < 10) {
16118             switch ((unsigned char)Diff) {
16119               default: break;
16120               case 1:  // result = add base, cond
16121               case 2:  // result = lea base(    , cond*2)
16122               case 3:  // result = lea base(cond, cond*2)
16123               case 4:  // result = lea base(    , cond*4)
16124               case 5:  // result = lea base(cond, cond*4)
16125               case 8:  // result = lea base(    , cond*8)
16126               case 9:  // result = lea base(cond, cond*8)
16127                 isFastMultiplier = true;
16128                 break;
16129             }
16130           }
16131
16132           if (isFastMultiplier) {
16133             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16134             if (NeedsCondInvert) // Invert the condition if needed.
16135               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16136                                  DAG.getConstant(1, Cond.getValueType()));
16137
16138             // Zero extend the condition if needed.
16139             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16140                                Cond);
16141             // Scale the condition by the difference.
16142             if (Diff != 1)
16143               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16144                                  DAG.getConstant(Diff, Cond.getValueType()));
16145
16146             // Add the base if non-zero.
16147             if (FalseC->getAPIntValue() != 0)
16148               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16149                                  SDValue(FalseC, 0));
16150             return Cond;
16151           }
16152         }
16153       }
16154   }
16155
16156   // Canonicalize max and min:
16157   // (x > y) ? x : y -> (x >= y) ? x : y
16158   // (x < y) ? x : y -> (x <= y) ? x : y
16159   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16160   // the need for an extra compare
16161   // against zero. e.g.
16162   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16163   // subl   %esi, %edi
16164   // testl  %edi, %edi
16165   // movl   $0, %eax
16166   // cmovgl %edi, %eax
16167   // =>
16168   // xorl   %eax, %eax
16169   // subl   %esi, $edi
16170   // cmovsl %eax, %edi
16171   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16172       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16173       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16174     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16175     switch (CC) {
16176     default: break;
16177     case ISD::SETLT:
16178     case ISD::SETGT: {
16179       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16180       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16181                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16182       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16183     }
16184     }
16185   }
16186
16187   // Match VSELECTs into subs with unsigned saturation.
16188   if (!DCI.isBeforeLegalize() &&
16189       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16190       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16191       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16192        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16193     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16194
16195     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16196     // left side invert the predicate to simplify logic below.
16197     SDValue Other;
16198     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16199       Other = RHS;
16200       CC = ISD::getSetCCInverse(CC, true);
16201     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16202       Other = LHS;
16203     }
16204
16205     if (Other.getNode() && Other->getNumOperands() == 2 &&
16206         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16207       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16208       SDValue CondRHS = Cond->getOperand(1);
16209
16210       // Look for a general sub with unsigned saturation first.
16211       // x >= y ? x-y : 0 --> subus x, y
16212       // x >  y ? x-y : 0 --> subus x, y
16213       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16214           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16215         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16216
16217       // If the RHS is a constant we have to reverse the const canonicalization.
16218       // x > C-1 ? x+-C : 0 --> subus x, C
16219       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16220           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16221         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16222         if (CondRHS.getConstantOperandVal(0) == -A-1)
16223           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16224                              DAG.getConstant(-A, VT));
16225       }
16226
16227       // Another special case: If C was a sign bit, the sub has been
16228       // canonicalized into a xor.
16229       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16230       //        it's safe to decanonicalize the xor?
16231       // x s< 0 ? x^C : 0 --> subus x, C
16232       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16233           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16234           isSplatVector(OpRHS.getNode())) {
16235         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16236         if (A.isSignBit())
16237           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16238       }
16239     }
16240   }
16241
16242   // Try to match a min/max vector operation.
16243   if (!DCI.isBeforeLegalize() &&
16244       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16245     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16246       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16247
16248   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16249   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16250       Cond.getOpcode() == ISD::SETCC) {
16251
16252     assert(Cond.getValueType().isVector() &&
16253            "vector select expects a vector selector!");
16254
16255     EVT IntVT = Cond.getValueType();
16256     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16257     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16258
16259     if (!TValIsAllOnes && !FValIsAllZeros) {
16260       // Try invert the condition if true value is not all 1s and false value
16261       // is not all 0s.
16262       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16263       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16264
16265       if (TValIsAllZeros || FValIsAllOnes) {
16266         SDValue CC = Cond.getOperand(2);
16267         ISD::CondCode NewCC =
16268           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16269                                Cond.getOperand(0).getValueType().isInteger());
16270         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16271         std::swap(LHS, RHS);
16272         TValIsAllOnes = FValIsAllOnes;
16273         FValIsAllZeros = TValIsAllZeros;
16274       }
16275     }
16276
16277     if (TValIsAllOnes || FValIsAllZeros) {
16278       SDValue Ret;
16279
16280       if (TValIsAllOnes && FValIsAllZeros)
16281         Ret = Cond;
16282       else if (TValIsAllOnes)
16283         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16284                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16285       else if (FValIsAllZeros)
16286         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16287                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16288
16289       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16290     }
16291   }
16292
16293   // If we know that this node is legal then we know that it is going to be
16294   // matched by one of the SSE/AVX BLEND instructions. These instructions only
16295   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16296   // to simplify previous instructions.
16297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16298   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16299       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16300     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16301
16302     // Don't optimize vector selects that map to mask-registers.
16303     if (BitWidth == 1)
16304       return SDValue();
16305
16306     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16307     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16308
16309     APInt KnownZero, KnownOne;
16310     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16311                                           DCI.isBeforeLegalizeOps());
16312     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16313         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16314       DCI.CommitTargetLoweringOpt(TLO);
16315   }
16316
16317   return SDValue();
16318 }
16319
16320 // Check whether a boolean test is testing a boolean value generated by
16321 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16322 // code.
16323 //
16324 // Simplify the following patterns:
16325 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16326 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16327 // to (Op EFLAGS Cond)
16328 //
16329 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16330 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16331 // to (Op EFLAGS !Cond)
16332 //
16333 // where Op could be BRCOND or CMOV.
16334 //
16335 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16336   // Quit if not CMP and SUB with its value result used.
16337   if (Cmp.getOpcode() != X86ISD::CMP &&
16338       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16339       return SDValue();
16340
16341   // Quit if not used as a boolean value.
16342   if (CC != X86::COND_E && CC != X86::COND_NE)
16343     return SDValue();
16344
16345   // Check CMP operands. One of them should be 0 or 1 and the other should be
16346   // an SetCC or extended from it.
16347   SDValue Op1 = Cmp.getOperand(0);
16348   SDValue Op2 = Cmp.getOperand(1);
16349
16350   SDValue SetCC;
16351   const ConstantSDNode* C = 0;
16352   bool needOppositeCond = (CC == X86::COND_E);
16353   bool checkAgainstTrue = false; // Is it a comparison against 1?
16354
16355   if ((C = dyn_cast<ConstantSDNode>(Op1)))
16356     SetCC = Op2;
16357   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16358     SetCC = Op1;
16359   else // Quit if all operands are not constants.
16360     return SDValue();
16361
16362   if (C->getZExtValue() == 1) {
16363     needOppositeCond = !needOppositeCond;
16364     checkAgainstTrue = true;
16365   } else if (C->getZExtValue() != 0)
16366     // Quit if the constant is neither 0 or 1.
16367     return SDValue();
16368
16369   bool truncatedToBoolWithAnd = false;
16370   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16371   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16372          SetCC.getOpcode() == ISD::TRUNCATE ||
16373          SetCC.getOpcode() == ISD::AND) {
16374     if (SetCC.getOpcode() == ISD::AND) {
16375       int OpIdx = -1;
16376       ConstantSDNode *CS;
16377       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16378           CS->getZExtValue() == 1)
16379         OpIdx = 1;
16380       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16381           CS->getZExtValue() == 1)
16382         OpIdx = 0;
16383       if (OpIdx == -1)
16384         break;
16385       SetCC = SetCC.getOperand(OpIdx);
16386       truncatedToBoolWithAnd = true;
16387     } else
16388       SetCC = SetCC.getOperand(0);
16389   }
16390
16391   switch (SetCC.getOpcode()) {
16392   case X86ISD::SETCC_CARRY:
16393     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16394     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16395     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16396     // truncated to i1 using 'and'.
16397     if (checkAgainstTrue && !truncatedToBoolWithAnd)
16398       break;
16399     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16400            "Invalid use of SETCC_CARRY!");
16401     // FALL THROUGH
16402   case X86ISD::SETCC:
16403     // Set the condition code or opposite one if necessary.
16404     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16405     if (needOppositeCond)
16406       CC = X86::GetOppositeBranchCondition(CC);
16407     return SetCC.getOperand(1);
16408   case X86ISD::CMOV: {
16409     // Check whether false/true value has canonical one, i.e. 0 or 1.
16410     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16411     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16412     // Quit if true value is not a constant.
16413     if (!TVal)
16414       return SDValue();
16415     // Quit if false value is not a constant.
16416     if (!FVal) {
16417       SDValue Op = SetCC.getOperand(0);
16418       // Skip 'zext' or 'trunc' node.
16419       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16420           Op.getOpcode() == ISD::TRUNCATE)
16421         Op = Op.getOperand(0);
16422       // A special case for rdrand/rdseed, where 0 is set if false cond is
16423       // found.
16424       if ((Op.getOpcode() != X86ISD::RDRAND &&
16425            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16426         return SDValue();
16427     }
16428     // Quit if false value is not the constant 0 or 1.
16429     bool FValIsFalse = true;
16430     if (FVal && FVal->getZExtValue() != 0) {
16431       if (FVal->getZExtValue() != 1)
16432         return SDValue();
16433       // If FVal is 1, opposite cond is needed.
16434       needOppositeCond = !needOppositeCond;
16435       FValIsFalse = false;
16436     }
16437     // Quit if TVal is not the constant opposite of FVal.
16438     if (FValIsFalse && TVal->getZExtValue() != 1)
16439       return SDValue();
16440     if (!FValIsFalse && TVal->getZExtValue() != 0)
16441       return SDValue();
16442     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16443     if (needOppositeCond)
16444       CC = X86::GetOppositeBranchCondition(CC);
16445     return SetCC.getOperand(3);
16446   }
16447   }
16448
16449   return SDValue();
16450 }
16451
16452 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16453 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16454                                   TargetLowering::DAGCombinerInfo &DCI,
16455                                   const X86Subtarget *Subtarget) {
16456   SDLoc DL(N);
16457
16458   // If the flag operand isn't dead, don't touch this CMOV.
16459   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16460     return SDValue();
16461
16462   SDValue FalseOp = N->getOperand(0);
16463   SDValue TrueOp = N->getOperand(1);
16464   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16465   SDValue Cond = N->getOperand(3);
16466
16467   if (CC == X86::COND_E || CC == X86::COND_NE) {
16468     switch (Cond.getOpcode()) {
16469     default: break;
16470     case X86ISD::BSR:
16471     case X86ISD::BSF:
16472       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16473       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16474         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16475     }
16476   }
16477
16478   SDValue Flags;
16479
16480   Flags = checkBoolTestSetCCCombine(Cond, CC);
16481   if (Flags.getNode() &&
16482       // Extra check as FCMOV only supports a subset of X86 cond.
16483       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16484     SDValue Ops[] = { FalseOp, TrueOp,
16485                       DAG.getConstant(CC, MVT::i8), Flags };
16486     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16487                        Ops, array_lengthof(Ops));
16488   }
16489
16490   // If this is a select between two integer constants, try to do some
16491   // optimizations.  Note that the operands are ordered the opposite of SELECT
16492   // operands.
16493   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16494     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16495       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16496       // larger than FalseC (the false value).
16497       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16498         CC = X86::GetOppositeBranchCondition(CC);
16499         std::swap(TrueC, FalseC);
16500         std::swap(TrueOp, FalseOp);
16501       }
16502
16503       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16504       // This is efficient for any integer data type (including i8/i16) and
16505       // shift amount.
16506       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16507         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16508                            DAG.getConstant(CC, MVT::i8), Cond);
16509
16510         // Zero extend the condition if needed.
16511         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16512
16513         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16514         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16515                            DAG.getConstant(ShAmt, MVT::i8));
16516         if (N->getNumValues() == 2)  // Dead flag value?
16517           return DCI.CombineTo(N, Cond, SDValue());
16518         return Cond;
16519       }
16520
16521       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16522       // for any integer data type, including i8/i16.
16523       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16524         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16525                            DAG.getConstant(CC, MVT::i8), Cond);
16526
16527         // Zero extend the condition if needed.
16528         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16529                            FalseC->getValueType(0), Cond);
16530         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16531                            SDValue(FalseC, 0));
16532
16533         if (N->getNumValues() == 2)  // Dead flag value?
16534           return DCI.CombineTo(N, Cond, SDValue());
16535         return Cond;
16536       }
16537
16538       // Optimize cases that will turn into an LEA instruction.  This requires
16539       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16540       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16541         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16542         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16543
16544         bool isFastMultiplier = false;
16545         if (Diff < 10) {
16546           switch ((unsigned char)Diff) {
16547           default: break;
16548           case 1:  // result = add base, cond
16549           case 2:  // result = lea base(    , cond*2)
16550           case 3:  // result = lea base(cond, cond*2)
16551           case 4:  // result = lea base(    , cond*4)
16552           case 5:  // result = lea base(cond, cond*4)
16553           case 8:  // result = lea base(    , cond*8)
16554           case 9:  // result = lea base(cond, cond*8)
16555             isFastMultiplier = true;
16556             break;
16557           }
16558         }
16559
16560         if (isFastMultiplier) {
16561           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16562           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16563                              DAG.getConstant(CC, MVT::i8), Cond);
16564           // Zero extend the condition if needed.
16565           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16566                              Cond);
16567           // Scale the condition by the difference.
16568           if (Diff != 1)
16569             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16570                                DAG.getConstant(Diff, Cond.getValueType()));
16571
16572           // Add the base if non-zero.
16573           if (FalseC->getAPIntValue() != 0)
16574             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16575                                SDValue(FalseC, 0));
16576           if (N->getNumValues() == 2)  // Dead flag value?
16577             return DCI.CombineTo(N, Cond, SDValue());
16578           return Cond;
16579         }
16580       }
16581     }
16582   }
16583
16584   // Handle these cases:
16585   //   (select (x != c), e, c) -> select (x != c), e, x),
16586   //   (select (x == c), c, e) -> select (x == c), x, e)
16587   // where the c is an integer constant, and the "select" is the combination
16588   // of CMOV and CMP.
16589   //
16590   // The rationale for this change is that the conditional-move from a constant
16591   // needs two instructions, however, conditional-move from a register needs
16592   // only one instruction.
16593   //
16594   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16595   //  some instruction-combining opportunities. This opt needs to be
16596   //  postponed as late as possible.
16597   //
16598   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16599     // the DCI.xxxx conditions are provided to postpone the optimization as
16600     // late as possible.
16601
16602     ConstantSDNode *CmpAgainst = 0;
16603     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16604         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16605         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16606
16607       if (CC == X86::COND_NE &&
16608           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16609         CC = X86::GetOppositeBranchCondition(CC);
16610         std::swap(TrueOp, FalseOp);
16611       }
16612
16613       if (CC == X86::COND_E &&
16614           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16615         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16616                           DAG.getConstant(CC, MVT::i8), Cond };
16617         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16618                            array_lengthof(Ops));
16619       }
16620     }
16621   }
16622
16623   return SDValue();
16624 }
16625
16626 /// PerformMulCombine - Optimize a single multiply with constant into two
16627 /// in order to implement it with two cheaper instructions, e.g.
16628 /// LEA + SHL, LEA + LEA.
16629 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16630                                  TargetLowering::DAGCombinerInfo &DCI) {
16631   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16632     return SDValue();
16633
16634   EVT VT = N->getValueType(0);
16635   if (VT != MVT::i64)
16636     return SDValue();
16637
16638   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16639   if (!C)
16640     return SDValue();
16641   uint64_t MulAmt = C->getZExtValue();
16642   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16643     return SDValue();
16644
16645   uint64_t MulAmt1 = 0;
16646   uint64_t MulAmt2 = 0;
16647   if ((MulAmt % 9) == 0) {
16648     MulAmt1 = 9;
16649     MulAmt2 = MulAmt / 9;
16650   } else if ((MulAmt % 5) == 0) {
16651     MulAmt1 = 5;
16652     MulAmt2 = MulAmt / 5;
16653   } else if ((MulAmt % 3) == 0) {
16654     MulAmt1 = 3;
16655     MulAmt2 = MulAmt / 3;
16656   }
16657   if (MulAmt2 &&
16658       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16659     SDLoc DL(N);
16660
16661     if (isPowerOf2_64(MulAmt2) &&
16662         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16663       // If second multiplifer is pow2, issue it first. We want the multiply by
16664       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16665       // is an add.
16666       std::swap(MulAmt1, MulAmt2);
16667
16668     SDValue NewMul;
16669     if (isPowerOf2_64(MulAmt1))
16670       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16671                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16672     else
16673       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16674                            DAG.getConstant(MulAmt1, VT));
16675
16676     if (isPowerOf2_64(MulAmt2))
16677       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16678                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16679     else
16680       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16681                            DAG.getConstant(MulAmt2, VT));
16682
16683     // Do not add new nodes to DAG combiner worklist.
16684     DCI.CombineTo(N, NewMul, false);
16685   }
16686   return SDValue();
16687 }
16688
16689 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16690   SDValue N0 = N->getOperand(0);
16691   SDValue N1 = N->getOperand(1);
16692   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16693   EVT VT = N0.getValueType();
16694
16695   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16696   // since the result of setcc_c is all zero's or all ones.
16697   if (VT.isInteger() && !VT.isVector() &&
16698       N1C && N0.getOpcode() == ISD::AND &&
16699       N0.getOperand(1).getOpcode() == ISD::Constant) {
16700     SDValue N00 = N0.getOperand(0);
16701     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16702         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16703           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16704          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16705       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16706       APInt ShAmt = N1C->getAPIntValue();
16707       Mask = Mask.shl(ShAmt);
16708       if (Mask != 0)
16709         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16710                            N00, DAG.getConstant(Mask, VT));
16711     }
16712   }
16713
16714   // Hardware support for vector shifts is sparse which makes us scalarize the
16715   // vector operations in many cases. Also, on sandybridge ADD is faster than
16716   // shl.
16717   // (shl V, 1) -> add V,V
16718   if (isSplatVector(N1.getNode())) {
16719     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16720     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16721     // We shift all of the values by one. In many cases we do not have
16722     // hardware support for this operation. This is better expressed as an ADD
16723     // of two values.
16724     if (N1C && (1 == N1C->getZExtValue())) {
16725       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16726     }
16727   }
16728
16729   return SDValue();
16730 }
16731
16732 /// \brief Returns a vector of 0s if the node in input is a vector logical
16733 /// shift by a constant amount which is known to be bigger than or equal 
16734 /// to the vector element size in bits.
16735 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16736                                       const X86Subtarget *Subtarget) {
16737   EVT VT = N->getValueType(0);
16738
16739   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16740       (!Subtarget->hasInt256() ||
16741        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16742     return SDValue();
16743
16744   SDValue Amt = N->getOperand(1);
16745   SDLoc DL(N);
16746   if (isSplatVector(Amt.getNode())) {
16747     SDValue SclrAmt = Amt->getOperand(0);
16748     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16749       APInt ShiftAmt = C->getAPIntValue();
16750       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16751
16752       // SSE2/AVX2 logical shifts always return a vector of 0s
16753       // if the shift amount is bigger than or equal to 
16754       // the element size. The constant shift amount will be
16755       // encoded as a 8-bit immediate.
16756       if (ShiftAmt.trunc(8).uge(MaxAmount))
16757         return getZeroVector(VT, Subtarget, DAG, DL);
16758     }
16759   }
16760
16761   return SDValue();
16762 }
16763
16764 /// PerformShiftCombine - Combine shifts.
16765 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16766                                    TargetLowering::DAGCombinerInfo &DCI,
16767                                    const X86Subtarget *Subtarget) {
16768   if (N->getOpcode() == ISD::SHL) {
16769     SDValue V = PerformSHLCombine(N, DAG);
16770     if (V.getNode()) return V;
16771   }
16772
16773   if (N->getOpcode() != ISD::SRA) {
16774     // Try to fold this logical shift into a zero vector.
16775     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16776     if (V.getNode()) return V;
16777   }
16778
16779   return SDValue();
16780 }
16781
16782 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16783 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16784 // and friends.  Likewise for OR -> CMPNEQSS.
16785 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16786                             TargetLowering::DAGCombinerInfo &DCI,
16787                             const X86Subtarget *Subtarget) {
16788   unsigned opcode;
16789
16790   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16791   // we're requiring SSE2 for both.
16792   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16793     SDValue N0 = N->getOperand(0);
16794     SDValue N1 = N->getOperand(1);
16795     SDValue CMP0 = N0->getOperand(1);
16796     SDValue CMP1 = N1->getOperand(1);
16797     SDLoc DL(N);
16798
16799     // The SETCCs should both refer to the same CMP.
16800     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16801       return SDValue();
16802
16803     SDValue CMP00 = CMP0->getOperand(0);
16804     SDValue CMP01 = CMP0->getOperand(1);
16805     EVT     VT    = CMP00.getValueType();
16806
16807     if (VT == MVT::f32 || VT == MVT::f64) {
16808       bool ExpectingFlags = false;
16809       // Check for any users that want flags:
16810       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16811            !ExpectingFlags && UI != UE; ++UI)
16812         switch (UI->getOpcode()) {
16813         default:
16814         case ISD::BR_CC:
16815         case ISD::BRCOND:
16816         case ISD::SELECT:
16817           ExpectingFlags = true;
16818           break;
16819         case ISD::CopyToReg:
16820         case ISD::SIGN_EXTEND:
16821         case ISD::ZERO_EXTEND:
16822         case ISD::ANY_EXTEND:
16823           break;
16824         }
16825
16826       if (!ExpectingFlags) {
16827         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16828         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16829
16830         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16831           X86::CondCode tmp = cc0;
16832           cc0 = cc1;
16833           cc1 = tmp;
16834         }
16835
16836         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16837             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16838           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16839           X86ISD::NodeType NTOperator = is64BitFP ?
16840             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16841           // FIXME: need symbolic constants for these magic numbers.
16842           // See X86ATTInstPrinter.cpp:printSSECC().
16843           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16844           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16845                                               DAG.getConstant(x86cc, MVT::i8));
16846           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16847                                               OnesOrZeroesF);
16848           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16849                                       DAG.getConstant(1, MVT::i32));
16850           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16851           return OneBitOfTruth;
16852         }
16853       }
16854     }
16855   }
16856   return SDValue();
16857 }
16858
16859 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16860 /// so it can be folded inside ANDNP.
16861 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16862   EVT VT = N->getValueType(0);
16863
16864   // Match direct AllOnes for 128 and 256-bit vectors
16865   if (ISD::isBuildVectorAllOnes(N))
16866     return true;
16867
16868   // Look through a bit convert.
16869   if (N->getOpcode() == ISD::BITCAST)
16870     N = N->getOperand(0).getNode();
16871
16872   // Sometimes the operand may come from a insert_subvector building a 256-bit
16873   // allones vector
16874   if (VT.is256BitVector() &&
16875       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16876     SDValue V1 = N->getOperand(0);
16877     SDValue V2 = N->getOperand(1);
16878
16879     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16880         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16881         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16882         ISD::isBuildVectorAllOnes(V2.getNode()))
16883       return true;
16884   }
16885
16886   return false;
16887 }
16888
16889 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16890 // register. In most cases we actually compare or select YMM-sized registers
16891 // and mixing the two types creates horrible code. This method optimizes
16892 // some of the transition sequences.
16893 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16894                                  TargetLowering::DAGCombinerInfo &DCI,
16895                                  const X86Subtarget *Subtarget) {
16896   EVT VT = N->getValueType(0);
16897   if (!VT.is256BitVector())
16898     return SDValue();
16899
16900   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16901           N->getOpcode() == ISD::ZERO_EXTEND ||
16902           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16903
16904   SDValue Narrow = N->getOperand(0);
16905   EVT NarrowVT = Narrow->getValueType(0);
16906   if (!NarrowVT.is128BitVector())
16907     return SDValue();
16908
16909   if (Narrow->getOpcode() != ISD::XOR &&
16910       Narrow->getOpcode() != ISD::AND &&
16911       Narrow->getOpcode() != ISD::OR)
16912     return SDValue();
16913
16914   SDValue N0  = Narrow->getOperand(0);
16915   SDValue N1  = Narrow->getOperand(1);
16916   SDLoc DL(Narrow);
16917
16918   // The Left side has to be a trunc.
16919   if (N0.getOpcode() != ISD::TRUNCATE)
16920     return SDValue();
16921
16922   // The type of the truncated inputs.
16923   EVT WideVT = N0->getOperand(0)->getValueType(0);
16924   if (WideVT != VT)
16925     return SDValue();
16926
16927   // The right side has to be a 'trunc' or a constant vector.
16928   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16929   bool RHSConst = (isSplatVector(N1.getNode()) &&
16930                    isa<ConstantSDNode>(N1->getOperand(0)));
16931   if (!RHSTrunc && !RHSConst)
16932     return SDValue();
16933
16934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16935
16936   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16937     return SDValue();
16938
16939   // Set N0 and N1 to hold the inputs to the new wide operation.
16940   N0 = N0->getOperand(0);
16941   if (RHSConst) {
16942     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16943                      N1->getOperand(0));
16944     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16945     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16946   } else if (RHSTrunc) {
16947     N1 = N1->getOperand(0);
16948   }
16949
16950   // Generate the wide operation.
16951   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16952   unsigned Opcode = N->getOpcode();
16953   switch (Opcode) {
16954   case ISD::ANY_EXTEND:
16955     return Op;
16956   case ISD::ZERO_EXTEND: {
16957     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16958     APInt Mask = APInt::getAllOnesValue(InBits);
16959     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16960     return DAG.getNode(ISD::AND, DL, VT,
16961                        Op, DAG.getConstant(Mask, VT));
16962   }
16963   case ISD::SIGN_EXTEND:
16964     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16965                        Op, DAG.getValueType(NarrowVT));
16966   default:
16967     llvm_unreachable("Unexpected opcode");
16968   }
16969 }
16970
16971 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16972                                  TargetLowering::DAGCombinerInfo &DCI,
16973                                  const X86Subtarget *Subtarget) {
16974   EVT VT = N->getValueType(0);
16975   if (DCI.isBeforeLegalizeOps())
16976     return SDValue();
16977
16978   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16979   if (R.getNode())
16980     return R;
16981
16982   // Create BLSI, and BLSR instructions
16983   // BLSI is X & (-X)
16984   // BLSR is X & (X-1)
16985   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16986     SDValue N0 = N->getOperand(0);
16987     SDValue N1 = N->getOperand(1);
16988     SDLoc DL(N);
16989
16990     // Check LHS for neg
16991     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16992         isZero(N0.getOperand(0)))
16993       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16994
16995     // Check RHS for neg
16996     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16997         isZero(N1.getOperand(0)))
16998       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16999
17000     // Check LHS for X-1
17001     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17002         isAllOnes(N0.getOperand(1)))
17003       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17004
17005     // Check RHS for X-1
17006     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17007         isAllOnes(N1.getOperand(1)))
17008       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17009
17010     return SDValue();
17011   }
17012
17013   // Want to form ANDNP nodes:
17014   // 1) In the hopes of then easily combining them with OR and AND nodes
17015   //    to form PBLEND/PSIGN.
17016   // 2) To match ANDN packed intrinsics
17017   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17018     return SDValue();
17019
17020   SDValue N0 = N->getOperand(0);
17021   SDValue N1 = N->getOperand(1);
17022   SDLoc DL(N);
17023
17024   // Check LHS for vnot
17025   if (N0.getOpcode() == ISD::XOR &&
17026       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17027       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17028     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17029
17030   // Check RHS for vnot
17031   if (N1.getOpcode() == ISD::XOR &&
17032       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17033       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17034     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17035
17036   return SDValue();
17037 }
17038
17039 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17040                                 TargetLowering::DAGCombinerInfo &DCI,
17041                                 const X86Subtarget *Subtarget) {
17042   EVT VT = N->getValueType(0);
17043   if (DCI.isBeforeLegalizeOps())
17044     return SDValue();
17045
17046   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17047   if (R.getNode())
17048     return R;
17049
17050   SDValue N0 = N->getOperand(0);
17051   SDValue N1 = N->getOperand(1);
17052
17053   // look for psign/blend
17054   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17055     if (!Subtarget->hasSSSE3() ||
17056         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17057       return SDValue();
17058
17059     // Canonicalize pandn to RHS
17060     if (N0.getOpcode() == X86ISD::ANDNP)
17061       std::swap(N0, N1);
17062     // or (and (m, y), (pandn m, x))
17063     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17064       SDValue Mask = N1.getOperand(0);
17065       SDValue X    = N1.getOperand(1);
17066       SDValue Y;
17067       if (N0.getOperand(0) == Mask)
17068         Y = N0.getOperand(1);
17069       if (N0.getOperand(1) == Mask)
17070         Y = N0.getOperand(0);
17071
17072       // Check to see if the mask appeared in both the AND and ANDNP and
17073       if (!Y.getNode())
17074         return SDValue();
17075
17076       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17077       // Look through mask bitcast.
17078       if (Mask.getOpcode() == ISD::BITCAST)
17079         Mask = Mask.getOperand(0);
17080       if (X.getOpcode() == ISD::BITCAST)
17081         X = X.getOperand(0);
17082       if (Y.getOpcode() == ISD::BITCAST)
17083         Y = Y.getOperand(0);
17084
17085       EVT MaskVT = Mask.getValueType();
17086
17087       // Validate that the Mask operand is a vector sra node.
17088       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17089       // there is no psrai.b
17090       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17091       unsigned SraAmt = ~0;
17092       if (Mask.getOpcode() == ISD::SRA) {
17093         SDValue Amt = Mask.getOperand(1);
17094         if (isSplatVector(Amt.getNode())) {
17095           SDValue SclrAmt = Amt->getOperand(0);
17096           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17097             SraAmt = C->getZExtValue();
17098         }
17099       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17100         SDValue SraC = Mask.getOperand(1);
17101         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
17102       }
17103       if ((SraAmt + 1) != EltBits)
17104         return SDValue();
17105
17106       SDLoc DL(N);
17107
17108       // Now we know we at least have a plendvb with the mask val.  See if
17109       // we can form a psignb/w/d.
17110       // psign = x.type == y.type == mask.type && y = sub(0, x);
17111       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17112           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17113           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17114         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17115                "Unsupported VT for PSIGN");
17116         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17117         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17118       }
17119       // PBLENDVB only available on SSE 4.1
17120       if (!Subtarget->hasSSE41())
17121         return SDValue();
17122
17123       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17124
17125       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17126       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17127       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17128       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17129       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17130     }
17131   }
17132
17133   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17134     return SDValue();
17135
17136   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17137   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17138     std::swap(N0, N1);
17139   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17140     return SDValue();
17141   if (!N0.hasOneUse() || !N1.hasOneUse())
17142     return SDValue();
17143
17144   SDValue ShAmt0 = N0.getOperand(1);
17145   if (ShAmt0.getValueType() != MVT::i8)
17146     return SDValue();
17147   SDValue ShAmt1 = N1.getOperand(1);
17148   if (ShAmt1.getValueType() != MVT::i8)
17149     return SDValue();
17150   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17151     ShAmt0 = ShAmt0.getOperand(0);
17152   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17153     ShAmt1 = ShAmt1.getOperand(0);
17154
17155   SDLoc DL(N);
17156   unsigned Opc = X86ISD::SHLD;
17157   SDValue Op0 = N0.getOperand(0);
17158   SDValue Op1 = N1.getOperand(0);
17159   if (ShAmt0.getOpcode() == ISD::SUB) {
17160     Opc = X86ISD::SHRD;
17161     std::swap(Op0, Op1);
17162     std::swap(ShAmt0, ShAmt1);
17163   }
17164
17165   unsigned Bits = VT.getSizeInBits();
17166   if (ShAmt1.getOpcode() == ISD::SUB) {
17167     SDValue Sum = ShAmt1.getOperand(0);
17168     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17169       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17170       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17171         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17172       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17173         return DAG.getNode(Opc, DL, VT,
17174                            Op0, Op1,
17175                            DAG.getNode(ISD::TRUNCATE, DL,
17176                                        MVT::i8, ShAmt0));
17177     }
17178   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17179     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17180     if (ShAmt0C &&
17181         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17182       return DAG.getNode(Opc, DL, VT,
17183                          N0.getOperand(0), N1.getOperand(0),
17184                          DAG.getNode(ISD::TRUNCATE, DL,
17185                                        MVT::i8, ShAmt0));
17186   }
17187
17188   return SDValue();
17189 }
17190
17191 // Generate NEG and CMOV for integer abs.
17192 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17193   EVT VT = N->getValueType(0);
17194
17195   // Since X86 does not have CMOV for 8-bit integer, we don't convert
17196   // 8-bit integer abs to NEG and CMOV.
17197   if (VT.isInteger() && VT.getSizeInBits() == 8)
17198     return SDValue();
17199
17200   SDValue N0 = N->getOperand(0);
17201   SDValue N1 = N->getOperand(1);
17202   SDLoc DL(N);
17203
17204   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17205   // and change it to SUB and CMOV.
17206   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17207       N0.getOpcode() == ISD::ADD &&
17208       N0.getOperand(1) == N1 &&
17209       N1.getOpcode() == ISD::SRA &&
17210       N1.getOperand(0) == N0.getOperand(0))
17211     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17212       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17213         // Generate SUB & CMOV.
17214         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17215                                   DAG.getConstant(0, VT), N0.getOperand(0));
17216
17217         SDValue Ops[] = { N0.getOperand(0), Neg,
17218                           DAG.getConstant(X86::COND_GE, MVT::i8),
17219                           SDValue(Neg.getNode(), 1) };
17220         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17221                            Ops, array_lengthof(Ops));
17222       }
17223   return SDValue();
17224 }
17225
17226 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17227 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17228                                  TargetLowering::DAGCombinerInfo &DCI,
17229                                  const X86Subtarget *Subtarget) {
17230   EVT VT = N->getValueType(0);
17231   if (DCI.isBeforeLegalizeOps())
17232     return SDValue();
17233
17234   if (Subtarget->hasCMov()) {
17235     SDValue RV = performIntegerAbsCombine(N, DAG);
17236     if (RV.getNode())
17237       return RV;
17238   }
17239
17240   // Try forming BMI if it is available.
17241   if (!Subtarget->hasBMI())
17242     return SDValue();
17243
17244   if (VT != MVT::i32 && VT != MVT::i64)
17245     return SDValue();
17246
17247   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17248
17249   // Create BLSMSK instructions by finding X ^ (X-1)
17250   SDValue N0 = N->getOperand(0);
17251   SDValue N1 = N->getOperand(1);
17252   SDLoc DL(N);
17253
17254   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17255       isAllOnes(N0.getOperand(1)))
17256     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17257
17258   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17259       isAllOnes(N1.getOperand(1)))
17260     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17261
17262   return SDValue();
17263 }
17264
17265 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17266 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17267                                   TargetLowering::DAGCombinerInfo &DCI,
17268                                   const X86Subtarget *Subtarget) {
17269   LoadSDNode *Ld = cast<LoadSDNode>(N);
17270   EVT RegVT = Ld->getValueType(0);
17271   EVT MemVT = Ld->getMemoryVT();
17272   SDLoc dl(Ld);
17273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17274   unsigned RegSz = RegVT.getSizeInBits();
17275
17276   // On Sandybridge unaligned 256bit loads are inefficient.
17277   ISD::LoadExtType Ext = Ld->getExtensionType();
17278   unsigned Alignment = Ld->getAlignment();
17279   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17280   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17281       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17282     unsigned NumElems = RegVT.getVectorNumElements();
17283     if (NumElems < 2)
17284       return SDValue();
17285
17286     SDValue Ptr = Ld->getBasePtr();
17287     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17288
17289     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17290                                   NumElems/2);
17291     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17292                                 Ld->getPointerInfo(), Ld->isVolatile(),
17293                                 Ld->isNonTemporal(), Ld->isInvariant(),
17294                                 Alignment);
17295     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17296     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17297                                 Ld->getPointerInfo(), Ld->isVolatile(),
17298                                 Ld->isNonTemporal(), Ld->isInvariant(),
17299                                 std::min(16U, Alignment));
17300     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17301                              Load1.getValue(1),
17302                              Load2.getValue(1));
17303
17304     SDValue NewVec = DAG.getUNDEF(RegVT);
17305     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17306     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17307     return DCI.CombineTo(N, NewVec, TF, true);
17308   }
17309
17310   // If this is a vector EXT Load then attempt to optimize it using a
17311   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17312   // expansion is still better than scalar code.
17313   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17314   // emit a shuffle and a arithmetic shift.
17315   // TODO: It is possible to support ZExt by zeroing the undef values
17316   // during the shuffle phase or after the shuffle.
17317   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17318       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17319     assert(MemVT != RegVT && "Cannot extend to the same type");
17320     assert(MemVT.isVector() && "Must load a vector from memory");
17321
17322     unsigned NumElems = RegVT.getVectorNumElements();
17323     unsigned MemSz = MemVT.getSizeInBits();
17324     assert(RegSz > MemSz && "Register size must be greater than the mem size");
17325
17326     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17327       return SDValue();
17328
17329     // All sizes must be a power of two.
17330     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17331       return SDValue();
17332
17333     // Attempt to load the original value using scalar loads.
17334     // Find the largest scalar type that divides the total loaded size.
17335     MVT SclrLoadTy = MVT::i8;
17336     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17337          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17338       MVT Tp = (MVT::SimpleValueType)tp;
17339       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17340         SclrLoadTy = Tp;
17341       }
17342     }
17343
17344     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17345     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17346         (64 <= MemSz))
17347       SclrLoadTy = MVT::f64;
17348
17349     // Calculate the number of scalar loads that we need to perform
17350     // in order to load our vector from memory.
17351     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17352     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17353       return SDValue();
17354
17355     unsigned loadRegZize = RegSz;
17356     if (Ext == ISD::SEXTLOAD && RegSz == 256)
17357       loadRegZize /= 2;
17358
17359     // Represent our vector as a sequence of elements which are the
17360     // largest scalar that we can load.
17361     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17362       loadRegZize/SclrLoadTy.getSizeInBits());
17363
17364     // Represent the data using the same element type that is stored in
17365     // memory. In practice, we ''widen'' MemVT.
17366     EVT WideVecVT =
17367           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17368                        loadRegZize/MemVT.getScalarType().getSizeInBits());
17369
17370     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17371       "Invalid vector type");
17372
17373     // We can't shuffle using an illegal type.
17374     if (!TLI.isTypeLegal(WideVecVT))
17375       return SDValue();
17376
17377     SmallVector<SDValue, 8> Chains;
17378     SDValue Ptr = Ld->getBasePtr();
17379     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17380                                         TLI.getPointerTy());
17381     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17382
17383     for (unsigned i = 0; i < NumLoads; ++i) {
17384       // Perform a single load.
17385       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17386                                        Ptr, Ld->getPointerInfo(),
17387                                        Ld->isVolatile(), Ld->isNonTemporal(),
17388                                        Ld->isInvariant(), Ld->getAlignment());
17389       Chains.push_back(ScalarLoad.getValue(1));
17390       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17391       // another round of DAGCombining.
17392       if (i == 0)
17393         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17394       else
17395         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17396                           ScalarLoad, DAG.getIntPtrConstant(i));
17397
17398       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17399     }
17400
17401     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17402                                Chains.size());
17403
17404     // Bitcast the loaded value to a vector of the original element type, in
17405     // the size of the target vector type.
17406     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17407     unsigned SizeRatio = RegSz/MemSz;
17408
17409     if (Ext == ISD::SEXTLOAD) {
17410       // If we have SSE4.1 we can directly emit a VSEXT node.
17411       if (Subtarget->hasSSE41()) {
17412         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17413         return DCI.CombineTo(N, Sext, TF, true);
17414       }
17415
17416       // Otherwise we'll shuffle the small elements in the high bits of the
17417       // larger type and perform an arithmetic shift. If the shift is not legal
17418       // it's better to scalarize.
17419       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17420         return SDValue();
17421
17422       // Redistribute the loaded elements into the different locations.
17423       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17424       for (unsigned i = 0; i != NumElems; ++i)
17425         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17426
17427       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17428                                            DAG.getUNDEF(WideVecVT),
17429                                            &ShuffleVec[0]);
17430
17431       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17432
17433       // Build the arithmetic shift.
17434       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17435                      MemVT.getVectorElementType().getSizeInBits();
17436       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17437                           DAG.getConstant(Amt, RegVT));
17438
17439       return DCI.CombineTo(N, Shuff, TF, true);
17440     }
17441
17442     // Redistribute the loaded elements into the different locations.
17443     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17444     for (unsigned i = 0; i != NumElems; ++i)
17445       ShuffleVec[i*SizeRatio] = i;
17446
17447     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17448                                          DAG.getUNDEF(WideVecVT),
17449                                          &ShuffleVec[0]);
17450
17451     // Bitcast to the requested type.
17452     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17453     // Replace the original load with the new sequence
17454     // and return the new chain.
17455     return DCI.CombineTo(N, Shuff, TF, true);
17456   }
17457
17458   return SDValue();
17459 }
17460
17461 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17462 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17463                                    const X86Subtarget *Subtarget) {
17464   StoreSDNode *St = cast<StoreSDNode>(N);
17465   EVT VT = St->getValue().getValueType();
17466   EVT StVT = St->getMemoryVT();
17467   SDLoc dl(St);
17468   SDValue StoredVal = St->getOperand(1);
17469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17470
17471   // If we are saving a concatenation of two XMM registers, perform two stores.
17472   // On Sandy Bridge, 256-bit memory operations are executed by two
17473   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17474   // memory  operation.
17475   unsigned Alignment = St->getAlignment();
17476   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17477   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17478       StVT == VT && !IsAligned) {
17479     unsigned NumElems = VT.getVectorNumElements();
17480     if (NumElems < 2)
17481       return SDValue();
17482
17483     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17484     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17485
17486     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17487     SDValue Ptr0 = St->getBasePtr();
17488     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17489
17490     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17491                                 St->getPointerInfo(), St->isVolatile(),
17492                                 St->isNonTemporal(), Alignment);
17493     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17494                                 St->getPointerInfo(), St->isVolatile(),
17495                                 St->isNonTemporal(),
17496                                 std::min(16U, Alignment));
17497     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17498   }
17499
17500   // Optimize trunc store (of multiple scalars) to shuffle and store.
17501   // First, pack all of the elements in one place. Next, store to memory
17502   // in fewer chunks.
17503   if (St->isTruncatingStore() && VT.isVector()) {
17504     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17505     unsigned NumElems = VT.getVectorNumElements();
17506     assert(StVT != VT && "Cannot truncate to the same type");
17507     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17508     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17509
17510     // From, To sizes and ElemCount must be pow of two
17511     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17512     // We are going to use the original vector elt for storing.
17513     // Accumulated smaller vector elements must be a multiple of the store size.
17514     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17515
17516     unsigned SizeRatio  = FromSz / ToSz;
17517
17518     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17519
17520     // Create a type on which we perform the shuffle
17521     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17522             StVT.getScalarType(), NumElems*SizeRatio);
17523
17524     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17525
17526     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17527     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17528     for (unsigned i = 0; i != NumElems; ++i)
17529       ShuffleVec[i] = i * SizeRatio;
17530
17531     // Can't shuffle using an illegal type.
17532     if (!TLI.isTypeLegal(WideVecVT))
17533       return SDValue();
17534
17535     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17536                                          DAG.getUNDEF(WideVecVT),
17537                                          &ShuffleVec[0]);
17538     // At this point all of the data is stored at the bottom of the
17539     // register. We now need to save it to mem.
17540
17541     // Find the largest store unit
17542     MVT StoreType = MVT::i8;
17543     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17544          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17545       MVT Tp = (MVT::SimpleValueType)tp;
17546       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17547         StoreType = Tp;
17548     }
17549
17550     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17551     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17552         (64 <= NumElems * ToSz))
17553       StoreType = MVT::f64;
17554
17555     // Bitcast the original vector into a vector of store-size units
17556     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17557             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17558     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17559     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17560     SmallVector<SDValue, 8> Chains;
17561     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17562                                         TLI.getPointerTy());
17563     SDValue Ptr = St->getBasePtr();
17564
17565     // Perform one or more big stores into memory.
17566     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17567       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17568                                    StoreType, ShuffWide,
17569                                    DAG.getIntPtrConstant(i));
17570       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17571                                 St->getPointerInfo(), St->isVolatile(),
17572                                 St->isNonTemporal(), St->getAlignment());
17573       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17574       Chains.push_back(Ch);
17575     }
17576
17577     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17578                                Chains.size());
17579   }
17580
17581   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17582   // the FP state in cases where an emms may be missing.
17583   // A preferable solution to the general problem is to figure out the right
17584   // places to insert EMMS.  This qualifies as a quick hack.
17585
17586   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17587   if (VT.getSizeInBits() != 64)
17588     return SDValue();
17589
17590   const Function *F = DAG.getMachineFunction().getFunction();
17591   bool NoImplicitFloatOps = F->getAttributes().
17592     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17593   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17594                      && Subtarget->hasSSE2();
17595   if ((VT.isVector() ||
17596        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17597       isa<LoadSDNode>(St->getValue()) &&
17598       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17599       St->getChain().hasOneUse() && !St->isVolatile()) {
17600     SDNode* LdVal = St->getValue().getNode();
17601     LoadSDNode *Ld = 0;
17602     int TokenFactorIndex = -1;
17603     SmallVector<SDValue, 8> Ops;
17604     SDNode* ChainVal = St->getChain().getNode();
17605     // Must be a store of a load.  We currently handle two cases:  the load
17606     // is a direct child, and it's under an intervening TokenFactor.  It is
17607     // possible to dig deeper under nested TokenFactors.
17608     if (ChainVal == LdVal)
17609       Ld = cast<LoadSDNode>(St->getChain());
17610     else if (St->getValue().hasOneUse() &&
17611              ChainVal->getOpcode() == ISD::TokenFactor) {
17612       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17613         if (ChainVal->getOperand(i).getNode() == LdVal) {
17614           TokenFactorIndex = i;
17615           Ld = cast<LoadSDNode>(St->getValue());
17616         } else
17617           Ops.push_back(ChainVal->getOperand(i));
17618       }
17619     }
17620
17621     if (!Ld || !ISD::isNormalLoad(Ld))
17622       return SDValue();
17623
17624     // If this is not the MMX case, i.e. we are just turning i64 load/store
17625     // into f64 load/store, avoid the transformation if there are multiple
17626     // uses of the loaded value.
17627     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17628       return SDValue();
17629
17630     SDLoc LdDL(Ld);
17631     SDLoc StDL(N);
17632     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17633     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17634     // pair instead.
17635     if (Subtarget->is64Bit() || F64IsLegal) {
17636       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17637       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17638                                   Ld->getPointerInfo(), Ld->isVolatile(),
17639                                   Ld->isNonTemporal(), Ld->isInvariant(),
17640                                   Ld->getAlignment());
17641       SDValue NewChain = NewLd.getValue(1);
17642       if (TokenFactorIndex != -1) {
17643         Ops.push_back(NewChain);
17644         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17645                                Ops.size());
17646       }
17647       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17648                           St->getPointerInfo(),
17649                           St->isVolatile(), St->isNonTemporal(),
17650                           St->getAlignment());
17651     }
17652
17653     // Otherwise, lower to two pairs of 32-bit loads / stores.
17654     SDValue LoAddr = Ld->getBasePtr();
17655     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17656                                  DAG.getConstant(4, MVT::i32));
17657
17658     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17659                                Ld->getPointerInfo(),
17660                                Ld->isVolatile(), Ld->isNonTemporal(),
17661                                Ld->isInvariant(), Ld->getAlignment());
17662     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17663                                Ld->getPointerInfo().getWithOffset(4),
17664                                Ld->isVolatile(), Ld->isNonTemporal(),
17665                                Ld->isInvariant(),
17666                                MinAlign(Ld->getAlignment(), 4));
17667
17668     SDValue NewChain = LoLd.getValue(1);
17669     if (TokenFactorIndex != -1) {
17670       Ops.push_back(LoLd);
17671       Ops.push_back(HiLd);
17672       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17673                              Ops.size());
17674     }
17675
17676     LoAddr = St->getBasePtr();
17677     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17678                          DAG.getConstant(4, MVT::i32));
17679
17680     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17681                                 St->getPointerInfo(),
17682                                 St->isVolatile(), St->isNonTemporal(),
17683                                 St->getAlignment());
17684     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17685                                 St->getPointerInfo().getWithOffset(4),
17686                                 St->isVolatile(),
17687                                 St->isNonTemporal(),
17688                                 MinAlign(St->getAlignment(), 4));
17689     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17690   }
17691   return SDValue();
17692 }
17693
17694 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17695 /// and return the operands for the horizontal operation in LHS and RHS.  A
17696 /// horizontal operation performs the binary operation on successive elements
17697 /// of its first operand, then on successive elements of its second operand,
17698 /// returning the resulting values in a vector.  For example, if
17699 ///   A = < float a0, float a1, float a2, float a3 >
17700 /// and
17701 ///   B = < float b0, float b1, float b2, float b3 >
17702 /// then the result of doing a horizontal operation on A and B is
17703 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17704 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17705 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17706 /// set to A, RHS to B, and the routine returns 'true'.
17707 /// Note that the binary operation should have the property that if one of the
17708 /// operands is UNDEF then the result is UNDEF.
17709 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17710   // Look for the following pattern: if
17711   //   A = < float a0, float a1, float a2, float a3 >
17712   //   B = < float b0, float b1, float b2, float b3 >
17713   // and
17714   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17715   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17716   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17717   // which is A horizontal-op B.
17718
17719   // At least one of the operands should be a vector shuffle.
17720   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17721       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17722     return false;
17723
17724   MVT VT = LHS.getValueType().getSimpleVT();
17725
17726   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17727          "Unsupported vector type for horizontal add/sub");
17728
17729   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17730   // operate independently on 128-bit lanes.
17731   unsigned NumElts = VT.getVectorNumElements();
17732   unsigned NumLanes = VT.getSizeInBits()/128;
17733   unsigned NumLaneElts = NumElts / NumLanes;
17734   assert((NumLaneElts % 2 == 0) &&
17735          "Vector type should have an even number of elements in each lane");
17736   unsigned HalfLaneElts = NumLaneElts/2;
17737
17738   // View LHS in the form
17739   //   LHS = VECTOR_SHUFFLE A, B, LMask
17740   // If LHS is not a shuffle then pretend it is the shuffle
17741   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17742   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17743   // type VT.
17744   SDValue A, B;
17745   SmallVector<int, 16> LMask(NumElts);
17746   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17747     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17748       A = LHS.getOperand(0);
17749     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17750       B = LHS.getOperand(1);
17751     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17752     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17753   } else {
17754     if (LHS.getOpcode() != ISD::UNDEF)
17755       A = LHS;
17756     for (unsigned i = 0; i != NumElts; ++i)
17757       LMask[i] = i;
17758   }
17759
17760   // Likewise, view RHS in the form
17761   //   RHS = VECTOR_SHUFFLE C, D, RMask
17762   SDValue C, D;
17763   SmallVector<int, 16> RMask(NumElts);
17764   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17765     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17766       C = RHS.getOperand(0);
17767     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17768       D = RHS.getOperand(1);
17769     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17770     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17771   } else {
17772     if (RHS.getOpcode() != ISD::UNDEF)
17773       C = RHS;
17774     for (unsigned i = 0; i != NumElts; ++i)
17775       RMask[i] = i;
17776   }
17777
17778   // Check that the shuffles are both shuffling the same vectors.
17779   if (!(A == C && B == D) && !(A == D && B == C))
17780     return false;
17781
17782   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17783   if (!A.getNode() && !B.getNode())
17784     return false;
17785
17786   // If A and B occur in reverse order in RHS, then "swap" them (which means
17787   // rewriting the mask).
17788   if (A != C)
17789     CommuteVectorShuffleMask(RMask, NumElts);
17790
17791   // At this point LHS and RHS are equivalent to
17792   //   LHS = VECTOR_SHUFFLE A, B, LMask
17793   //   RHS = VECTOR_SHUFFLE A, B, RMask
17794   // Check that the masks correspond to performing a horizontal operation.
17795   for (unsigned i = 0; i != NumElts; ++i) {
17796     int LIdx = LMask[i], RIdx = RMask[i];
17797
17798     // Ignore any UNDEF components.
17799     if (LIdx < 0 || RIdx < 0 ||
17800         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17801         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17802       continue;
17803
17804     // Check that successive elements are being operated on.  If not, this is
17805     // not a horizontal operation.
17806     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17807     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17808     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17809     if (!(LIdx == Index && RIdx == Index + 1) &&
17810         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17811       return false;
17812   }
17813
17814   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17815   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17816   return true;
17817 }
17818
17819 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17820 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17821                                   const X86Subtarget *Subtarget) {
17822   EVT VT = N->getValueType(0);
17823   SDValue LHS = N->getOperand(0);
17824   SDValue RHS = N->getOperand(1);
17825
17826   // Try to synthesize horizontal adds from adds of shuffles.
17827   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17828        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17829       isHorizontalBinOp(LHS, RHS, true))
17830     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17831   return SDValue();
17832 }
17833
17834 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17835 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17836                                   const X86Subtarget *Subtarget) {
17837   EVT VT = N->getValueType(0);
17838   SDValue LHS = N->getOperand(0);
17839   SDValue RHS = N->getOperand(1);
17840
17841   // Try to synthesize horizontal subs from subs of shuffles.
17842   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17843        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17844       isHorizontalBinOp(LHS, RHS, false))
17845     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17846   return SDValue();
17847 }
17848
17849 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17850 /// X86ISD::FXOR nodes.
17851 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17852   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17853   // F[X]OR(0.0, x) -> x
17854   // F[X]OR(x, 0.0) -> x
17855   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17856     if (C->getValueAPF().isPosZero())
17857       return N->getOperand(1);
17858   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17859     if (C->getValueAPF().isPosZero())
17860       return N->getOperand(0);
17861   return SDValue();
17862 }
17863
17864 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17865 /// X86ISD::FMAX nodes.
17866 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17867   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17868
17869   // Only perform optimizations if UnsafeMath is used.
17870   if (!DAG.getTarget().Options.UnsafeFPMath)
17871     return SDValue();
17872
17873   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17874   // into FMINC and FMAXC, which are Commutative operations.
17875   unsigned NewOp = 0;
17876   switch (N->getOpcode()) {
17877     default: llvm_unreachable("unknown opcode");
17878     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17879     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17880   }
17881
17882   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17883                      N->getOperand(0), N->getOperand(1));
17884 }
17885
17886 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17887 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17888   // FAND(0.0, x) -> 0.0
17889   // FAND(x, 0.0) -> 0.0
17890   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17891     if (C->getValueAPF().isPosZero())
17892       return N->getOperand(0);
17893   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17894     if (C->getValueAPF().isPosZero())
17895       return N->getOperand(1);
17896   return SDValue();
17897 }
17898
17899 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
17900 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
17901   // FANDN(x, 0.0) -> 0.0
17902   // FANDN(0.0, x) -> x
17903   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17904     if (C->getValueAPF().isPosZero())
17905       return N->getOperand(1);
17906   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17907     if (C->getValueAPF().isPosZero())
17908       return N->getOperand(1);
17909   return SDValue();
17910 }
17911
17912 static SDValue PerformBTCombine(SDNode *N,
17913                                 SelectionDAG &DAG,
17914                                 TargetLowering::DAGCombinerInfo &DCI) {
17915   // BT ignores high bits in the bit index operand.
17916   SDValue Op1 = N->getOperand(1);
17917   if (Op1.hasOneUse()) {
17918     unsigned BitWidth = Op1.getValueSizeInBits();
17919     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17920     APInt KnownZero, KnownOne;
17921     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17922                                           !DCI.isBeforeLegalizeOps());
17923     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17924     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17925         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17926       DCI.CommitTargetLoweringOpt(TLO);
17927   }
17928   return SDValue();
17929 }
17930
17931 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17932   SDValue Op = N->getOperand(0);
17933   if (Op.getOpcode() == ISD::BITCAST)
17934     Op = Op.getOperand(0);
17935   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17936   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17937       VT.getVectorElementType().getSizeInBits() ==
17938       OpVT.getVectorElementType().getSizeInBits()) {
17939     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17940   }
17941   return SDValue();
17942 }
17943
17944 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17945                                                const X86Subtarget *Subtarget) {
17946   EVT VT = N->getValueType(0);
17947   if (!VT.isVector())
17948     return SDValue();
17949
17950   SDValue N0 = N->getOperand(0);
17951   SDValue N1 = N->getOperand(1);
17952   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17953   SDLoc dl(N);
17954
17955   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17956   // both SSE and AVX2 since there is no sign-extended shift right
17957   // operation on a vector with 64-bit elements.
17958   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17959   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17960   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17961       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17962     SDValue N00 = N0.getOperand(0);
17963
17964     // EXTLOAD has a better solution on AVX2,
17965     // it may be replaced with X86ISD::VSEXT node.
17966     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17967       if (!ISD::isNormalLoad(N00.getNode()))
17968         return SDValue();
17969
17970     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17971         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17972                                   N00, N1);
17973       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17974     }
17975   }
17976   return SDValue();
17977 }
17978
17979 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17980                                   TargetLowering::DAGCombinerInfo &DCI,
17981                                   const X86Subtarget *Subtarget) {
17982   if (!DCI.isBeforeLegalizeOps())
17983     return SDValue();
17984
17985   if (!Subtarget->hasFp256())
17986     return SDValue();
17987
17988   EVT VT = N->getValueType(0);
17989   if (VT.isVector() && VT.getSizeInBits() == 256) {
17990     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17991     if (R.getNode())
17992       return R;
17993   }
17994
17995   return SDValue();
17996 }
17997
17998 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17999                                  const X86Subtarget* Subtarget) {
18000   SDLoc dl(N);
18001   EVT VT = N->getValueType(0);
18002
18003   // Let legalize expand this if it isn't a legal type yet.
18004   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18005     return SDValue();
18006
18007   EVT ScalarVT = VT.getScalarType();
18008   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18009       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18010     return SDValue();
18011
18012   SDValue A = N->getOperand(0);
18013   SDValue B = N->getOperand(1);
18014   SDValue C = N->getOperand(2);
18015
18016   bool NegA = (A.getOpcode() == ISD::FNEG);
18017   bool NegB = (B.getOpcode() == ISD::FNEG);
18018   bool NegC = (C.getOpcode() == ISD::FNEG);
18019
18020   // Negative multiplication when NegA xor NegB
18021   bool NegMul = (NegA != NegB);
18022   if (NegA)
18023     A = A.getOperand(0);
18024   if (NegB)
18025     B = B.getOperand(0);
18026   if (NegC)
18027     C = C.getOperand(0);
18028
18029   unsigned Opcode;
18030   if (!NegMul)
18031     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18032   else
18033     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18034
18035   return DAG.getNode(Opcode, dl, VT, A, B, C);
18036 }
18037
18038 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18039                                   TargetLowering::DAGCombinerInfo &DCI,
18040                                   const X86Subtarget *Subtarget) {
18041   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18042   //           (and (i32 x86isd::setcc_carry), 1)
18043   // This eliminates the zext. This transformation is necessary because
18044   // ISD::SETCC is always legalized to i8.
18045   SDLoc dl(N);
18046   SDValue N0 = N->getOperand(0);
18047   EVT VT = N->getValueType(0);
18048
18049   if (N0.getOpcode() == ISD::AND &&
18050       N0.hasOneUse() &&
18051       N0.getOperand(0).hasOneUse()) {
18052     SDValue N00 = N0.getOperand(0);
18053     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18054       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18055       if (!C || C->getZExtValue() != 1)
18056         return SDValue();
18057       return DAG.getNode(ISD::AND, dl, VT,
18058                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18059                                      N00.getOperand(0), N00.getOperand(1)),
18060                          DAG.getConstant(1, VT));
18061     }
18062   }
18063
18064   if (VT.is256BitVector()) {
18065     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18066     if (R.getNode())
18067       return R;
18068   }
18069
18070   return SDValue();
18071 }
18072
18073 // Optimize x == -y --> x+y == 0
18074 //          x != -y --> x+y != 0
18075 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18076   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18077   SDValue LHS = N->getOperand(0);
18078   SDValue RHS = N->getOperand(1);
18079
18080   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18081     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18082       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18083         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18084                                    LHS.getValueType(), RHS, LHS.getOperand(1));
18085         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18086                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18087       }
18088   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18089     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18090       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18091         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18092                                    RHS.getValueType(), LHS, RHS.getOperand(1));
18093         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18094                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18095       }
18096   return SDValue();
18097 }
18098
18099 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18100 // as "sbb reg,reg", since it can be extended without zext and produces
18101 // an all-ones bit which is more useful than 0/1 in some cases.
18102 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18103   return DAG.getNode(ISD::AND, DL, MVT::i8,
18104                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18105                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18106                      DAG.getConstant(1, MVT::i8));
18107 }
18108
18109 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18110 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18111                                    TargetLowering::DAGCombinerInfo &DCI,
18112                                    const X86Subtarget *Subtarget) {
18113   SDLoc DL(N);
18114   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18115   SDValue EFLAGS = N->getOperand(1);
18116
18117   if (CC == X86::COND_A) {
18118     // Try to convert COND_A into COND_B in an attempt to facilitate
18119     // materializing "setb reg".
18120     //
18121     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18122     // cannot take an immediate as its first operand.
18123     //
18124     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18125         EFLAGS.getValueType().isInteger() &&
18126         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18127       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18128                                    EFLAGS.getNode()->getVTList(),
18129                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18130       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18131       return MaterializeSETB(DL, NewEFLAGS, DAG);
18132     }
18133   }
18134
18135   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18136   // a zext and produces an all-ones bit which is more useful than 0/1 in some
18137   // cases.
18138   if (CC == X86::COND_B)
18139     return MaterializeSETB(DL, EFLAGS, DAG);
18140
18141   SDValue Flags;
18142
18143   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18144   if (Flags.getNode()) {
18145     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18146     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18147   }
18148
18149   return SDValue();
18150 }
18151
18152 // Optimize branch condition evaluation.
18153 //
18154 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18155                                     TargetLowering::DAGCombinerInfo &DCI,
18156                                     const X86Subtarget *Subtarget) {
18157   SDLoc DL(N);
18158   SDValue Chain = N->getOperand(0);
18159   SDValue Dest = N->getOperand(1);
18160   SDValue EFLAGS = N->getOperand(3);
18161   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18162
18163   SDValue Flags;
18164
18165   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18166   if (Flags.getNode()) {
18167     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18168     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18169                        Flags);
18170   }
18171
18172   return SDValue();
18173 }
18174
18175 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18176                                         const X86TargetLowering *XTLI) {
18177   SDValue Op0 = N->getOperand(0);
18178   EVT InVT = Op0->getValueType(0);
18179
18180   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18181   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18182     SDLoc dl(N);
18183     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18184     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18185     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18186   }
18187
18188   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18189   // a 32-bit target where SSE doesn't support i64->FP operations.
18190   if (Op0.getOpcode() == ISD::LOAD) {
18191     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18192     EVT VT = Ld->getValueType(0);
18193     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18194         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18195         !XTLI->getSubtarget()->is64Bit() &&
18196         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18197       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18198                                           Ld->getChain(), Op0, DAG);
18199       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18200       return FILDChain;
18201     }
18202   }
18203   return SDValue();
18204 }
18205
18206 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18207 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18208                                  X86TargetLowering::DAGCombinerInfo &DCI) {
18209   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18210   // the result is either zero or one (depending on the input carry bit).
18211   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18212   if (X86::isZeroNode(N->getOperand(0)) &&
18213       X86::isZeroNode(N->getOperand(1)) &&
18214       // We don't have a good way to replace an EFLAGS use, so only do this when
18215       // dead right now.
18216       SDValue(N, 1).use_empty()) {
18217     SDLoc DL(N);
18218     EVT VT = N->getValueType(0);
18219     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18220     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18221                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18222                                            DAG.getConstant(X86::COND_B,MVT::i8),
18223                                            N->getOperand(2)),
18224                                DAG.getConstant(1, VT));
18225     return DCI.CombineTo(N, Res1, CarryOut);
18226   }
18227
18228   return SDValue();
18229 }
18230
18231 // fold (add Y, (sete  X, 0)) -> adc  0, Y
18232 //      (add Y, (setne X, 0)) -> sbb -1, Y
18233 //      (sub (sete  X, 0), Y) -> sbb  0, Y
18234 //      (sub (setne X, 0), Y) -> adc -1, Y
18235 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18236   SDLoc DL(N);
18237
18238   // Look through ZExts.
18239   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18240   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18241     return SDValue();
18242
18243   SDValue SetCC = Ext.getOperand(0);
18244   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18245     return SDValue();
18246
18247   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18248   if (CC != X86::COND_E && CC != X86::COND_NE)
18249     return SDValue();
18250
18251   SDValue Cmp = SetCC.getOperand(1);
18252   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18253       !X86::isZeroNode(Cmp.getOperand(1)) ||
18254       !Cmp.getOperand(0).getValueType().isInteger())
18255     return SDValue();
18256
18257   SDValue CmpOp0 = Cmp.getOperand(0);
18258   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18259                                DAG.getConstant(1, CmpOp0.getValueType()));
18260
18261   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18262   if (CC == X86::COND_NE)
18263     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18264                        DL, OtherVal.getValueType(), OtherVal,
18265                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18266   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18267                      DL, OtherVal.getValueType(), OtherVal,
18268                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18269 }
18270
18271 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18272 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18273                                  const X86Subtarget *Subtarget) {
18274   EVT VT = N->getValueType(0);
18275   SDValue Op0 = N->getOperand(0);
18276   SDValue Op1 = N->getOperand(1);
18277
18278   // Try to synthesize horizontal adds from adds of shuffles.
18279   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18280        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18281       isHorizontalBinOp(Op0, Op1, true))
18282     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18283
18284   return OptimizeConditionalInDecrement(N, DAG);
18285 }
18286
18287 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18288                                  const X86Subtarget *Subtarget) {
18289   SDValue Op0 = N->getOperand(0);
18290   SDValue Op1 = N->getOperand(1);
18291
18292   // X86 can't encode an immediate LHS of a sub. See if we can push the
18293   // negation into a preceding instruction.
18294   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18295     // If the RHS of the sub is a XOR with one use and a constant, invert the
18296     // immediate. Then add one to the LHS of the sub so we can turn
18297     // X-Y -> X+~Y+1, saving one register.
18298     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18299         isa<ConstantSDNode>(Op1.getOperand(1))) {
18300       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18301       EVT VT = Op0.getValueType();
18302       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18303                                    Op1.getOperand(0),
18304                                    DAG.getConstant(~XorC, VT));
18305       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18306                          DAG.getConstant(C->getAPIntValue()+1, VT));
18307     }
18308   }
18309
18310   // Try to synthesize horizontal adds from adds of shuffles.
18311   EVT VT = N->getValueType(0);
18312   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18313        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18314       isHorizontalBinOp(Op0, Op1, true))
18315     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18316
18317   return OptimizeConditionalInDecrement(N, DAG);
18318 }
18319
18320 /// performVZEXTCombine - Performs build vector combines
18321 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18322                                         TargetLowering::DAGCombinerInfo &DCI,
18323                                         const X86Subtarget *Subtarget) {
18324   // (vzext (bitcast (vzext (x)) -> (vzext x)
18325   SDValue In = N->getOperand(0);
18326   while (In.getOpcode() == ISD::BITCAST)
18327     In = In.getOperand(0);
18328
18329   if (In.getOpcode() != X86ISD::VZEXT)
18330     return SDValue();
18331
18332   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18333                      In.getOperand(0));
18334 }
18335
18336 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18337                                              DAGCombinerInfo &DCI) const {
18338   SelectionDAG &DAG = DCI.DAG;
18339   switch (N->getOpcode()) {
18340   default: break;
18341   case ISD::EXTRACT_VECTOR_ELT:
18342     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18343   case ISD::VSELECT:
18344   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18345   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18346   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
18347   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
18348   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
18349   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
18350   case ISD::SHL:
18351   case ISD::SRA:
18352   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
18353   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
18354   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
18355   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
18356   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
18357   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
18358   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
18359   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
18360   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
18361   case X86ISD::FXOR:
18362   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
18363   case X86ISD::FMIN:
18364   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
18365   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
18366   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
18367   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
18368   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
18369   case ISD::ANY_EXTEND:
18370   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
18371   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
18372   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18373   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18374   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
18375   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18376   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18377   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
18378   case X86ISD::SHUFP:       // Handle all target specific shuffles
18379   case X86ISD::PALIGNR:
18380   case X86ISD::UNPCKH:
18381   case X86ISD::UNPCKL:
18382   case X86ISD::MOVHLPS:
18383   case X86ISD::MOVLHPS:
18384   case X86ISD::PSHUFD:
18385   case X86ISD::PSHUFHW:
18386   case X86ISD::PSHUFLW:
18387   case X86ISD::MOVSS:
18388   case X86ISD::MOVSD:
18389   case X86ISD::VPERMILP:
18390   case X86ISD::VPERM2X128:
18391   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18392   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
18393   }
18394
18395   return SDValue();
18396 }
18397
18398 /// isTypeDesirableForOp - Return true if the target has native support for
18399 /// the specified value type and it is 'desirable' to use the type for the
18400 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18401 /// instruction encodings are longer and some i16 instructions are slow.
18402 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18403   if (!isTypeLegal(VT))
18404     return false;
18405   if (VT != MVT::i16)
18406     return true;
18407
18408   switch (Opc) {
18409   default:
18410     return true;
18411   case ISD::LOAD:
18412   case ISD::SIGN_EXTEND:
18413   case ISD::ZERO_EXTEND:
18414   case ISD::ANY_EXTEND:
18415   case ISD::SHL:
18416   case ISD::SRL:
18417   case ISD::SUB:
18418   case ISD::ADD:
18419   case ISD::MUL:
18420   case ISD::AND:
18421   case ISD::OR:
18422   case ISD::XOR:
18423     return false;
18424   }
18425 }
18426
18427 /// IsDesirableToPromoteOp - This method query the target whether it is
18428 /// beneficial for dag combiner to promote the specified node. If true, it
18429 /// should return the desired promotion type by reference.
18430 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18431   EVT VT = Op.getValueType();
18432   if (VT != MVT::i16)
18433     return false;
18434
18435   bool Promote = false;
18436   bool Commute = false;
18437   switch (Op.getOpcode()) {
18438   default: break;
18439   case ISD::LOAD: {
18440     LoadSDNode *LD = cast<LoadSDNode>(Op);
18441     // If the non-extending load has a single use and it's not live out, then it
18442     // might be folded.
18443     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18444                                                      Op.hasOneUse()*/) {
18445       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18446              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18447         // The only case where we'd want to promote LOAD (rather then it being
18448         // promoted as an operand is when it's only use is liveout.
18449         if (UI->getOpcode() != ISD::CopyToReg)
18450           return false;
18451       }
18452     }
18453     Promote = true;
18454     break;
18455   }
18456   case ISD::SIGN_EXTEND:
18457   case ISD::ZERO_EXTEND:
18458   case ISD::ANY_EXTEND:
18459     Promote = true;
18460     break;
18461   case ISD::SHL:
18462   case ISD::SRL: {
18463     SDValue N0 = Op.getOperand(0);
18464     // Look out for (store (shl (load), x)).
18465     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18466       return false;
18467     Promote = true;
18468     break;
18469   }
18470   case ISD::ADD:
18471   case ISD::MUL:
18472   case ISD::AND:
18473   case ISD::OR:
18474   case ISD::XOR:
18475     Commute = true;
18476     // fallthrough
18477   case ISD::SUB: {
18478     SDValue N0 = Op.getOperand(0);
18479     SDValue N1 = Op.getOperand(1);
18480     if (!Commute && MayFoldLoad(N1))
18481       return false;
18482     // Avoid disabling potential load folding opportunities.
18483     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18484       return false;
18485     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18486       return false;
18487     Promote = true;
18488   }
18489   }
18490
18491   PVT = MVT::i32;
18492   return Promote;
18493 }
18494
18495 //===----------------------------------------------------------------------===//
18496 //                           X86 Inline Assembly Support
18497 //===----------------------------------------------------------------------===//
18498
18499 namespace {
18500   // Helper to match a string separated by whitespace.
18501   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18502     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18503
18504     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18505       StringRef piece(*args[i]);
18506       if (!s.startswith(piece)) // Check if the piece matches.
18507         return false;
18508
18509       s = s.substr(piece.size());
18510       StringRef::size_type pos = s.find_first_not_of(" \t");
18511       if (pos == 0) // We matched a prefix.
18512         return false;
18513
18514       s = s.substr(pos);
18515     }
18516
18517     return s.empty();
18518   }
18519   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18520 }
18521
18522 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18523   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18524
18525   std::string AsmStr = IA->getAsmString();
18526
18527   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18528   if (!Ty || Ty->getBitWidth() % 16 != 0)
18529     return false;
18530
18531   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18532   SmallVector<StringRef, 4> AsmPieces;
18533   SplitString(AsmStr, AsmPieces, ";\n");
18534
18535   switch (AsmPieces.size()) {
18536   default: return false;
18537   case 1:
18538     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18539     // we will turn this bswap into something that will be lowered to logical
18540     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18541     // lower so don't worry about this.
18542     // bswap $0
18543     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18544         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18545         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18546         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18547         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18548         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18549       // No need to check constraints, nothing other than the equivalent of
18550       // "=r,0" would be valid here.
18551       return IntrinsicLowering::LowerToByteSwap(CI);
18552     }
18553
18554     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18555     if (CI->getType()->isIntegerTy(16) &&
18556         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18557         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18558          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18559       AsmPieces.clear();
18560       const std::string &ConstraintsStr = IA->getConstraintString();
18561       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18562       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18563       if (AsmPieces.size() == 4 &&
18564           AsmPieces[0] == "~{cc}" &&
18565           AsmPieces[1] == "~{dirflag}" &&
18566           AsmPieces[2] == "~{flags}" &&
18567           AsmPieces[3] == "~{fpsr}")
18568       return IntrinsicLowering::LowerToByteSwap(CI);
18569     }
18570     break;
18571   case 3:
18572     if (CI->getType()->isIntegerTy(32) &&
18573         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18574         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18575         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18576         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18577       AsmPieces.clear();
18578       const std::string &ConstraintsStr = IA->getConstraintString();
18579       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18580       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18581       if (AsmPieces.size() == 4 &&
18582           AsmPieces[0] == "~{cc}" &&
18583           AsmPieces[1] == "~{dirflag}" &&
18584           AsmPieces[2] == "~{flags}" &&
18585           AsmPieces[3] == "~{fpsr}")
18586         return IntrinsicLowering::LowerToByteSwap(CI);
18587     }
18588
18589     if (CI->getType()->isIntegerTy(64)) {
18590       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18591       if (Constraints.size() >= 2 &&
18592           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18593           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18594         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18595         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18596             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18597             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18598           return IntrinsicLowering::LowerToByteSwap(CI);
18599       }
18600     }
18601     break;
18602   }
18603   return false;
18604 }
18605
18606 /// getConstraintType - Given a constraint letter, return the type of
18607 /// constraint it is for this target.
18608 X86TargetLowering::ConstraintType
18609 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18610   if (Constraint.size() == 1) {
18611     switch (Constraint[0]) {
18612     case 'R':
18613     case 'q':
18614     case 'Q':
18615     case 'f':
18616     case 't':
18617     case 'u':
18618     case 'y':
18619     case 'x':
18620     case 'Y':
18621     case 'l':
18622       return C_RegisterClass;
18623     case 'a':
18624     case 'b':
18625     case 'c':
18626     case 'd':
18627     case 'S':
18628     case 'D':
18629     case 'A':
18630       return C_Register;
18631     case 'I':
18632     case 'J':
18633     case 'K':
18634     case 'L':
18635     case 'M':
18636     case 'N':
18637     case 'G':
18638     case 'C':
18639     case 'e':
18640     case 'Z':
18641       return C_Other;
18642     default:
18643       break;
18644     }
18645   }
18646   return TargetLowering::getConstraintType(Constraint);
18647 }
18648
18649 /// Examine constraint type and operand type and determine a weight value.
18650 /// This object must already have been set up with the operand type
18651 /// and the current alternative constraint selected.
18652 TargetLowering::ConstraintWeight
18653   X86TargetLowering::getSingleConstraintMatchWeight(
18654     AsmOperandInfo &info, const char *constraint) const {
18655   ConstraintWeight weight = CW_Invalid;
18656   Value *CallOperandVal = info.CallOperandVal;
18657     // If we don't have a value, we can't do a match,
18658     // but allow it at the lowest weight.
18659   if (CallOperandVal == NULL)
18660     return CW_Default;
18661   Type *type = CallOperandVal->getType();
18662   // Look at the constraint type.
18663   switch (*constraint) {
18664   default:
18665     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18666   case 'R':
18667   case 'q':
18668   case 'Q':
18669   case 'a':
18670   case 'b':
18671   case 'c':
18672   case 'd':
18673   case 'S':
18674   case 'D':
18675   case 'A':
18676     if (CallOperandVal->getType()->isIntegerTy())
18677       weight = CW_SpecificReg;
18678     break;
18679   case 'f':
18680   case 't':
18681   case 'u':
18682     if (type->isFloatingPointTy())
18683       weight = CW_SpecificReg;
18684     break;
18685   case 'y':
18686     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18687       weight = CW_SpecificReg;
18688     break;
18689   case 'x':
18690   case 'Y':
18691     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18692         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18693       weight = CW_Register;
18694     break;
18695   case 'I':
18696     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18697       if (C->getZExtValue() <= 31)
18698         weight = CW_Constant;
18699     }
18700     break;
18701   case 'J':
18702     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18703       if (C->getZExtValue() <= 63)
18704         weight = CW_Constant;
18705     }
18706     break;
18707   case 'K':
18708     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18709       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18710         weight = CW_Constant;
18711     }
18712     break;
18713   case 'L':
18714     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18715       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18716         weight = CW_Constant;
18717     }
18718     break;
18719   case 'M':
18720     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18721       if (C->getZExtValue() <= 3)
18722         weight = CW_Constant;
18723     }
18724     break;
18725   case 'N':
18726     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18727       if (C->getZExtValue() <= 0xff)
18728         weight = CW_Constant;
18729     }
18730     break;
18731   case 'G':
18732   case 'C':
18733     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18734       weight = CW_Constant;
18735     }
18736     break;
18737   case 'e':
18738     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18739       if ((C->getSExtValue() >= -0x80000000LL) &&
18740           (C->getSExtValue() <= 0x7fffffffLL))
18741         weight = CW_Constant;
18742     }
18743     break;
18744   case 'Z':
18745     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18746       if (C->getZExtValue() <= 0xffffffff)
18747         weight = CW_Constant;
18748     }
18749     break;
18750   }
18751   return weight;
18752 }
18753
18754 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18755 /// with another that has more specific requirements based on the type of the
18756 /// corresponding operand.
18757 const char *X86TargetLowering::
18758 LowerXConstraint(EVT ConstraintVT) const {
18759   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18760   // 'f' like normal targets.
18761   if (ConstraintVT.isFloatingPoint()) {
18762     if (Subtarget->hasSSE2())
18763       return "Y";
18764     if (Subtarget->hasSSE1())
18765       return "x";
18766   }
18767
18768   return TargetLowering::LowerXConstraint(ConstraintVT);
18769 }
18770
18771 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18772 /// vector.  If it is invalid, don't add anything to Ops.
18773 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18774                                                      std::string &Constraint,
18775                                                      std::vector<SDValue>&Ops,
18776                                                      SelectionDAG &DAG) const {
18777   SDValue Result(0, 0);
18778
18779   // Only support length 1 constraints for now.
18780   if (Constraint.length() > 1) return;
18781
18782   char ConstraintLetter = Constraint[0];
18783   switch (ConstraintLetter) {
18784   default: break;
18785   case 'I':
18786     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18787       if (C->getZExtValue() <= 31) {
18788         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18789         break;
18790       }
18791     }
18792     return;
18793   case 'J':
18794     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18795       if (C->getZExtValue() <= 63) {
18796         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18797         break;
18798       }
18799     }
18800     return;
18801   case 'K':
18802     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18803       if (isInt<8>(C->getSExtValue())) {
18804         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18805         break;
18806       }
18807     }
18808     return;
18809   case 'N':
18810     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18811       if (C->getZExtValue() <= 255) {
18812         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18813         break;
18814       }
18815     }
18816     return;
18817   case 'e': {
18818     // 32-bit signed value
18819     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18820       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18821                                            C->getSExtValue())) {
18822         // Widen to 64 bits here to get it sign extended.
18823         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18824         break;
18825       }
18826     // FIXME gcc accepts some relocatable values here too, but only in certain
18827     // memory models; it's complicated.
18828     }
18829     return;
18830   }
18831   case 'Z': {
18832     // 32-bit unsigned value
18833     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18834       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18835                                            C->getZExtValue())) {
18836         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18837         break;
18838       }
18839     }
18840     // FIXME gcc accepts some relocatable values here too, but only in certain
18841     // memory models; it's complicated.
18842     return;
18843   }
18844   case 'i': {
18845     // Literal immediates are always ok.
18846     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18847       // Widen to 64 bits here to get it sign extended.
18848       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18849       break;
18850     }
18851
18852     // In any sort of PIC mode addresses need to be computed at runtime by
18853     // adding in a register or some sort of table lookup.  These can't
18854     // be used as immediates.
18855     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18856       return;
18857
18858     // If we are in non-pic codegen mode, we allow the address of a global (with
18859     // an optional displacement) to be used with 'i'.
18860     GlobalAddressSDNode *GA = 0;
18861     int64_t Offset = 0;
18862
18863     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18864     while (1) {
18865       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18866         Offset += GA->getOffset();
18867         break;
18868       } else if (Op.getOpcode() == ISD::ADD) {
18869         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18870           Offset += C->getZExtValue();
18871           Op = Op.getOperand(0);
18872           continue;
18873         }
18874       } else if (Op.getOpcode() == ISD::SUB) {
18875         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18876           Offset += -C->getZExtValue();
18877           Op = Op.getOperand(0);
18878           continue;
18879         }
18880       }
18881
18882       // Otherwise, this isn't something we can handle, reject it.
18883       return;
18884     }
18885
18886     const GlobalValue *GV = GA->getGlobal();
18887     // If we require an extra load to get this address, as in PIC mode, we
18888     // can't accept it.
18889     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18890                                                         getTargetMachine())))
18891       return;
18892
18893     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18894                                         GA->getValueType(0), Offset);
18895     break;
18896   }
18897   }
18898
18899   if (Result.getNode()) {
18900     Ops.push_back(Result);
18901     return;
18902   }
18903   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18904 }
18905
18906 std::pair<unsigned, const TargetRegisterClass*>
18907 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18908                                                 MVT VT) const {
18909   // First, see if this is a constraint that directly corresponds to an LLVM
18910   // register class.
18911   if (Constraint.size() == 1) {
18912     // GCC Constraint Letters
18913     switch (Constraint[0]) {
18914     default: break;
18915       // TODO: Slight differences here in allocation order and leaving
18916       // RIP in the class. Do they matter any more here than they do
18917       // in the normal allocation?
18918     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18919       if (Subtarget->is64Bit()) {
18920         if (VT == MVT::i32 || VT == MVT::f32)
18921           return std::make_pair(0U, &X86::GR32RegClass);
18922         if (VT == MVT::i16)
18923           return std::make_pair(0U, &X86::GR16RegClass);
18924         if (VT == MVT::i8 || VT == MVT::i1)
18925           return std::make_pair(0U, &X86::GR8RegClass);
18926         if (VT == MVT::i64 || VT == MVT::f64)
18927           return std::make_pair(0U, &X86::GR64RegClass);
18928         break;
18929       }
18930       // 32-bit fallthrough
18931     case 'Q':   // Q_REGS
18932       if (VT == MVT::i32 || VT == MVT::f32)
18933         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18934       if (VT == MVT::i16)
18935         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18936       if (VT == MVT::i8 || VT == MVT::i1)
18937         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18938       if (VT == MVT::i64)
18939         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18940       break;
18941     case 'r':   // GENERAL_REGS
18942     case 'l':   // INDEX_REGS
18943       if (VT == MVT::i8 || VT == MVT::i1)
18944         return std::make_pair(0U, &X86::GR8RegClass);
18945       if (VT == MVT::i16)
18946         return std::make_pair(0U, &X86::GR16RegClass);
18947       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18948         return std::make_pair(0U, &X86::GR32RegClass);
18949       return std::make_pair(0U, &X86::GR64RegClass);
18950     case 'R':   // LEGACY_REGS
18951       if (VT == MVT::i8 || VT == MVT::i1)
18952         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18953       if (VT == MVT::i16)
18954         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18955       if (VT == MVT::i32 || !Subtarget->is64Bit())
18956         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18957       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18958     case 'f':  // FP Stack registers.
18959       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18960       // value to the correct fpstack register class.
18961       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18962         return std::make_pair(0U, &X86::RFP32RegClass);
18963       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18964         return std::make_pair(0U, &X86::RFP64RegClass);
18965       return std::make_pair(0U, &X86::RFP80RegClass);
18966     case 'y':   // MMX_REGS if MMX allowed.
18967       if (!Subtarget->hasMMX()) break;
18968       return std::make_pair(0U, &X86::VR64RegClass);
18969     case 'Y':   // SSE_REGS if SSE2 allowed
18970       if (!Subtarget->hasSSE2()) break;
18971       // FALL THROUGH.
18972     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18973       if (!Subtarget->hasSSE1()) break;
18974
18975       switch (VT.SimpleTy) {
18976       default: break;
18977       // Scalar SSE types.
18978       case MVT::f32:
18979       case MVT::i32:
18980         return std::make_pair(0U, &X86::FR32RegClass);
18981       case MVT::f64:
18982       case MVT::i64:
18983         return std::make_pair(0U, &X86::FR64RegClass);
18984       // Vector types.
18985       case MVT::v16i8:
18986       case MVT::v8i16:
18987       case MVT::v4i32:
18988       case MVT::v2i64:
18989       case MVT::v4f32:
18990       case MVT::v2f64:
18991         return std::make_pair(0U, &X86::VR128RegClass);
18992       // AVX types.
18993       case MVT::v32i8:
18994       case MVT::v16i16:
18995       case MVT::v8i32:
18996       case MVT::v4i64:
18997       case MVT::v8f32:
18998       case MVT::v4f64:
18999         return std::make_pair(0U, &X86::VR256RegClass);
19000       case MVT::v8f64:
19001       case MVT::v16f32:
19002       case MVT::v16i32:
19003       case MVT::v8i64:
19004         return std::make_pair(0U, &X86::VR512RegClass);
19005       }
19006       break;
19007     }
19008   }
19009
19010   // Use the default implementation in TargetLowering to convert the register
19011   // constraint into a member of a register class.
19012   std::pair<unsigned, const TargetRegisterClass*> Res;
19013   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19014
19015   // Not found as a standard register?
19016   if (Res.second == 0) {
19017     // Map st(0) -> st(7) -> ST0
19018     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19019         tolower(Constraint[1]) == 's' &&
19020         tolower(Constraint[2]) == 't' &&
19021         Constraint[3] == '(' &&
19022         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19023         Constraint[5] == ')' &&
19024         Constraint[6] == '}') {
19025
19026       Res.first = X86::ST0+Constraint[4]-'0';
19027       Res.second = &X86::RFP80RegClass;
19028       return Res;
19029     }
19030
19031     // GCC allows "st(0)" to be called just plain "st".
19032     if (StringRef("{st}").equals_lower(Constraint)) {
19033       Res.first = X86::ST0;
19034       Res.second = &X86::RFP80RegClass;
19035       return Res;
19036     }
19037
19038     // flags -> EFLAGS
19039     if (StringRef("{flags}").equals_lower(Constraint)) {
19040       Res.first = X86::EFLAGS;
19041       Res.second = &X86::CCRRegClass;
19042       return Res;
19043     }
19044
19045     // 'A' means EAX + EDX.
19046     if (Constraint == "A") {
19047       Res.first = X86::EAX;
19048       Res.second = &X86::GR32_ADRegClass;
19049       return Res;
19050     }
19051     return Res;
19052   }
19053
19054   // Otherwise, check to see if this is a register class of the wrong value
19055   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19056   // turn into {ax},{dx}.
19057   if (Res.second->hasType(VT))
19058     return Res;   // Correct type already, nothing to do.
19059
19060   // All of the single-register GCC register classes map their values onto
19061   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
19062   // really want an 8-bit or 32-bit register, map to the appropriate register
19063   // class and return the appropriate register.
19064   if (Res.second == &X86::GR16RegClass) {
19065     if (VT == MVT::i8 || VT == MVT::i1) {
19066       unsigned DestReg = 0;
19067       switch (Res.first) {
19068       default: break;
19069       case X86::AX: DestReg = X86::AL; break;
19070       case X86::DX: DestReg = X86::DL; break;
19071       case X86::CX: DestReg = X86::CL; break;
19072       case X86::BX: DestReg = X86::BL; break;
19073       }
19074       if (DestReg) {
19075         Res.first = DestReg;
19076         Res.second = &X86::GR8RegClass;
19077       }
19078     } else if (VT == MVT::i32 || VT == MVT::f32) {
19079       unsigned DestReg = 0;
19080       switch (Res.first) {
19081       default: break;
19082       case X86::AX: DestReg = X86::EAX; break;
19083       case X86::DX: DestReg = X86::EDX; break;
19084       case X86::CX: DestReg = X86::ECX; break;
19085       case X86::BX: DestReg = X86::EBX; break;
19086       case X86::SI: DestReg = X86::ESI; break;
19087       case X86::DI: DestReg = X86::EDI; break;
19088       case X86::BP: DestReg = X86::EBP; break;
19089       case X86::SP: DestReg = X86::ESP; break;
19090       }
19091       if (DestReg) {
19092         Res.first = DestReg;
19093         Res.second = &X86::GR32RegClass;
19094       }
19095     } else if (VT == MVT::i64 || VT == MVT::f64) {
19096       unsigned DestReg = 0;
19097       switch (Res.first) {
19098       default: break;
19099       case X86::AX: DestReg = X86::RAX; break;
19100       case X86::DX: DestReg = X86::RDX; break;
19101       case X86::CX: DestReg = X86::RCX; break;
19102       case X86::BX: DestReg = X86::RBX; break;
19103       case X86::SI: DestReg = X86::RSI; break;
19104       case X86::DI: DestReg = X86::RDI; break;
19105       case X86::BP: DestReg = X86::RBP; break;
19106       case X86::SP: DestReg = X86::RSP; break;
19107       }
19108       if (DestReg) {
19109         Res.first = DestReg;
19110         Res.second = &X86::GR64RegClass;
19111       }
19112     }
19113   } else if (Res.second == &X86::FR32RegClass ||
19114              Res.second == &X86::FR64RegClass ||
19115              Res.second == &X86::VR128RegClass ||
19116              Res.second == &X86::VR256RegClass ||
19117              Res.second == &X86::FR32XRegClass ||
19118              Res.second == &X86::FR64XRegClass ||
19119              Res.second == &X86::VR128XRegClass ||
19120              Res.second == &X86::VR256XRegClass ||
19121              Res.second == &X86::VR512RegClass) {
19122     // Handle references to XMM physical registers that got mapped into the
19123     // wrong class.  This can happen with constraints like {xmm0} where the
19124     // target independent register mapper will just pick the first match it can
19125     // find, ignoring the required type.
19126
19127     if (VT == MVT::f32 || VT == MVT::i32)
19128       Res.second = &X86::FR32RegClass;
19129     else if (VT == MVT::f64 || VT == MVT::i64)
19130       Res.second = &X86::FR64RegClass;
19131     else if (X86::VR128RegClass.hasType(VT))
19132       Res.second = &X86::VR128RegClass;
19133     else if (X86::VR256RegClass.hasType(VT))
19134       Res.second = &X86::VR256RegClass;
19135     else if (X86::VR512RegClass.hasType(VT))
19136       Res.second = &X86::VR512RegClass;
19137   }
19138
19139   return Res;
19140 }