ea78d9f88b055e36ceef79c90bff534e0090a487
[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 "X86CallingConv.h"
20 #include "X86InstrBuilder.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.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->isTargetMacho()) {
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())
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->isOSWindows() && !Subtarget->isTargetMacho())
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::FP_TO_SINT,         MVT::v8i16, Custom);
1154
1155     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1156     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1157     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1158     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1159
1160     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1161     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1162
1163     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1164
1165     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1172     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1173
1174     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1175
1176     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1177     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1178     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1180
1181     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1182     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1183     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1184
1185     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1186     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1187     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1189
1190     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1191     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1193     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1194     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1196     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1197     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1199     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1200     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1202
1203     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1204       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1205       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1206       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1208       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1209       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1210     }
1211
1212     if (Subtarget->hasInt256()) {
1213       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1214       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1215       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1217
1218       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1219       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1220       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1222
1223       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1224       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1225       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1226       // Don't lower v32i8 because there is no 128-bit byte mul
1227
1228       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1229
1230       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1231     } else {
1232       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1233       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1234       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1235       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1236
1237       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1238       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1239       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1240       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1241
1242       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1243       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1244       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1245       // Don't lower v32i8 because there is no 128-bit byte mul
1246     }
1247
1248     // In the customized shift lowering, the legal cases in AVX2 will be
1249     // recognized.
1250     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1251     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1252
1253     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1254     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1255
1256     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1257
1258     // Custom lower several nodes for 256-bit types.
1259     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1260              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1261       MVT VT = (MVT::SimpleValueType)i;
1262
1263       // Extract subvector is special because the value type
1264       // (result) is 128-bit but the source is 256-bit wide.
1265       if (VT.is128BitVector())
1266         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1267
1268       // Do not attempt to custom lower other non-256-bit vectors
1269       if (!VT.is256BitVector())
1270         continue;
1271
1272       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1273       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1274       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1275       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1276       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1277       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1278       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1279     }
1280
1281     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1282     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1283       MVT VT = (MVT::SimpleValueType)i;
1284
1285       // Do not attempt to promote non-256-bit vectors
1286       if (!VT.is256BitVector())
1287         continue;
1288
1289       setOperationAction(ISD::AND,    VT, Promote);
1290       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1291       setOperationAction(ISD::OR,     VT, Promote);
1292       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1293       setOperationAction(ISD::XOR,    VT, Promote);
1294       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1295       setOperationAction(ISD::LOAD,   VT, Promote);
1296       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1297       setOperationAction(ISD::SELECT, VT, Promote);
1298       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1299     }
1300   }
1301
1302   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1303     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1304     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1307
1308     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1309     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1310     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1311
1312     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1313     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1314     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1315     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1316     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1317     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1318     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1320     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1321     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1323
1324     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1326     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1327     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1329     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1330
1331     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1334     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1336     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1337     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1338     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1339     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1340
1341     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1342     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1343     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1345     if (Subtarget->is64Bit()) {
1346       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1347       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1348       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1349       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1350     }
1351     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1352     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1357     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1358     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1359
1360     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1361     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1362     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1363     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1364     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1365     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1366     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1367     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1368     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1369     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1370     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1371     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1372     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1373
1374     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1375     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1376     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1377     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1378     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1379     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1380
1381     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1382     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1383
1384     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1385
1386     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1387     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1388     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1389     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1390     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1391     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1392     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1393
1394     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1395     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1396
1397     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1398     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1399
1400     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1401
1402     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1403     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1404
1405     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1406     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1407
1408     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1409     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1410
1411     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1412     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1413     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1414     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1415     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1416     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1417
1418     // Custom lower several nodes.
1419     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1420              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1421       MVT VT = (MVT::SimpleValueType)i;
1422
1423       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1424       // Extract subvector is special because the value type
1425       // (result) is 256/128-bit but the source is 512-bit wide.
1426       if (VT.is128BitVector() || VT.is256BitVector())
1427         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1428
1429       if (VT.getVectorElementType() == MVT::i1)
1430         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1431
1432       // Do not attempt to custom lower other non-512-bit vectors
1433       if (!VT.is512BitVector())
1434         continue;
1435
1436       if ( EltSize >= 32) {
1437         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1438         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1439         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1440         setOperationAction(ISD::VSELECT,             VT, Legal);
1441         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1442         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1443         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1444       }
1445     }
1446     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1447       MVT VT = (MVT::SimpleValueType)i;
1448
1449       // Do not attempt to promote non-256-bit vectors
1450       if (!VT.is512BitVector())
1451         continue;
1452
1453       setOperationAction(ISD::SELECT, VT, Promote);
1454       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1455     }
1456   }// has  AVX-512
1457
1458   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1459   // of this type with custom code.
1460   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1461            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1462     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1463                        Custom);
1464   }
1465
1466   // We want to custom lower some of our intrinsics.
1467   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1468   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1469   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1470
1471   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1472   // handle type legalization for these operations here.
1473   //
1474   // FIXME: We really should do custom legalization for addition and
1475   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1476   // than generic legalization for 64-bit multiplication-with-overflow, though.
1477   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1478     // Add/Sub/Mul with overflow operations are custom lowered.
1479     MVT VT = IntVTs[i];
1480     setOperationAction(ISD::SADDO, VT, Custom);
1481     setOperationAction(ISD::UADDO, VT, Custom);
1482     setOperationAction(ISD::SSUBO, VT, Custom);
1483     setOperationAction(ISD::USUBO, VT, Custom);
1484     setOperationAction(ISD::SMULO, VT, Custom);
1485     setOperationAction(ISD::UMULO, VT, Custom);
1486   }
1487
1488   // There are no 8-bit 3-address imul/mul instructions
1489   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1490   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1491
1492   if (!Subtarget->is64Bit()) {
1493     // These libcalls are not available in 32-bit.
1494     setLibcallName(RTLIB::SHL_I128, 0);
1495     setLibcallName(RTLIB::SRL_I128, 0);
1496     setLibcallName(RTLIB::SRA_I128, 0);
1497   }
1498
1499   // Combine sin / cos into one node or libcall if possible.
1500   if (Subtarget->hasSinCos()) {
1501     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1502     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1503     if (Subtarget->isTargetDarwin()) {
1504       // For MacOSX, we don't want to the normal expansion of a libcall to
1505       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1506       // traffic.
1507       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1508       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1509     }
1510   }
1511
1512   // We have target-specific dag combine patterns for the following nodes:
1513   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1514   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1515   setTargetDAGCombine(ISD::VSELECT);
1516   setTargetDAGCombine(ISD::SELECT);
1517   setTargetDAGCombine(ISD::SHL);
1518   setTargetDAGCombine(ISD::SRA);
1519   setTargetDAGCombine(ISD::SRL);
1520   setTargetDAGCombine(ISD::OR);
1521   setTargetDAGCombine(ISD::AND);
1522   setTargetDAGCombine(ISD::ADD);
1523   setTargetDAGCombine(ISD::FADD);
1524   setTargetDAGCombine(ISD::FSUB);
1525   setTargetDAGCombine(ISD::FMA);
1526   setTargetDAGCombine(ISD::SUB);
1527   setTargetDAGCombine(ISD::LOAD);
1528   setTargetDAGCombine(ISD::STORE);
1529   setTargetDAGCombine(ISD::ZERO_EXTEND);
1530   setTargetDAGCombine(ISD::ANY_EXTEND);
1531   setTargetDAGCombine(ISD::SIGN_EXTEND);
1532   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1533   setTargetDAGCombine(ISD::TRUNCATE);
1534   setTargetDAGCombine(ISD::SINT_TO_FP);
1535   setTargetDAGCombine(ISD::SETCC);
1536   if (Subtarget->is64Bit())
1537     setTargetDAGCombine(ISD::MUL);
1538   setTargetDAGCombine(ISD::XOR);
1539
1540   computeRegisterProperties();
1541
1542   // On Darwin, -Os means optimize for size without hurting performance,
1543   // do not reduce the limit.
1544   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1545   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1546   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1547   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1548   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1549   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1550   setPrefLoopAlignment(4); // 2^4 bytes.
1551
1552   // Predictable cmov don't hurt on atom because it's in-order.
1553   PredictableSelectIsExpensive = !Subtarget->isAtom();
1554
1555   setPrefFunctionAlignment(4); // 2^4 bytes.
1556 }
1557
1558 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1559   if (!VT.isVector())
1560     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1561
1562   if (Subtarget->hasAVX512())
1563     switch(VT.getVectorNumElements()) {
1564     case  8: return MVT::v8i1;
1565     case 16: return MVT::v16i1;
1566   }
1567
1568   return VT.changeVectorElementTypeToInteger();
1569 }
1570
1571 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1572 /// the desired ByVal argument alignment.
1573 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1574   if (MaxAlign == 16)
1575     return;
1576   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1577     if (VTy->getBitWidth() == 128)
1578       MaxAlign = 16;
1579   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1580     unsigned EltAlign = 0;
1581     getMaxByValAlign(ATy->getElementType(), EltAlign);
1582     if (EltAlign > MaxAlign)
1583       MaxAlign = EltAlign;
1584   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1585     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1586       unsigned EltAlign = 0;
1587       getMaxByValAlign(STy->getElementType(i), EltAlign);
1588       if (EltAlign > MaxAlign)
1589         MaxAlign = EltAlign;
1590       if (MaxAlign == 16)
1591         break;
1592     }
1593   }
1594 }
1595
1596 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1597 /// function arguments in the caller parameter area. For X86, aggregates
1598 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1599 /// are at 4-byte boundaries.
1600 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1601   if (Subtarget->is64Bit()) {
1602     // Max of 8 and alignment of type.
1603     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1604     if (TyAlign > 8)
1605       return TyAlign;
1606     return 8;
1607   }
1608
1609   unsigned Align = 4;
1610   if (Subtarget->hasSSE1())
1611     getMaxByValAlign(Ty, Align);
1612   return Align;
1613 }
1614
1615 /// getOptimalMemOpType - Returns the target specific optimal type for load
1616 /// and store operations as a result of memset, memcpy, and memmove
1617 /// lowering. If DstAlign is zero that means it's safe to destination
1618 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1619 /// means there isn't a need to check it against alignment requirement,
1620 /// probably because the source does not need to be loaded. If 'IsMemset' is
1621 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1622 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1623 /// source is constant so it does not need to be loaded.
1624 /// It returns EVT::Other if the type should be determined using generic
1625 /// target-independent logic.
1626 EVT
1627 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1628                                        unsigned DstAlign, unsigned SrcAlign,
1629                                        bool IsMemset, bool ZeroMemset,
1630                                        bool MemcpyStrSrc,
1631                                        MachineFunction &MF) const {
1632   const Function *F = MF.getFunction();
1633   if ((!IsMemset || ZeroMemset) &&
1634       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1635                                        Attribute::NoImplicitFloat)) {
1636     if (Size >= 16 &&
1637         (Subtarget->isUnalignedMemAccessFast() ||
1638          ((DstAlign == 0 || DstAlign >= 16) &&
1639           (SrcAlign == 0 || SrcAlign >= 16)))) {
1640       if (Size >= 32) {
1641         if (Subtarget->hasInt256())
1642           return MVT::v8i32;
1643         if (Subtarget->hasFp256())
1644           return MVT::v8f32;
1645       }
1646       if (Subtarget->hasSSE2())
1647         return MVT::v4i32;
1648       if (Subtarget->hasSSE1())
1649         return MVT::v4f32;
1650     } else if (!MemcpyStrSrc && Size >= 8 &&
1651                !Subtarget->is64Bit() &&
1652                Subtarget->hasSSE2()) {
1653       // Do not use f64 to lower memcpy if source is string constant. It's
1654       // better to use i32 to avoid the loads.
1655       return MVT::f64;
1656     }
1657   }
1658   if (Subtarget->is64Bit() && Size >= 8)
1659     return MVT::i64;
1660   return MVT::i32;
1661 }
1662
1663 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1664   if (VT == MVT::f32)
1665     return X86ScalarSSEf32;
1666   else if (VT == MVT::f64)
1667     return X86ScalarSSEf64;
1668   return true;
1669 }
1670
1671 bool
1672 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1673   if (Fast)
1674     *Fast = Subtarget->isUnalignedMemAccessFast();
1675   return true;
1676 }
1677
1678 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1679 /// current function.  The returned value is a member of the
1680 /// MachineJumpTableInfo::JTEntryKind enum.
1681 unsigned X86TargetLowering::getJumpTableEncoding() const {
1682   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1683   // symbol.
1684   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1685       Subtarget->isPICStyleGOT())
1686     return MachineJumpTableInfo::EK_Custom32;
1687
1688   // Otherwise, use the normal jump table encoding heuristics.
1689   return TargetLowering::getJumpTableEncoding();
1690 }
1691
1692 const MCExpr *
1693 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1694                                              const MachineBasicBlock *MBB,
1695                                              unsigned uid,MCContext &Ctx) const{
1696   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1697          Subtarget->isPICStyleGOT());
1698   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1699   // entries.
1700   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1701                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1702 }
1703
1704 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1705 /// jumptable.
1706 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1707                                                     SelectionDAG &DAG) const {
1708   if (!Subtarget->is64Bit())
1709     // This doesn't have SDLoc associated with it, but is not really the
1710     // same as a Register.
1711     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1712   return Table;
1713 }
1714
1715 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1716 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1717 /// MCExpr.
1718 const MCExpr *X86TargetLowering::
1719 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1720                              MCContext &Ctx) const {
1721   // X86-64 uses RIP relative addressing based on the jump table label.
1722   if (Subtarget->isPICStyleRIPRel())
1723     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1724
1725   // Otherwise, the reference is relative to the PIC base.
1726   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1727 }
1728
1729 // FIXME: Why this routine is here? Move to RegInfo!
1730 std::pair<const TargetRegisterClass*, uint8_t>
1731 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1732   const TargetRegisterClass *RRC = 0;
1733   uint8_t Cost = 1;
1734   switch (VT.SimpleTy) {
1735   default:
1736     return TargetLowering::findRepresentativeClass(VT);
1737   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1738     RRC = Subtarget->is64Bit() ?
1739       (const TargetRegisterClass*)&X86::GR64RegClass :
1740       (const TargetRegisterClass*)&X86::GR32RegClass;
1741     break;
1742   case MVT::x86mmx:
1743     RRC = &X86::VR64RegClass;
1744     break;
1745   case MVT::f32: case MVT::f64:
1746   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1747   case MVT::v4f32: case MVT::v2f64:
1748   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1749   case MVT::v4f64:
1750     RRC = &X86::VR128RegClass;
1751     break;
1752   }
1753   return std::make_pair(RRC, Cost);
1754 }
1755
1756 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1757                                                unsigned &Offset) const {
1758   if (!Subtarget->isTargetLinux())
1759     return false;
1760
1761   if (Subtarget->is64Bit()) {
1762     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1763     Offset = 0x28;
1764     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1765       AddressSpace = 256;
1766     else
1767       AddressSpace = 257;
1768   } else {
1769     // %gs:0x14 on i386
1770     Offset = 0x14;
1771     AddressSpace = 256;
1772   }
1773   return true;
1774 }
1775
1776 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1777                                             unsigned DestAS) const {
1778   assert(SrcAS != DestAS && "Expected different address spaces!");
1779
1780   return SrcAS < 256 && DestAS < 256;
1781 }
1782
1783 //===----------------------------------------------------------------------===//
1784 //               Return Value Calling Convention Implementation
1785 //===----------------------------------------------------------------------===//
1786
1787 #include "X86GenCallingConv.inc"
1788
1789 bool
1790 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1791                                   MachineFunction &MF, bool isVarArg,
1792                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1793                         LLVMContext &Context) const {
1794   SmallVector<CCValAssign, 16> RVLocs;
1795   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1796                  RVLocs, Context);
1797   return CCInfo.CheckReturn(Outs, RetCC_X86);
1798 }
1799
1800 const uint16_t *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1801   static const uint16_t ScratchRegs[] = { X86::R11, 0 };
1802   return ScratchRegs;
1803 }
1804
1805 SDValue
1806 X86TargetLowering::LowerReturn(SDValue Chain,
1807                                CallingConv::ID CallConv, bool isVarArg,
1808                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1809                                const SmallVectorImpl<SDValue> &OutVals,
1810                                SDLoc dl, SelectionDAG &DAG) const {
1811   MachineFunction &MF = DAG.getMachineFunction();
1812   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1813
1814   SmallVector<CCValAssign, 16> RVLocs;
1815   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1816                  RVLocs, *DAG.getContext());
1817   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1818
1819   SDValue Flag;
1820   SmallVector<SDValue, 6> RetOps;
1821   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1822   // Operand #1 = Bytes To Pop
1823   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1824                    MVT::i16));
1825
1826   // Copy the result values into the output registers.
1827   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1828     CCValAssign &VA = RVLocs[i];
1829     assert(VA.isRegLoc() && "Can only return in registers!");
1830     SDValue ValToCopy = OutVals[i];
1831     EVT ValVT = ValToCopy.getValueType();
1832
1833     // Promote values to the appropriate types
1834     if (VA.getLocInfo() == CCValAssign::SExt)
1835       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1836     else if (VA.getLocInfo() == CCValAssign::ZExt)
1837       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1838     else if (VA.getLocInfo() == CCValAssign::AExt)
1839       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1840     else if (VA.getLocInfo() == CCValAssign::BCvt)
1841       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1842
1843     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1844            "Unexpected FP-extend for return value.");  
1845
1846     // If this is x86-64, and we disabled SSE, we can't return FP values,
1847     // or SSE or MMX vectors.
1848     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1849          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1850           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1851       report_fatal_error("SSE register return with SSE disabled");
1852     }
1853     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1854     // llvm-gcc has never done it right and no one has noticed, so this
1855     // should be OK for now.
1856     if (ValVT == MVT::f64 &&
1857         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1858       report_fatal_error("SSE2 register return with SSE2 disabled");
1859
1860     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1861     // the RET instruction and handled by the FP Stackifier.
1862     if (VA.getLocReg() == X86::ST0 ||
1863         VA.getLocReg() == X86::ST1) {
1864       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1865       // change the value to the FP stack register class.
1866       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1867         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1868       RetOps.push_back(ValToCopy);
1869       // Don't emit a copytoreg.
1870       continue;
1871     }
1872
1873     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1874     // which is returned in RAX / RDX.
1875     if (Subtarget->is64Bit()) {
1876       if (ValVT == MVT::x86mmx) {
1877         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1878           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1879           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1880                                   ValToCopy);
1881           // If we don't have SSE2 available, convert to v4f32 so the generated
1882           // register is legal.
1883           if (!Subtarget->hasSSE2())
1884             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1885         }
1886       }
1887     }
1888
1889     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1890     Flag = Chain.getValue(1);
1891     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1892   }
1893
1894   // The x86-64 ABIs require that for returning structs by value we copy
1895   // the sret argument into %rax/%eax (depending on ABI) for the return.
1896   // Win32 requires us to put the sret argument to %eax as well.
1897   // We saved the argument into a virtual register in the entry block,
1898   // so now we copy the value out and into %rax/%eax.
1899   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1900       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1901     MachineFunction &MF = DAG.getMachineFunction();
1902     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1903     unsigned Reg = FuncInfo->getSRetReturnReg();
1904     assert(Reg &&
1905            "SRetReturnReg should have been set in LowerFormalArguments().");
1906     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1907
1908     unsigned RetValReg
1909         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1910           X86::RAX : X86::EAX;
1911     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1912     Flag = Chain.getValue(1);
1913
1914     // RAX/EAX now acts like a return value.
1915     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1916   }
1917
1918   RetOps[0] = Chain;  // Update chain.
1919
1920   // Add the flag if we have it.
1921   if (Flag.getNode())
1922     RetOps.push_back(Flag);
1923
1924   return DAG.getNode(X86ISD::RET_FLAG, dl,
1925                      MVT::Other, &RetOps[0], RetOps.size());
1926 }
1927
1928 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1929   if (N->getNumValues() != 1)
1930     return false;
1931   if (!N->hasNUsesOfValue(1, 0))
1932     return false;
1933
1934   SDValue TCChain = Chain;
1935   SDNode *Copy = *N->use_begin();
1936   if (Copy->getOpcode() == ISD::CopyToReg) {
1937     // If the copy has a glue operand, we conservatively assume it isn't safe to
1938     // perform a tail call.
1939     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1940       return false;
1941     TCChain = Copy->getOperand(0);
1942   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1943     return false;
1944
1945   bool HasRet = false;
1946   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1947        UI != UE; ++UI) {
1948     if (UI->getOpcode() != X86ISD::RET_FLAG)
1949       return false;
1950     HasRet = true;
1951   }
1952
1953   if (!HasRet)
1954     return false;
1955
1956   Chain = TCChain;
1957   return true;
1958 }
1959
1960 MVT
1961 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1962                                             ISD::NodeType ExtendKind) const {
1963   MVT ReturnMVT;
1964   // TODO: Is this also valid on 32-bit?
1965   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1966     ReturnMVT = MVT::i8;
1967   else
1968     ReturnMVT = MVT::i32;
1969
1970   MVT MinVT = getRegisterType(ReturnMVT);
1971   return VT.bitsLT(MinVT) ? MinVT : VT;
1972 }
1973
1974 /// LowerCallResult - Lower the result values of a call into the
1975 /// appropriate copies out of appropriate physical registers.
1976 ///
1977 SDValue
1978 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1979                                    CallingConv::ID CallConv, bool isVarArg,
1980                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1981                                    SDLoc dl, SelectionDAG &DAG,
1982                                    SmallVectorImpl<SDValue> &InVals) const {
1983
1984   // Assign locations to each value returned by this call.
1985   SmallVector<CCValAssign, 16> RVLocs;
1986   bool Is64Bit = Subtarget->is64Bit();
1987   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1988                  getTargetMachine(), RVLocs, *DAG.getContext());
1989   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1990
1991   // Copy all of the result registers out of their specified physreg.
1992   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1993     CCValAssign &VA = RVLocs[i];
1994     EVT CopyVT = VA.getValVT();
1995
1996     // If this is x86-64, and we disabled SSE, we can't return FP values
1997     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1998         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1999       report_fatal_error("SSE register return with SSE disabled");
2000     }
2001
2002     SDValue Val;
2003
2004     // If this is a call to a function that returns an fp value on the floating
2005     // point stack, we must guarantee the value is popped from the stack, so
2006     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2007     // if the return value is not used. We use the FpPOP_RETVAL instruction
2008     // instead.
2009     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2010       // If we prefer to use the value in xmm registers, copy it out as f80 and
2011       // use a truncate to move it from fp stack reg to xmm reg.
2012       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2013       SDValue Ops[] = { Chain, InFlag };
2014       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2015                                          MVT::Other, MVT::Glue, Ops), 1);
2016       Val = Chain.getValue(0);
2017
2018       // Round the f80 to the right size, which also moves it to the appropriate
2019       // xmm register.
2020       if (CopyVT != VA.getValVT())
2021         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2022                           // This truncation won't change the value.
2023                           DAG.getIntPtrConstant(1));
2024     } else {
2025       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2026                                  CopyVT, InFlag).getValue(1);
2027       Val = Chain.getValue(0);
2028     }
2029     InFlag = Chain.getValue(2);
2030     InVals.push_back(Val);
2031   }
2032
2033   return Chain;
2034 }
2035
2036 //===----------------------------------------------------------------------===//
2037 //                C & StdCall & Fast Calling Convention implementation
2038 //===----------------------------------------------------------------------===//
2039 //  StdCall calling convention seems to be standard for many Windows' API
2040 //  routines and around. It differs from C calling convention just a little:
2041 //  callee should clean up the stack, not caller. Symbols should be also
2042 //  decorated in some fancy way :) It doesn't support any vector arguments.
2043 //  For info on fast calling convention see Fast Calling Convention (tail call)
2044 //  implementation LowerX86_32FastCCCallTo.
2045
2046 /// CallIsStructReturn - Determines whether a call uses struct return
2047 /// semantics.
2048 enum StructReturnType {
2049   NotStructReturn,
2050   RegStructReturn,
2051   StackStructReturn
2052 };
2053 static StructReturnType
2054 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2055   if (Outs.empty())
2056     return NotStructReturn;
2057
2058   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2059   if (!Flags.isSRet())
2060     return NotStructReturn;
2061   if (Flags.isInReg())
2062     return RegStructReturn;
2063   return StackStructReturn;
2064 }
2065
2066 /// ArgsAreStructReturn - Determines whether a function uses struct
2067 /// return semantics.
2068 static StructReturnType
2069 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2070   if (Ins.empty())
2071     return NotStructReturn;
2072
2073   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2074   if (!Flags.isSRet())
2075     return NotStructReturn;
2076   if (Flags.isInReg())
2077     return RegStructReturn;
2078   return StackStructReturn;
2079 }
2080
2081 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2082 /// by "Src" to address "Dst" with size and alignment information specified by
2083 /// the specific parameter attribute. The copy will be passed as a byval
2084 /// function parameter.
2085 static SDValue
2086 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2087                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2088                           SDLoc dl) {
2089   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2090
2091   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2092                        /*isVolatile*/false, /*AlwaysInline=*/true,
2093                        MachinePointerInfo(), MachinePointerInfo());
2094 }
2095
2096 /// IsTailCallConvention - Return true if the calling convention is one that
2097 /// supports tail call optimization.
2098 static bool IsTailCallConvention(CallingConv::ID CC) {
2099   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2100           CC == CallingConv::HiPE);
2101 }
2102
2103 /// \brief Return true if the calling convention is a C calling convention.
2104 static bool IsCCallConvention(CallingConv::ID CC) {
2105   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2106           CC == CallingConv::X86_64_SysV);
2107 }
2108
2109 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2110   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2111     return false;
2112
2113   CallSite CS(CI);
2114   CallingConv::ID CalleeCC = CS.getCallingConv();
2115   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2116     return false;
2117
2118   return true;
2119 }
2120
2121 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2122 /// a tailcall target by changing its ABI.
2123 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2124                                    bool GuaranteedTailCallOpt) {
2125   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2126 }
2127
2128 SDValue
2129 X86TargetLowering::LowerMemArgument(SDValue Chain,
2130                                     CallingConv::ID CallConv,
2131                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2132                                     SDLoc dl, SelectionDAG &DAG,
2133                                     const CCValAssign &VA,
2134                                     MachineFrameInfo *MFI,
2135                                     unsigned i) const {
2136   // Create the nodes corresponding to a load from this parameter slot.
2137   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2138   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2139                               getTargetMachine().Options.GuaranteedTailCallOpt);
2140   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2141   EVT ValVT;
2142
2143   // If value is passed by pointer we have address passed instead of the value
2144   // itself.
2145   if (VA.getLocInfo() == CCValAssign::Indirect)
2146     ValVT = VA.getLocVT();
2147   else
2148     ValVT = VA.getValVT();
2149
2150   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2151   // changed with more analysis.
2152   // In case of tail call optimization mark all arguments mutable. Since they
2153   // could be overwritten by lowering of arguments in case of a tail call.
2154   if (Flags.isByVal()) {
2155     unsigned Bytes = Flags.getByValSize();
2156     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2157     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2158     return DAG.getFrameIndex(FI, getPointerTy());
2159   } else {
2160     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2161                                     VA.getLocMemOffset(), isImmutable);
2162     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2163     return DAG.getLoad(ValVT, dl, Chain, FIN,
2164                        MachinePointerInfo::getFixedStack(FI),
2165                        false, false, false, 0);
2166   }
2167 }
2168
2169 SDValue
2170 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2171                                         CallingConv::ID CallConv,
2172                                         bool isVarArg,
2173                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2174                                         SDLoc dl,
2175                                         SelectionDAG &DAG,
2176                                         SmallVectorImpl<SDValue> &InVals)
2177                                           const {
2178   MachineFunction &MF = DAG.getMachineFunction();
2179   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2180
2181   const Function* Fn = MF.getFunction();
2182   if (Fn->hasExternalLinkage() &&
2183       Subtarget->isTargetCygMing() &&
2184       Fn->getName() == "main")
2185     FuncInfo->setForceFramePointer(true);
2186
2187   MachineFrameInfo *MFI = MF.getFrameInfo();
2188   bool Is64Bit = Subtarget->is64Bit();
2189   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2190
2191   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2192          "Var args not supported with calling convention fastcc, ghc or hipe");
2193
2194   // Assign locations to all of the incoming arguments.
2195   SmallVector<CCValAssign, 16> ArgLocs;
2196   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2197                  ArgLocs, *DAG.getContext());
2198
2199   // Allocate shadow area for Win64
2200   if (IsWin64)
2201     CCInfo.AllocateStack(32, 8);
2202
2203   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2204
2205   unsigned LastVal = ~0U;
2206   SDValue ArgValue;
2207   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2208     CCValAssign &VA = ArgLocs[i];
2209     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2210     // places.
2211     assert(VA.getValNo() != LastVal &&
2212            "Don't support value assigned to multiple locs yet");
2213     (void)LastVal;
2214     LastVal = VA.getValNo();
2215
2216     if (VA.isRegLoc()) {
2217       EVT RegVT = VA.getLocVT();
2218       const TargetRegisterClass *RC;
2219       if (RegVT == MVT::i32)
2220         RC = &X86::GR32RegClass;
2221       else if (Is64Bit && RegVT == MVT::i64)
2222         RC = &X86::GR64RegClass;
2223       else if (RegVT == MVT::f32)
2224         RC = &X86::FR32RegClass;
2225       else if (RegVT == MVT::f64)
2226         RC = &X86::FR64RegClass;
2227       else if (RegVT.is512BitVector())
2228         RC = &X86::VR512RegClass;
2229       else if (RegVT.is256BitVector())
2230         RC = &X86::VR256RegClass;
2231       else if (RegVT.is128BitVector())
2232         RC = &X86::VR128RegClass;
2233       else if (RegVT == MVT::x86mmx)
2234         RC = &X86::VR64RegClass;
2235       else if (RegVT == MVT::i1)
2236         RC = &X86::VK1RegClass;
2237       else if (RegVT == MVT::v8i1)
2238         RC = &X86::VK8RegClass;
2239       else if (RegVT == MVT::v16i1)
2240         RC = &X86::VK16RegClass;
2241       else
2242         llvm_unreachable("Unknown argument type!");
2243
2244       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2245       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2246
2247       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2248       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2249       // right size.
2250       if (VA.getLocInfo() == CCValAssign::SExt)
2251         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2252                                DAG.getValueType(VA.getValVT()));
2253       else if (VA.getLocInfo() == CCValAssign::ZExt)
2254         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2255                                DAG.getValueType(VA.getValVT()));
2256       else if (VA.getLocInfo() == CCValAssign::BCvt)
2257         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2258
2259       if (VA.isExtInLoc()) {
2260         // Handle MMX values passed in XMM regs.
2261         if (RegVT.isVector())
2262           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2263         else
2264           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2265       }
2266     } else {
2267       assert(VA.isMemLoc());
2268       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2269     }
2270
2271     // If value is passed via pointer - do a load.
2272     if (VA.getLocInfo() == CCValAssign::Indirect)
2273       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2274                              MachinePointerInfo(), false, false, false, 0);
2275
2276     InVals.push_back(ArgValue);
2277   }
2278
2279   // The x86-64 ABIs require that for returning structs by value we copy
2280   // the sret argument into %rax/%eax (depending on ABI) for the return.
2281   // Win32 requires us to put the sret argument to %eax as well.
2282   // Save the argument into a virtual register so that we can access it
2283   // from the return points.
2284   if (MF.getFunction()->hasStructRetAttr() &&
2285       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2286     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2287     unsigned Reg = FuncInfo->getSRetReturnReg();
2288     if (!Reg) {
2289       MVT PtrTy = getPointerTy();
2290       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2291       FuncInfo->setSRetReturnReg(Reg);
2292     }
2293     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2294     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2295   }
2296
2297   unsigned StackSize = CCInfo.getNextStackOffset();
2298   // Align stack specially for tail calls.
2299   if (FuncIsMadeTailCallSafe(CallConv,
2300                              MF.getTarget().Options.GuaranteedTailCallOpt))
2301     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2302
2303   // If the function takes variable number of arguments, make a frame index for
2304   // the start of the first vararg value... for expansion of llvm.va_start.
2305   if (isVarArg) {
2306     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2307                     CallConv != CallingConv::X86_ThisCall)) {
2308       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2309     }
2310     if (Is64Bit) {
2311       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2312
2313       // FIXME: We should really autogenerate these arrays
2314       static const uint16_t GPR64ArgRegsWin64[] = {
2315         X86::RCX, X86::RDX, X86::R8,  X86::R9
2316       };
2317       static const uint16_t GPR64ArgRegs64Bit[] = {
2318         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2319       };
2320       static const uint16_t XMMArgRegs64Bit[] = {
2321         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2322         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2323       };
2324       const uint16_t *GPR64ArgRegs;
2325       unsigned NumXMMRegs = 0;
2326
2327       if (IsWin64) {
2328         // The XMM registers which might contain var arg parameters are shadowed
2329         // in their paired GPR.  So we only need to save the GPR to their home
2330         // slots.
2331         TotalNumIntRegs = 4;
2332         GPR64ArgRegs = GPR64ArgRegsWin64;
2333       } else {
2334         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2335         GPR64ArgRegs = GPR64ArgRegs64Bit;
2336
2337         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2338                                                 TotalNumXMMRegs);
2339       }
2340       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2341                                                        TotalNumIntRegs);
2342
2343       bool NoImplicitFloatOps = Fn->getAttributes().
2344         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2345       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2346              "SSE register cannot be used when SSE is disabled!");
2347       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2348                NoImplicitFloatOps) &&
2349              "SSE register cannot be used when SSE is disabled!");
2350       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2351           !Subtarget->hasSSE1())
2352         // Kernel mode asks for SSE to be disabled, so don't push them
2353         // on the stack.
2354         TotalNumXMMRegs = 0;
2355
2356       if (IsWin64) {
2357         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2358         // Get to the caller-allocated home save location.  Add 8 to account
2359         // for the return address.
2360         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2361         FuncInfo->setRegSaveFrameIndex(
2362           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2363         // Fixup to set vararg frame on shadow area (4 x i64).
2364         if (NumIntRegs < 4)
2365           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2366       } else {
2367         // For X86-64, if there are vararg parameters that are passed via
2368         // registers, then we must store them to their spots on the stack so
2369         // they may be loaded by deferencing the result of va_next.
2370         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2371         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2372         FuncInfo->setRegSaveFrameIndex(
2373           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2374                                false));
2375       }
2376
2377       // Store the integer parameter registers.
2378       SmallVector<SDValue, 8> MemOps;
2379       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2380                                         getPointerTy());
2381       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2382       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2383         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2384                                   DAG.getIntPtrConstant(Offset));
2385         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2386                                      &X86::GR64RegClass);
2387         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2388         SDValue Store =
2389           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2390                        MachinePointerInfo::getFixedStack(
2391                          FuncInfo->getRegSaveFrameIndex(), Offset),
2392                        false, false, 0);
2393         MemOps.push_back(Store);
2394         Offset += 8;
2395       }
2396
2397       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2398         // Now store the XMM (fp + vector) parameter registers.
2399         SmallVector<SDValue, 11> SaveXMMOps;
2400         SaveXMMOps.push_back(Chain);
2401
2402         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2403         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2404         SaveXMMOps.push_back(ALVal);
2405
2406         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2407                                FuncInfo->getRegSaveFrameIndex()));
2408         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2409                                FuncInfo->getVarArgsFPOffset()));
2410
2411         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2412           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2413                                        &X86::VR128RegClass);
2414           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2415           SaveXMMOps.push_back(Val);
2416         }
2417         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2418                                      MVT::Other,
2419                                      &SaveXMMOps[0], SaveXMMOps.size()));
2420       }
2421
2422       if (!MemOps.empty())
2423         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2424                             &MemOps[0], MemOps.size());
2425     }
2426   }
2427
2428   // Some CCs need callee pop.
2429   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2430                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2431     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2432   } else {
2433     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2434     // If this is an sret function, the return should pop the hidden pointer.
2435     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2436         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2437         argsAreStructReturn(Ins) == StackStructReturn)
2438       FuncInfo->setBytesToPopOnReturn(4);
2439   }
2440
2441   if (!Is64Bit) {
2442     // RegSaveFrameIndex is X86-64 only.
2443     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2444     if (CallConv == CallingConv::X86_FastCall ||
2445         CallConv == CallingConv::X86_ThisCall)
2446       // fastcc functions can't have varargs.
2447       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2448   }
2449
2450   FuncInfo->setArgumentStackSize(StackSize);
2451
2452   return Chain;
2453 }
2454
2455 SDValue
2456 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2457                                     SDValue StackPtr, SDValue Arg,
2458                                     SDLoc dl, SelectionDAG &DAG,
2459                                     const CCValAssign &VA,
2460                                     ISD::ArgFlagsTy Flags) const {
2461   unsigned LocMemOffset = VA.getLocMemOffset();
2462   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2463   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2464   if (Flags.isByVal())
2465     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2466
2467   return DAG.getStore(Chain, dl, Arg, PtrOff,
2468                       MachinePointerInfo::getStack(LocMemOffset),
2469                       false, false, 0);
2470 }
2471
2472 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2473 /// optimization is performed and it is required.
2474 SDValue
2475 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2476                                            SDValue &OutRetAddr, SDValue Chain,
2477                                            bool IsTailCall, bool Is64Bit,
2478                                            int FPDiff, SDLoc dl) const {
2479   // Adjust the Return address stack slot.
2480   EVT VT = getPointerTy();
2481   OutRetAddr = getReturnAddressFrameIndex(DAG);
2482
2483   // Load the "old" Return address.
2484   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2485                            false, false, false, 0);
2486   return SDValue(OutRetAddr.getNode(), 1);
2487 }
2488
2489 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2490 /// optimization is performed and it is required (FPDiff!=0).
2491 static SDValue
2492 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2493                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2494                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2495   // Store the return address to the appropriate stack slot.
2496   if (!FPDiff) return Chain;
2497   // Calculate the new stack slot for the return address.
2498   int NewReturnAddrFI =
2499     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2500                                          false);
2501   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2502   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2503                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2504                        false, false, 0);
2505   return Chain;
2506 }
2507
2508 SDValue
2509 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2510                              SmallVectorImpl<SDValue> &InVals) const {
2511   SelectionDAG &DAG                     = CLI.DAG;
2512   SDLoc &dl                             = CLI.DL;
2513   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2514   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2515   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2516   SDValue Chain                         = CLI.Chain;
2517   SDValue Callee                        = CLI.Callee;
2518   CallingConv::ID CallConv              = CLI.CallConv;
2519   bool &isTailCall                      = CLI.IsTailCall;
2520   bool isVarArg                         = CLI.IsVarArg;
2521
2522   MachineFunction &MF = DAG.getMachineFunction();
2523   bool Is64Bit        = Subtarget->is64Bit();
2524   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2525   StructReturnType SR = callIsStructReturn(Outs);
2526   bool IsSibcall      = false;
2527
2528   if (MF.getTarget().Options.DisableTailCalls)
2529     isTailCall = false;
2530
2531   if (isTailCall) {
2532     // Check if it's really possible to do a tail call.
2533     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2534                     isVarArg, SR != NotStructReturn,
2535                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2536                     Outs, OutVals, Ins, DAG);
2537
2538     // Sibcalls are automatically detected tailcalls which do not require
2539     // ABI changes.
2540     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2541       IsSibcall = true;
2542
2543     if (isTailCall)
2544       ++NumTailCalls;
2545   }
2546
2547   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2548          "Var args not supported with calling convention fastcc, ghc or hipe");
2549
2550   // Analyze operands of the call, assigning locations to each operand.
2551   SmallVector<CCValAssign, 16> ArgLocs;
2552   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2553                  ArgLocs, *DAG.getContext());
2554
2555   // Allocate shadow area for Win64
2556   if (IsWin64)
2557     CCInfo.AllocateStack(32, 8);
2558
2559   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2560
2561   // Get a count of how many bytes are to be pushed on the stack.
2562   unsigned NumBytes = CCInfo.getNextStackOffset();
2563   if (IsSibcall)
2564     // This is a sibcall. The memory operands are available in caller's
2565     // own caller's stack.
2566     NumBytes = 0;
2567   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2568            IsTailCallConvention(CallConv))
2569     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2570
2571   int FPDiff = 0;
2572   if (isTailCall && !IsSibcall) {
2573     // Lower arguments at fp - stackoffset + fpdiff.
2574     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2575     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2576
2577     FPDiff = NumBytesCallerPushed - NumBytes;
2578
2579     // Set the delta of movement of the returnaddr stackslot.
2580     // But only set if delta is greater than previous delta.
2581     if (FPDiff < X86Info->getTCReturnAddrDelta())
2582       X86Info->setTCReturnAddrDelta(FPDiff);
2583   }
2584
2585   if (!IsSibcall)
2586     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2587                                  dl);
2588
2589   SDValue RetAddrFrIdx;
2590   // Load return address for tail calls.
2591   if (isTailCall && FPDiff)
2592     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2593                                     Is64Bit, FPDiff, dl);
2594
2595   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2596   SmallVector<SDValue, 8> MemOpChains;
2597   SDValue StackPtr;
2598
2599   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2600   // of tail call optimization arguments are handle later.
2601   const X86RegisterInfo *RegInfo =
2602     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2603   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2604     CCValAssign &VA = ArgLocs[i];
2605     EVT RegVT = VA.getLocVT();
2606     SDValue Arg = OutVals[i];
2607     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2608     bool isByVal = Flags.isByVal();
2609
2610     // Promote the value if needed.
2611     switch (VA.getLocInfo()) {
2612     default: llvm_unreachable("Unknown loc info!");
2613     case CCValAssign::Full: break;
2614     case CCValAssign::SExt:
2615       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2616       break;
2617     case CCValAssign::ZExt:
2618       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2619       break;
2620     case CCValAssign::AExt:
2621       if (RegVT.is128BitVector()) {
2622         // Special case: passing MMX values in XMM registers.
2623         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2624         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2625         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2626       } else
2627         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2628       break;
2629     case CCValAssign::BCvt:
2630       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2631       break;
2632     case CCValAssign::Indirect: {
2633       // Store the argument.
2634       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2635       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2636       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2637                            MachinePointerInfo::getFixedStack(FI),
2638                            false, false, 0);
2639       Arg = SpillSlot;
2640       break;
2641     }
2642     }
2643
2644     if (VA.isRegLoc()) {
2645       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2646       if (isVarArg && IsWin64) {
2647         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2648         // shadow reg if callee is a varargs function.
2649         unsigned ShadowReg = 0;
2650         switch (VA.getLocReg()) {
2651         case X86::XMM0: ShadowReg = X86::RCX; break;
2652         case X86::XMM1: ShadowReg = X86::RDX; break;
2653         case X86::XMM2: ShadowReg = X86::R8; break;
2654         case X86::XMM3: ShadowReg = X86::R9; break;
2655         }
2656         if (ShadowReg)
2657           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2658       }
2659     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2660       assert(VA.isMemLoc());
2661       if (StackPtr.getNode() == 0)
2662         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2663                                       getPointerTy());
2664       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2665                                              dl, DAG, VA, Flags));
2666     }
2667   }
2668
2669   if (!MemOpChains.empty())
2670     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2671                         &MemOpChains[0], MemOpChains.size());
2672
2673   if (Subtarget->isPICStyleGOT()) {
2674     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2675     // GOT pointer.
2676     if (!isTailCall) {
2677       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2678                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2679     } else {
2680       // If we are tail calling and generating PIC/GOT style code load the
2681       // address of the callee into ECX. The value in ecx is used as target of
2682       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2683       // for tail calls on PIC/GOT architectures. Normally we would just put the
2684       // address of GOT into ebx and then call target@PLT. But for tail calls
2685       // ebx would be restored (since ebx is callee saved) before jumping to the
2686       // target@PLT.
2687
2688       // Note: The actual moving to ECX is done further down.
2689       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2690       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2691           !G->getGlobal()->hasProtectedVisibility())
2692         Callee = LowerGlobalAddress(Callee, DAG);
2693       else if (isa<ExternalSymbolSDNode>(Callee))
2694         Callee = LowerExternalSymbol(Callee, DAG);
2695     }
2696   }
2697
2698   if (Is64Bit && isVarArg && !IsWin64) {
2699     // From AMD64 ABI document:
2700     // For calls that may call functions that use varargs or stdargs
2701     // (prototype-less calls or calls to functions containing ellipsis (...) in
2702     // the declaration) %al is used as hidden argument to specify the number
2703     // of SSE registers used. The contents of %al do not need to match exactly
2704     // the number of registers, but must be an ubound on the number of SSE
2705     // registers used and is in the range 0 - 8 inclusive.
2706
2707     // Count the number of XMM registers allocated.
2708     static const uint16_t XMMArgRegs[] = {
2709       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2710       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2711     };
2712     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2713     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2714            && "SSE registers cannot be used when SSE is disabled");
2715
2716     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2717                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2718   }
2719
2720   // For tail calls lower the arguments to the 'real' stack slot.
2721   if (isTailCall) {
2722     // Force all the incoming stack arguments to be loaded from the stack
2723     // before any new outgoing arguments are stored to the stack, because the
2724     // outgoing stack slots may alias the incoming argument stack slots, and
2725     // the alias isn't otherwise explicit. This is slightly more conservative
2726     // than necessary, because it means that each store effectively depends
2727     // on every argument instead of just those arguments it would clobber.
2728     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2729
2730     SmallVector<SDValue, 8> MemOpChains2;
2731     SDValue FIN;
2732     int FI = 0;
2733     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2734       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2735         CCValAssign &VA = ArgLocs[i];
2736         if (VA.isRegLoc())
2737           continue;
2738         assert(VA.isMemLoc());
2739         SDValue Arg = OutVals[i];
2740         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2741         // Create frame index.
2742         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2743         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2744         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2745         FIN = DAG.getFrameIndex(FI, getPointerTy());
2746
2747         if (Flags.isByVal()) {
2748           // Copy relative to framepointer.
2749           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2750           if (StackPtr.getNode() == 0)
2751             StackPtr = DAG.getCopyFromReg(Chain, dl,
2752                                           RegInfo->getStackRegister(),
2753                                           getPointerTy());
2754           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2755
2756           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2757                                                            ArgChain,
2758                                                            Flags, DAG, dl));
2759         } else {
2760           // Store relative to framepointer.
2761           MemOpChains2.push_back(
2762             DAG.getStore(ArgChain, dl, Arg, FIN,
2763                          MachinePointerInfo::getFixedStack(FI),
2764                          false, false, 0));
2765         }
2766       }
2767     }
2768
2769     if (!MemOpChains2.empty())
2770       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2771                           &MemOpChains2[0], MemOpChains2.size());
2772
2773     // Store the return address to the appropriate stack slot.
2774     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2775                                      getPointerTy(), RegInfo->getSlotSize(),
2776                                      FPDiff, dl);
2777   }
2778
2779   // Build a sequence of copy-to-reg nodes chained together with token chain
2780   // and flag operands which copy the outgoing args into registers.
2781   SDValue InFlag;
2782   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2783     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2784                              RegsToPass[i].second, InFlag);
2785     InFlag = Chain.getValue(1);
2786   }
2787
2788   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2789     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2790     // In the 64-bit large code model, we have to make all calls
2791     // through a register, since the call instruction's 32-bit
2792     // pc-relative offset may not be large enough to hold the whole
2793     // address.
2794   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2795     // If the callee is a GlobalAddress node (quite common, every direct call
2796     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2797     // it.
2798
2799     // We should use extra load for direct calls to dllimported functions in
2800     // non-JIT mode.
2801     const GlobalValue *GV = G->getGlobal();
2802     if (!GV->hasDLLImportStorageClass()) {
2803       unsigned char OpFlags = 0;
2804       bool ExtraLoad = false;
2805       unsigned WrapperKind = ISD::DELETED_NODE;
2806
2807       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2808       // external symbols most go through the PLT in PIC mode.  If the symbol
2809       // has hidden or protected visibility, or if it is static or local, then
2810       // we don't need to use the PLT - we can directly call it.
2811       if (Subtarget->isTargetELF() &&
2812           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2813           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2814         OpFlags = X86II::MO_PLT;
2815       } else if (Subtarget->isPICStyleStubAny() &&
2816                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2817                  (!Subtarget->getTargetTriple().isMacOSX() ||
2818                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2819         // PC-relative references to external symbols should go through $stub,
2820         // unless we're building with the leopard linker or later, which
2821         // automatically synthesizes these stubs.
2822         OpFlags = X86II::MO_DARWIN_STUB;
2823       } else if (Subtarget->isPICStyleRIPRel() &&
2824                  isa<Function>(GV) &&
2825                  cast<Function>(GV)->getAttributes().
2826                    hasAttribute(AttributeSet::FunctionIndex,
2827                                 Attribute::NonLazyBind)) {
2828         // If the function is marked as non-lazy, generate an indirect call
2829         // which loads from the GOT directly. This avoids runtime overhead
2830         // at the cost of eager binding (and one extra byte of encoding).
2831         OpFlags = X86II::MO_GOTPCREL;
2832         WrapperKind = X86ISD::WrapperRIP;
2833         ExtraLoad = true;
2834       }
2835
2836       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2837                                           G->getOffset(), OpFlags);
2838
2839       // Add a wrapper if needed.
2840       if (WrapperKind != ISD::DELETED_NODE)
2841         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2842       // Add extra indirection if needed.
2843       if (ExtraLoad)
2844         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2845                              MachinePointerInfo::getGOT(),
2846                              false, false, false, 0);
2847     }
2848   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2849     unsigned char OpFlags = 0;
2850
2851     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2852     // external symbols should go through the PLT.
2853     if (Subtarget->isTargetELF() &&
2854         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2855       OpFlags = X86II::MO_PLT;
2856     } else if (Subtarget->isPICStyleStubAny() &&
2857                (!Subtarget->getTargetTriple().isMacOSX() ||
2858                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2859       // PC-relative references to external symbols should go through $stub,
2860       // unless we're building with the leopard linker or later, which
2861       // automatically synthesizes these stubs.
2862       OpFlags = X86II::MO_DARWIN_STUB;
2863     }
2864
2865     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2866                                          OpFlags);
2867   }
2868
2869   // Returns a chain & a flag for retval copy to use.
2870   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2871   SmallVector<SDValue, 8> Ops;
2872
2873   if (!IsSibcall && isTailCall) {
2874     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2875                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2876     InFlag = Chain.getValue(1);
2877   }
2878
2879   Ops.push_back(Chain);
2880   Ops.push_back(Callee);
2881
2882   if (isTailCall)
2883     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2884
2885   // Add argument registers to the end of the list so that they are known live
2886   // into the call.
2887   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2888     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2889                                   RegsToPass[i].second.getValueType()));
2890
2891   // Add a register mask operand representing the call-preserved registers.
2892   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2893   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2894   assert(Mask && "Missing call preserved mask for calling convention");
2895   Ops.push_back(DAG.getRegisterMask(Mask));
2896
2897   if (InFlag.getNode())
2898     Ops.push_back(InFlag);
2899
2900   if (isTailCall) {
2901     // We used to do:
2902     //// If this is the first return lowered for this function, add the regs
2903     //// to the liveout set for the function.
2904     // This isn't right, although it's probably harmless on x86; liveouts
2905     // should be computed from returns not tail calls.  Consider a void
2906     // function making a tail call to a function returning int.
2907     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2908   }
2909
2910   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2911   InFlag = Chain.getValue(1);
2912
2913   // Create the CALLSEQ_END node.
2914   unsigned NumBytesForCalleeToPush;
2915   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2916                        getTargetMachine().Options.GuaranteedTailCallOpt))
2917     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2918   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2919            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2920            SR == StackStructReturn)
2921     // If this is a call to a struct-return function, the callee
2922     // pops the hidden struct pointer, so we have to push it back.
2923     // This is common for Darwin/X86, Linux & Mingw32 targets.
2924     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2925     NumBytesForCalleeToPush = 4;
2926   else
2927     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2928
2929   // Returns a flag for retval copy to use.
2930   if (!IsSibcall) {
2931     Chain = DAG.getCALLSEQ_END(Chain,
2932                                DAG.getIntPtrConstant(NumBytes, true),
2933                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2934                                                      true),
2935                                InFlag, dl);
2936     InFlag = Chain.getValue(1);
2937   }
2938
2939   // Handle result values, copying them out of physregs into vregs that we
2940   // return.
2941   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2942                          Ins, dl, DAG, InVals);
2943 }
2944
2945 //===----------------------------------------------------------------------===//
2946 //                Fast Calling Convention (tail call) implementation
2947 //===----------------------------------------------------------------------===//
2948
2949 //  Like std call, callee cleans arguments, convention except that ECX is
2950 //  reserved for storing the tail called function address. Only 2 registers are
2951 //  free for argument passing (inreg). Tail call optimization is performed
2952 //  provided:
2953 //                * tailcallopt is enabled
2954 //                * caller/callee are fastcc
2955 //  On X86_64 architecture with GOT-style position independent code only local
2956 //  (within module) calls are supported at the moment.
2957 //  To keep the stack aligned according to platform abi the function
2958 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2959 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2960 //  If a tail called function callee has more arguments than the caller the
2961 //  caller needs to make sure that there is room to move the RETADDR to. This is
2962 //  achieved by reserving an area the size of the argument delta right after the
2963 //  original REtADDR, but before the saved framepointer or the spilled registers
2964 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2965 //  stack layout:
2966 //    arg1
2967 //    arg2
2968 //    RETADDR
2969 //    [ new RETADDR
2970 //      move area ]
2971 //    (possible EBP)
2972 //    ESI
2973 //    EDI
2974 //    local1 ..
2975
2976 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2977 /// for a 16 byte align requirement.
2978 unsigned
2979 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2980                                                SelectionDAG& DAG) const {
2981   MachineFunction &MF = DAG.getMachineFunction();
2982   const TargetMachine &TM = MF.getTarget();
2983   const X86RegisterInfo *RegInfo =
2984     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2985   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2986   unsigned StackAlignment = TFI.getStackAlignment();
2987   uint64_t AlignMask = StackAlignment - 1;
2988   int64_t Offset = StackSize;
2989   unsigned SlotSize = RegInfo->getSlotSize();
2990   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2991     // Number smaller than 12 so just add the difference.
2992     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2993   } else {
2994     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2995     Offset = ((~AlignMask) & Offset) + StackAlignment +
2996       (StackAlignment-SlotSize);
2997   }
2998   return Offset;
2999 }
3000
3001 /// MatchingStackOffset - Return true if the given stack call argument is
3002 /// already available in the same position (relatively) of the caller's
3003 /// incoming argument stack.
3004 static
3005 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3006                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3007                          const X86InstrInfo *TII) {
3008   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3009   int FI = INT_MAX;
3010   if (Arg.getOpcode() == ISD::CopyFromReg) {
3011     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3012     if (!TargetRegisterInfo::isVirtualRegister(VR))
3013       return false;
3014     MachineInstr *Def = MRI->getVRegDef(VR);
3015     if (!Def)
3016       return false;
3017     if (!Flags.isByVal()) {
3018       if (!TII->isLoadFromStackSlot(Def, FI))
3019         return false;
3020     } else {
3021       unsigned Opcode = Def->getOpcode();
3022       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3023           Def->getOperand(1).isFI()) {
3024         FI = Def->getOperand(1).getIndex();
3025         Bytes = Flags.getByValSize();
3026       } else
3027         return false;
3028     }
3029   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3030     if (Flags.isByVal())
3031       // ByVal argument is passed in as a pointer but it's now being
3032       // dereferenced. e.g.
3033       // define @foo(%struct.X* %A) {
3034       //   tail call @bar(%struct.X* byval %A)
3035       // }
3036       return false;
3037     SDValue Ptr = Ld->getBasePtr();
3038     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3039     if (!FINode)
3040       return false;
3041     FI = FINode->getIndex();
3042   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3043     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3044     FI = FINode->getIndex();
3045     Bytes = Flags.getByValSize();
3046   } else
3047     return false;
3048
3049   assert(FI != INT_MAX);
3050   if (!MFI->isFixedObjectIndex(FI))
3051     return false;
3052   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3053 }
3054
3055 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3056 /// for tail call optimization. Targets which want to do tail call
3057 /// optimization should implement this function.
3058 bool
3059 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3060                                                      CallingConv::ID CalleeCC,
3061                                                      bool isVarArg,
3062                                                      bool isCalleeStructRet,
3063                                                      bool isCallerStructRet,
3064                                                      Type *RetTy,
3065                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3066                                     const SmallVectorImpl<SDValue> &OutVals,
3067                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3068                                                      SelectionDAG &DAG) const {
3069   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3070     return false;
3071
3072   // If -tailcallopt is specified, make fastcc functions tail-callable.
3073   const MachineFunction &MF = DAG.getMachineFunction();
3074   const Function *CallerF = MF.getFunction();
3075
3076   // If the function return type is x86_fp80 and the callee return type is not,
3077   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3078   // perform a tailcall optimization here.
3079   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3080     return false;
3081
3082   CallingConv::ID CallerCC = CallerF->getCallingConv();
3083   bool CCMatch = CallerCC == CalleeCC;
3084   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3085   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3086
3087   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3088     if (IsTailCallConvention(CalleeCC) && CCMatch)
3089       return true;
3090     return false;
3091   }
3092
3093   // Look for obvious safe cases to perform tail call optimization that do not
3094   // require ABI changes. This is what gcc calls sibcall.
3095
3096   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3097   // emit a special epilogue.
3098   const X86RegisterInfo *RegInfo =
3099     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3100   if (RegInfo->needsStackRealignment(MF))
3101     return false;
3102
3103   // Also avoid sibcall optimization if either caller or callee uses struct
3104   // return semantics.
3105   if (isCalleeStructRet || isCallerStructRet)
3106     return false;
3107
3108   // An stdcall/thiscall caller is expected to clean up its arguments; the
3109   // callee isn't going to do that.
3110   // FIXME: this is more restrictive than needed. We could produce a tailcall
3111   // when the stack adjustment matches. For example, with a thiscall that takes
3112   // only one argument.
3113   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3114                    CallerCC == CallingConv::X86_ThisCall))
3115     return false;
3116
3117   // Do not sibcall optimize vararg calls unless all arguments are passed via
3118   // registers.
3119   if (isVarArg && !Outs.empty()) {
3120
3121     // Optimizing for varargs on Win64 is unlikely to be safe without
3122     // additional testing.
3123     if (IsCalleeWin64 || IsCallerWin64)
3124       return false;
3125
3126     SmallVector<CCValAssign, 16> ArgLocs;
3127     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3128                    getTargetMachine(), ArgLocs, *DAG.getContext());
3129
3130     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3131     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3132       if (!ArgLocs[i].isRegLoc())
3133         return false;
3134   }
3135
3136   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3137   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3138   // this into a sibcall.
3139   bool Unused = false;
3140   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3141     if (!Ins[i].Used) {
3142       Unused = true;
3143       break;
3144     }
3145   }
3146   if (Unused) {
3147     SmallVector<CCValAssign, 16> RVLocs;
3148     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3149                    getTargetMachine(), RVLocs, *DAG.getContext());
3150     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3151     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3152       CCValAssign &VA = RVLocs[i];
3153       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3154         return false;
3155     }
3156   }
3157
3158   // If the calling conventions do not match, then we'd better make sure the
3159   // results are returned in the same way as what the caller expects.
3160   if (!CCMatch) {
3161     SmallVector<CCValAssign, 16> RVLocs1;
3162     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3163                     getTargetMachine(), RVLocs1, *DAG.getContext());
3164     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3165
3166     SmallVector<CCValAssign, 16> RVLocs2;
3167     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3168                     getTargetMachine(), RVLocs2, *DAG.getContext());
3169     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3170
3171     if (RVLocs1.size() != RVLocs2.size())
3172       return false;
3173     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3174       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3175         return false;
3176       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3177         return false;
3178       if (RVLocs1[i].isRegLoc()) {
3179         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3180           return false;
3181       } else {
3182         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3183           return false;
3184       }
3185     }
3186   }
3187
3188   // If the callee takes no arguments then go on to check the results of the
3189   // call.
3190   if (!Outs.empty()) {
3191     // Check if stack adjustment is needed. For now, do not do this if any
3192     // argument is passed on the stack.
3193     SmallVector<CCValAssign, 16> ArgLocs;
3194     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3195                    getTargetMachine(), ArgLocs, *DAG.getContext());
3196
3197     // Allocate shadow area for Win64
3198     if (IsCalleeWin64)
3199       CCInfo.AllocateStack(32, 8);
3200
3201     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3202     if (CCInfo.getNextStackOffset()) {
3203       MachineFunction &MF = DAG.getMachineFunction();
3204       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3205         return false;
3206
3207       // Check if the arguments are already laid out in the right way as
3208       // the caller's fixed stack objects.
3209       MachineFrameInfo *MFI = MF.getFrameInfo();
3210       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3211       const X86InstrInfo *TII =
3212         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3213       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3214         CCValAssign &VA = ArgLocs[i];
3215         SDValue Arg = OutVals[i];
3216         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3217         if (VA.getLocInfo() == CCValAssign::Indirect)
3218           return false;
3219         if (!VA.isRegLoc()) {
3220           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3221                                    MFI, MRI, TII))
3222             return false;
3223         }
3224       }
3225     }
3226
3227     // If the tailcall address may be in a register, then make sure it's
3228     // possible to register allocate for it. In 32-bit, the call address can
3229     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3230     // callee-saved registers are restored. These happen to be the same
3231     // registers used to pass 'inreg' arguments so watch out for those.
3232     if (!Subtarget->is64Bit() &&
3233         ((!isa<GlobalAddressSDNode>(Callee) &&
3234           !isa<ExternalSymbolSDNode>(Callee)) ||
3235          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3236       unsigned NumInRegs = 0;
3237       // In PIC we need an extra register to formulate the address computation
3238       // for the callee.
3239       unsigned MaxInRegs =
3240           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3241
3242       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3243         CCValAssign &VA = ArgLocs[i];
3244         if (!VA.isRegLoc())
3245           continue;
3246         unsigned Reg = VA.getLocReg();
3247         switch (Reg) {
3248         default: break;
3249         case X86::EAX: case X86::EDX: case X86::ECX:
3250           if (++NumInRegs == MaxInRegs)
3251             return false;
3252           break;
3253         }
3254       }
3255     }
3256   }
3257
3258   return true;
3259 }
3260
3261 FastISel *
3262 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3263                                   const TargetLibraryInfo *libInfo) const {
3264   return X86::createFastISel(funcInfo, libInfo);
3265 }
3266
3267 //===----------------------------------------------------------------------===//
3268 //                           Other Lowering Hooks
3269 //===----------------------------------------------------------------------===//
3270
3271 static bool MayFoldLoad(SDValue Op) {
3272   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3273 }
3274
3275 static bool MayFoldIntoStore(SDValue Op) {
3276   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3277 }
3278
3279 static bool isTargetShuffle(unsigned Opcode) {
3280   switch(Opcode) {
3281   default: return false;
3282   case X86ISD::PSHUFD:
3283   case X86ISD::PSHUFHW:
3284   case X86ISD::PSHUFLW:
3285   case X86ISD::SHUFP:
3286   case X86ISD::PALIGNR:
3287   case X86ISD::MOVLHPS:
3288   case X86ISD::MOVLHPD:
3289   case X86ISD::MOVHLPS:
3290   case X86ISD::MOVLPS:
3291   case X86ISD::MOVLPD:
3292   case X86ISD::MOVSHDUP:
3293   case X86ISD::MOVSLDUP:
3294   case X86ISD::MOVDDUP:
3295   case X86ISD::MOVSS:
3296   case X86ISD::MOVSD:
3297   case X86ISD::UNPCKL:
3298   case X86ISD::UNPCKH:
3299   case X86ISD::VPERMILP:
3300   case X86ISD::VPERM2X128:
3301   case X86ISD::VPERMI:
3302     return true;
3303   }
3304 }
3305
3306 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3307                                     SDValue V1, SelectionDAG &DAG) {
3308   switch(Opc) {
3309   default: llvm_unreachable("Unknown x86 shuffle node");
3310   case X86ISD::MOVSHDUP:
3311   case X86ISD::MOVSLDUP:
3312   case X86ISD::MOVDDUP:
3313     return DAG.getNode(Opc, dl, VT, V1);
3314   }
3315 }
3316
3317 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3318                                     SDValue V1, unsigned TargetMask,
3319                                     SelectionDAG &DAG) {
3320   switch(Opc) {
3321   default: llvm_unreachable("Unknown x86 shuffle node");
3322   case X86ISD::PSHUFD:
3323   case X86ISD::PSHUFHW:
3324   case X86ISD::PSHUFLW:
3325   case X86ISD::VPERMILP:
3326   case X86ISD::VPERMI:
3327     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3328   }
3329 }
3330
3331 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3332                                     SDValue V1, SDValue V2, unsigned TargetMask,
3333                                     SelectionDAG &DAG) {
3334   switch(Opc) {
3335   default: llvm_unreachable("Unknown x86 shuffle node");
3336   case X86ISD::PALIGNR:
3337   case X86ISD::SHUFP:
3338   case X86ISD::VPERM2X128:
3339     return DAG.getNode(Opc, dl, VT, V1, V2,
3340                        DAG.getConstant(TargetMask, MVT::i8));
3341   }
3342 }
3343
3344 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3345                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3346   switch(Opc) {
3347   default: llvm_unreachable("Unknown x86 shuffle node");
3348   case X86ISD::MOVLHPS:
3349   case X86ISD::MOVLHPD:
3350   case X86ISD::MOVHLPS:
3351   case X86ISD::MOVLPS:
3352   case X86ISD::MOVLPD:
3353   case X86ISD::MOVSS:
3354   case X86ISD::MOVSD:
3355   case X86ISD::UNPCKL:
3356   case X86ISD::UNPCKH:
3357     return DAG.getNode(Opc, dl, VT, V1, V2);
3358   }
3359 }
3360
3361 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3362   MachineFunction &MF = DAG.getMachineFunction();
3363   const X86RegisterInfo *RegInfo =
3364     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3365   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3366   int ReturnAddrIndex = FuncInfo->getRAIndex();
3367
3368   if (ReturnAddrIndex == 0) {
3369     // Set up a frame object for the return address.
3370     unsigned SlotSize = RegInfo->getSlotSize();
3371     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3372                                                            -(int64_t)SlotSize,
3373                                                            false);
3374     FuncInfo->setRAIndex(ReturnAddrIndex);
3375   }
3376
3377   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3378 }
3379
3380 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3381                                        bool hasSymbolicDisplacement) {
3382   // Offset should fit into 32 bit immediate field.
3383   if (!isInt<32>(Offset))
3384     return false;
3385
3386   // If we don't have a symbolic displacement - we don't have any extra
3387   // restrictions.
3388   if (!hasSymbolicDisplacement)
3389     return true;
3390
3391   // FIXME: Some tweaks might be needed for medium code model.
3392   if (M != CodeModel::Small && M != CodeModel::Kernel)
3393     return false;
3394
3395   // For small code model we assume that latest object is 16MB before end of 31
3396   // bits boundary. We may also accept pretty large negative constants knowing
3397   // that all objects are in the positive half of address space.
3398   if (M == CodeModel::Small && Offset < 16*1024*1024)
3399     return true;
3400
3401   // For kernel code model we know that all object resist in the negative half
3402   // of 32bits address space. We may not accept negative offsets, since they may
3403   // be just off and we may accept pretty large positive ones.
3404   if (M == CodeModel::Kernel && Offset > 0)
3405     return true;
3406
3407   return false;
3408 }
3409
3410 /// isCalleePop - Determines whether the callee is required to pop its
3411 /// own arguments. Callee pop is necessary to support tail calls.
3412 bool X86::isCalleePop(CallingConv::ID CallingConv,
3413                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3414   if (IsVarArg)
3415     return false;
3416
3417   switch (CallingConv) {
3418   default:
3419     return false;
3420   case CallingConv::X86_StdCall:
3421     return !is64Bit;
3422   case CallingConv::X86_FastCall:
3423     return !is64Bit;
3424   case CallingConv::X86_ThisCall:
3425     return !is64Bit;
3426   case CallingConv::Fast:
3427     return TailCallOpt;
3428   case CallingConv::GHC:
3429     return TailCallOpt;
3430   case CallingConv::HiPE:
3431     return TailCallOpt;
3432   }
3433 }
3434
3435 /// \brief Return true if the condition is an unsigned comparison operation.
3436 static bool isX86CCUnsigned(unsigned X86CC) {
3437   switch (X86CC) {
3438   default: llvm_unreachable("Invalid integer condition!");
3439   case X86::COND_E:     return true;
3440   case X86::COND_G:     return false;
3441   case X86::COND_GE:    return false;
3442   case X86::COND_L:     return false;
3443   case X86::COND_LE:    return false;
3444   case X86::COND_NE:    return true;
3445   case X86::COND_B:     return true;
3446   case X86::COND_A:     return true;
3447   case X86::COND_BE:    return true;
3448   case X86::COND_AE:    return true;
3449   }
3450   llvm_unreachable("covered switch fell through?!");
3451 }
3452
3453 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3454 /// specific condition code, returning the condition code and the LHS/RHS of the
3455 /// comparison to make.
3456 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3457                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3458   if (!isFP) {
3459     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3460       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3461         // X > -1   -> X == 0, jump !sign.
3462         RHS = DAG.getConstant(0, RHS.getValueType());
3463         return X86::COND_NS;
3464       }
3465       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3466         // X < 0   -> X == 0, jump on sign.
3467         return X86::COND_S;
3468       }
3469       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3470         // X < 1   -> X <= 0
3471         RHS = DAG.getConstant(0, RHS.getValueType());
3472         return X86::COND_LE;
3473       }
3474     }
3475
3476     switch (SetCCOpcode) {
3477     default: llvm_unreachable("Invalid integer condition!");
3478     case ISD::SETEQ:  return X86::COND_E;
3479     case ISD::SETGT:  return X86::COND_G;
3480     case ISD::SETGE:  return X86::COND_GE;
3481     case ISD::SETLT:  return X86::COND_L;
3482     case ISD::SETLE:  return X86::COND_LE;
3483     case ISD::SETNE:  return X86::COND_NE;
3484     case ISD::SETULT: return X86::COND_B;
3485     case ISD::SETUGT: return X86::COND_A;
3486     case ISD::SETULE: return X86::COND_BE;
3487     case ISD::SETUGE: return X86::COND_AE;
3488     }
3489   }
3490
3491   // First determine if it is required or is profitable to flip the operands.
3492
3493   // If LHS is a foldable load, but RHS is not, flip the condition.
3494   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3495       !ISD::isNON_EXTLoad(RHS.getNode())) {
3496     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3497     std::swap(LHS, RHS);
3498   }
3499
3500   switch (SetCCOpcode) {
3501   default: break;
3502   case ISD::SETOLT:
3503   case ISD::SETOLE:
3504   case ISD::SETUGT:
3505   case ISD::SETUGE:
3506     std::swap(LHS, RHS);
3507     break;
3508   }
3509
3510   // On a floating point condition, the flags are set as follows:
3511   // ZF  PF  CF   op
3512   //  0 | 0 | 0 | X > Y
3513   //  0 | 0 | 1 | X < Y
3514   //  1 | 0 | 0 | X == Y
3515   //  1 | 1 | 1 | unordered
3516   switch (SetCCOpcode) {
3517   default: llvm_unreachable("Condcode should be pre-legalized away");
3518   case ISD::SETUEQ:
3519   case ISD::SETEQ:   return X86::COND_E;
3520   case ISD::SETOLT:              // flipped
3521   case ISD::SETOGT:
3522   case ISD::SETGT:   return X86::COND_A;
3523   case ISD::SETOLE:              // flipped
3524   case ISD::SETOGE:
3525   case ISD::SETGE:   return X86::COND_AE;
3526   case ISD::SETUGT:              // flipped
3527   case ISD::SETULT:
3528   case ISD::SETLT:   return X86::COND_B;
3529   case ISD::SETUGE:              // flipped
3530   case ISD::SETULE:
3531   case ISD::SETLE:   return X86::COND_BE;
3532   case ISD::SETONE:
3533   case ISD::SETNE:   return X86::COND_NE;
3534   case ISD::SETUO:   return X86::COND_P;
3535   case ISD::SETO:    return X86::COND_NP;
3536   case ISD::SETOEQ:
3537   case ISD::SETUNE:  return X86::COND_INVALID;
3538   }
3539 }
3540
3541 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3542 /// code. Current x86 isa includes the following FP cmov instructions:
3543 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3544 static bool hasFPCMov(unsigned X86CC) {
3545   switch (X86CC) {
3546   default:
3547     return false;
3548   case X86::COND_B:
3549   case X86::COND_BE:
3550   case X86::COND_E:
3551   case X86::COND_P:
3552   case X86::COND_A:
3553   case X86::COND_AE:
3554   case X86::COND_NE:
3555   case X86::COND_NP:
3556     return true;
3557   }
3558 }
3559
3560 /// isFPImmLegal - Returns true if the target can instruction select the
3561 /// specified FP immediate natively. If false, the legalizer will
3562 /// materialize the FP immediate as a load from a constant pool.
3563 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3564   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3565     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3566       return true;
3567   }
3568   return false;
3569 }
3570
3571 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3572 /// the specified range (L, H].
3573 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3574   return (Val < 0) || (Val >= Low && Val < Hi);
3575 }
3576
3577 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3578 /// specified value.
3579 static bool isUndefOrEqual(int Val, int CmpVal) {
3580   return (Val < 0 || Val == CmpVal);
3581 }
3582
3583 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3584 /// from position Pos and ending in Pos+Size, falls within the specified
3585 /// sequential range (L, L+Pos]. or is undef.
3586 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3587                                        unsigned Pos, unsigned Size, int Low) {
3588   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3589     if (!isUndefOrEqual(Mask[i], Low))
3590       return false;
3591   return true;
3592 }
3593
3594 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3595 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3596 /// the second operand.
3597 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3598   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3599     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3600   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3601     return (Mask[0] < 2 && Mask[1] < 2);
3602   return false;
3603 }
3604
3605 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3606 /// is suitable for input to PSHUFHW.
3607 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3608   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3609     return false;
3610
3611   // Lower quadword copied in order or undef.
3612   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3613     return false;
3614
3615   // Upper quadword shuffled.
3616   for (unsigned i = 4; i != 8; ++i)
3617     if (!isUndefOrInRange(Mask[i], 4, 8))
3618       return false;
3619
3620   if (VT == MVT::v16i16) {
3621     // Lower quadword copied in order or undef.
3622     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3623       return false;
3624
3625     // Upper quadword shuffled.
3626     for (unsigned i = 12; i != 16; ++i)
3627       if (!isUndefOrInRange(Mask[i], 12, 16))
3628         return false;
3629   }
3630
3631   return true;
3632 }
3633
3634 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3635 /// is suitable for input to PSHUFLW.
3636 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3637   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3638     return false;
3639
3640   // Upper quadword copied in order.
3641   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3642     return false;
3643
3644   // Lower quadword shuffled.
3645   for (unsigned i = 0; i != 4; ++i)
3646     if (!isUndefOrInRange(Mask[i], 0, 4))
3647       return false;
3648
3649   if (VT == MVT::v16i16) {
3650     // Upper quadword copied in order.
3651     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3652       return false;
3653
3654     // Lower quadword shuffled.
3655     for (unsigned i = 8; i != 12; ++i)
3656       if (!isUndefOrInRange(Mask[i], 8, 12))
3657         return false;
3658   }
3659
3660   return true;
3661 }
3662
3663 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3664 /// is suitable for input to PALIGNR.
3665 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3666                           const X86Subtarget *Subtarget) {
3667   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3668       (VT.is256BitVector() && !Subtarget->hasInt256()))
3669     return false;
3670
3671   unsigned NumElts = VT.getVectorNumElements();
3672   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3673   unsigned NumLaneElts = NumElts/NumLanes;
3674
3675   // Do not handle 64-bit element shuffles with palignr.
3676   if (NumLaneElts == 2)
3677     return false;
3678
3679   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3680     unsigned i;
3681     for (i = 0; i != NumLaneElts; ++i) {
3682       if (Mask[i+l] >= 0)
3683         break;
3684     }
3685
3686     // Lane is all undef, go to next lane
3687     if (i == NumLaneElts)
3688       continue;
3689
3690     int Start = Mask[i+l];
3691
3692     // Make sure its in this lane in one of the sources
3693     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3694         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3695       return false;
3696
3697     // If not lane 0, then we must match lane 0
3698     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3699       return false;
3700
3701     // Correct second source to be contiguous with first source
3702     if (Start >= (int)NumElts)
3703       Start -= NumElts - NumLaneElts;
3704
3705     // Make sure we're shifting in the right direction.
3706     if (Start <= (int)(i+l))
3707       return false;
3708
3709     Start -= i;
3710
3711     // Check the rest of the elements to see if they are consecutive.
3712     for (++i; i != NumLaneElts; ++i) {
3713       int Idx = Mask[i+l];
3714
3715       // Make sure its in this lane
3716       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3717           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3718         return false;
3719
3720       // If not lane 0, then we must match lane 0
3721       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3722         return false;
3723
3724       if (Idx >= (int)NumElts)
3725         Idx -= NumElts - NumLaneElts;
3726
3727       if (!isUndefOrEqual(Idx, Start+i))
3728         return false;
3729
3730     }
3731   }
3732
3733   return true;
3734 }
3735
3736 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3737 /// the two vector operands have swapped position.
3738 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3739                                      unsigned NumElems) {
3740   for (unsigned i = 0; i != NumElems; ++i) {
3741     int idx = Mask[i];
3742     if (idx < 0)
3743       continue;
3744     else if (idx < (int)NumElems)
3745       Mask[i] = idx + NumElems;
3746     else
3747       Mask[i] = idx - NumElems;
3748   }
3749 }
3750
3751 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3752 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3753 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3754 /// reverse of what x86 shuffles want.
3755 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3756
3757   unsigned NumElems = VT.getVectorNumElements();
3758   unsigned NumLanes = VT.getSizeInBits()/128;
3759   unsigned NumLaneElems = NumElems/NumLanes;
3760
3761   if (NumLaneElems != 2 && NumLaneElems != 4)
3762     return false;
3763
3764   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3765   bool symetricMaskRequired =
3766     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3767
3768   // VSHUFPSY divides the resulting vector into 4 chunks.
3769   // The sources are also splitted into 4 chunks, and each destination
3770   // chunk must come from a different source chunk.
3771   //
3772   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3773   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3774   //
3775   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3776   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3777   //
3778   // VSHUFPDY divides the resulting vector into 4 chunks.
3779   // The sources are also splitted into 4 chunks, and each destination
3780   // chunk must come from a different source chunk.
3781   //
3782   //  SRC1 =>      X3       X2       X1       X0
3783   //  SRC2 =>      Y3       Y2       Y1       Y0
3784   //
3785   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3786   //
3787   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3788   unsigned HalfLaneElems = NumLaneElems/2;
3789   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3790     for (unsigned i = 0; i != NumLaneElems; ++i) {
3791       int Idx = Mask[i+l];
3792       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3793       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3794         return false;
3795       // For VSHUFPSY, the mask of the second half must be the same as the
3796       // first but with the appropriate offsets. This works in the same way as
3797       // VPERMILPS works with masks.
3798       if (!symetricMaskRequired || Idx < 0)
3799         continue;
3800       if (MaskVal[i] < 0) {
3801         MaskVal[i] = Idx - l;
3802         continue;
3803       }
3804       if ((signed)(Idx - l) != MaskVal[i])
3805         return false;
3806     }
3807   }
3808
3809   return true;
3810 }
3811
3812 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3813 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3814 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3815   if (!VT.is128BitVector())
3816     return false;
3817
3818   unsigned NumElems = VT.getVectorNumElements();
3819
3820   if (NumElems != 4)
3821     return false;
3822
3823   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3824   return isUndefOrEqual(Mask[0], 6) &&
3825          isUndefOrEqual(Mask[1], 7) &&
3826          isUndefOrEqual(Mask[2], 2) &&
3827          isUndefOrEqual(Mask[3], 3);
3828 }
3829
3830 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3831 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3832 /// <2, 3, 2, 3>
3833 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3834   if (!VT.is128BitVector())
3835     return false;
3836
3837   unsigned NumElems = VT.getVectorNumElements();
3838
3839   if (NumElems != 4)
3840     return false;
3841
3842   return isUndefOrEqual(Mask[0], 2) &&
3843          isUndefOrEqual(Mask[1], 3) &&
3844          isUndefOrEqual(Mask[2], 2) &&
3845          isUndefOrEqual(Mask[3], 3);
3846 }
3847
3848 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3849 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3850 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3851   if (!VT.is128BitVector())
3852     return false;
3853
3854   unsigned NumElems = VT.getVectorNumElements();
3855
3856   if (NumElems != 2 && NumElems != 4)
3857     return false;
3858
3859   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3860     if (!isUndefOrEqual(Mask[i], i + NumElems))
3861       return false;
3862
3863   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3864     if (!isUndefOrEqual(Mask[i], i))
3865       return false;
3866
3867   return true;
3868 }
3869
3870 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3871 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3872 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3873   if (!VT.is128BitVector())
3874     return false;
3875
3876   unsigned NumElems = VT.getVectorNumElements();
3877
3878   if (NumElems != 2 && NumElems != 4)
3879     return false;
3880
3881   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3882     if (!isUndefOrEqual(Mask[i], i))
3883       return false;
3884
3885   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3886     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3887       return false;
3888
3889   return true;
3890 }
3891
3892 //
3893 // Some special combinations that can be optimized.
3894 //
3895 static
3896 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3897                                SelectionDAG &DAG) {
3898   MVT VT = SVOp->getSimpleValueType(0);
3899   SDLoc dl(SVOp);
3900
3901   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3902     return SDValue();
3903
3904   ArrayRef<int> Mask = SVOp->getMask();
3905
3906   // These are the special masks that may be optimized.
3907   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3908   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3909   bool MatchEvenMask = true;
3910   bool MatchOddMask  = true;
3911   for (int i=0; i<8; ++i) {
3912     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3913       MatchEvenMask = false;
3914     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3915       MatchOddMask = false;
3916   }
3917
3918   if (!MatchEvenMask && !MatchOddMask)
3919     return SDValue();
3920
3921   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3922
3923   SDValue Op0 = SVOp->getOperand(0);
3924   SDValue Op1 = SVOp->getOperand(1);
3925
3926   if (MatchEvenMask) {
3927     // Shift the second operand right to 32 bits.
3928     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3929     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3930   } else {
3931     // Shift the first operand left to 32 bits.
3932     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3933     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3934   }
3935   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3936   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3937 }
3938
3939 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3940 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3941 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3942                          bool HasInt256, bool V2IsSplat = false) {
3943
3944   assert(VT.getSizeInBits() >= 128 &&
3945          "Unsupported vector type for unpckl");
3946
3947   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3948   unsigned NumLanes;
3949   unsigned NumOf256BitLanes;
3950   unsigned NumElts = VT.getVectorNumElements();
3951   if (VT.is256BitVector()) {
3952     if (NumElts != 4 && NumElts != 8 &&
3953         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3954     return false;
3955     NumLanes = 2;
3956     NumOf256BitLanes = 1;
3957   } else if (VT.is512BitVector()) {
3958     assert(VT.getScalarType().getSizeInBits() >= 32 &&
3959            "Unsupported vector type for unpckh");
3960     NumLanes = 2;
3961     NumOf256BitLanes = 2;
3962   } else {
3963     NumLanes = 1;
3964     NumOf256BitLanes = 1;
3965   }
3966
3967   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
3968   unsigned NumLaneElts = NumEltsInStride/NumLanes;
3969
3970   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
3971     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
3972       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3973         int BitI  = Mask[l256*NumEltsInStride+l+i];
3974         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
3975         if (!isUndefOrEqual(BitI, j+l256*NumElts))
3976           return false;
3977         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
3978           return false;
3979         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
3980           return false;
3981       }
3982     }
3983   }
3984   return true;
3985 }
3986
3987 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3988 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3989 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3990                          bool HasInt256, bool V2IsSplat = false) {
3991   assert(VT.getSizeInBits() >= 128 &&
3992          "Unsupported vector type for unpckh");
3993
3994   // AVX defines UNPCK* to operate independently on 128-bit lanes.
3995   unsigned NumLanes;
3996   unsigned NumOf256BitLanes;
3997   unsigned NumElts = VT.getVectorNumElements();
3998   if (VT.is256BitVector()) {
3999     if (NumElts != 4 && NumElts != 8 &&
4000         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4001     return false;
4002     NumLanes = 2;
4003     NumOf256BitLanes = 1;
4004   } else if (VT.is512BitVector()) {
4005     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4006            "Unsupported vector type for unpckh");
4007     NumLanes = 2;
4008     NumOf256BitLanes = 2;
4009   } else {
4010     NumLanes = 1;
4011     NumOf256BitLanes = 1;
4012   }
4013
4014   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4015   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4016
4017   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4018     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4019       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4020         int BitI  = Mask[l256*NumEltsInStride+l+i];
4021         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4022         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4023           return false;
4024         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4025           return false;
4026         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4027           return false;
4028       }
4029     }
4030   }
4031   return true;
4032 }
4033
4034 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4035 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4036 /// <0, 0, 1, 1>
4037 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4038   unsigned NumElts = VT.getVectorNumElements();
4039   bool Is256BitVec = VT.is256BitVector();
4040
4041   if (VT.is512BitVector())
4042     return false;
4043   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4044          "Unsupported vector type for unpckh");
4045
4046   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4047       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4048     return false;
4049
4050   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4051   // FIXME: Need a better way to get rid of this, there's no latency difference
4052   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4053   // the former later. We should also remove the "_undef" special mask.
4054   if (NumElts == 4 && Is256BitVec)
4055     return false;
4056
4057   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4058   // independently on 128-bit lanes.
4059   unsigned NumLanes = VT.getSizeInBits()/128;
4060   unsigned NumLaneElts = NumElts/NumLanes;
4061
4062   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4063     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4064       int BitI  = Mask[l+i];
4065       int BitI1 = Mask[l+i+1];
4066
4067       if (!isUndefOrEqual(BitI, j))
4068         return false;
4069       if (!isUndefOrEqual(BitI1, j))
4070         return false;
4071     }
4072   }
4073
4074   return true;
4075 }
4076
4077 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4078 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4079 /// <2, 2, 3, 3>
4080 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4081   unsigned NumElts = VT.getVectorNumElements();
4082
4083   if (VT.is512BitVector())
4084     return false;
4085
4086   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4087          "Unsupported vector type for unpckh");
4088
4089   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4090       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4091     return false;
4092
4093   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4094   // independently on 128-bit lanes.
4095   unsigned NumLanes = VT.getSizeInBits()/128;
4096   unsigned NumLaneElts = NumElts/NumLanes;
4097
4098   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4099     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4100       int BitI  = Mask[l+i];
4101       int BitI1 = Mask[l+i+1];
4102       if (!isUndefOrEqual(BitI, j))
4103         return false;
4104       if (!isUndefOrEqual(BitI1, j))
4105         return false;
4106     }
4107   }
4108   return true;
4109 }
4110
4111 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4112 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4113 /// MOVSD, and MOVD, i.e. setting the lowest element.
4114 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4115   if (VT.getVectorElementType().getSizeInBits() < 32)
4116     return false;
4117   if (!VT.is128BitVector())
4118     return false;
4119
4120   unsigned NumElts = VT.getVectorNumElements();
4121
4122   if (!isUndefOrEqual(Mask[0], NumElts))
4123     return false;
4124
4125   for (unsigned i = 1; i != NumElts; ++i)
4126     if (!isUndefOrEqual(Mask[i], i))
4127       return false;
4128
4129   return true;
4130 }
4131
4132 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4133 /// as permutations between 128-bit chunks or halves. As an example: this
4134 /// shuffle bellow:
4135 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4136 /// The first half comes from the second half of V1 and the second half from the
4137 /// the second half of V2.
4138 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4139   if (!HasFp256 || !VT.is256BitVector())
4140     return false;
4141
4142   // The shuffle result is divided into half A and half B. In total the two
4143   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4144   // B must come from C, D, E or F.
4145   unsigned HalfSize = VT.getVectorNumElements()/2;
4146   bool MatchA = false, MatchB = false;
4147
4148   // Check if A comes from one of C, D, E, F.
4149   for (unsigned Half = 0; Half != 4; ++Half) {
4150     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4151       MatchA = true;
4152       break;
4153     }
4154   }
4155
4156   // Check if B comes from one of C, D, E, F.
4157   for (unsigned Half = 0; Half != 4; ++Half) {
4158     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4159       MatchB = true;
4160       break;
4161     }
4162   }
4163
4164   return MatchA && MatchB;
4165 }
4166
4167 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4168 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4169 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4170   MVT VT = SVOp->getSimpleValueType(0);
4171
4172   unsigned HalfSize = VT.getVectorNumElements()/2;
4173
4174   unsigned FstHalf = 0, SndHalf = 0;
4175   for (unsigned i = 0; i < HalfSize; ++i) {
4176     if (SVOp->getMaskElt(i) > 0) {
4177       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4178       break;
4179     }
4180   }
4181   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4182     if (SVOp->getMaskElt(i) > 0) {
4183       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4184       break;
4185     }
4186   }
4187
4188   return (FstHalf | (SndHalf << 4));
4189 }
4190
4191 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4192 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4193   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4194   if (EltSize < 32)
4195     return false;
4196
4197   unsigned NumElts = VT.getVectorNumElements();
4198   Imm8 = 0;
4199   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4200     for (unsigned i = 0; i != NumElts; ++i) {
4201       if (Mask[i] < 0)
4202         continue;
4203       Imm8 |= Mask[i] << (i*2);
4204     }
4205     return true;
4206   }
4207
4208   unsigned LaneSize = 4;
4209   SmallVector<int, 4> MaskVal(LaneSize, -1);
4210
4211   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4212     for (unsigned i = 0; i != LaneSize; ++i) {
4213       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4214         return false;
4215       if (Mask[i+l] < 0)
4216         continue;
4217       if (MaskVal[i] < 0) {
4218         MaskVal[i] = Mask[i+l] - l;
4219         Imm8 |= MaskVal[i] << (i*2);
4220         continue;
4221       }
4222       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4223         return false;
4224     }
4225   }
4226   return true;
4227 }
4228
4229 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4230 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4231 /// Note that VPERMIL mask matching is different depending whether theunderlying
4232 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4233 /// to the same elements of the low, but to the higher half of the source.
4234 /// In VPERMILPD the two lanes could be shuffled independently of each other
4235 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4236 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4237   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4238   if (VT.getSizeInBits() < 256 || EltSize < 32)
4239     return false;
4240   bool symetricMaskRequired = (EltSize == 32);
4241   unsigned NumElts = VT.getVectorNumElements();
4242
4243   unsigned NumLanes = VT.getSizeInBits()/128;
4244   unsigned LaneSize = NumElts/NumLanes;
4245   // 2 or 4 elements in one lane
4246
4247   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4248   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4249     for (unsigned i = 0; i != LaneSize; ++i) {
4250       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4251         return false;
4252       if (symetricMaskRequired) {
4253         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4254           ExpectedMaskVal[i] = Mask[i+l] - l;
4255           continue;
4256         }
4257         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4258           return false;
4259       }
4260     }
4261   }
4262   return true;
4263 }
4264
4265 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4266 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4267 /// element of vector 2 and the other elements to come from vector 1 in order.
4268 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4269                                bool V2IsSplat = false, bool V2IsUndef = false) {
4270   if (!VT.is128BitVector())
4271     return false;
4272
4273   unsigned NumOps = VT.getVectorNumElements();
4274   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4275     return false;
4276
4277   if (!isUndefOrEqual(Mask[0], 0))
4278     return false;
4279
4280   for (unsigned i = 1; i != NumOps; ++i)
4281     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4282           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4283           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4284       return false;
4285
4286   return true;
4287 }
4288
4289 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4290 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4291 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4292 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4293                            const X86Subtarget *Subtarget) {
4294   if (!Subtarget->hasSSE3())
4295     return false;
4296
4297   unsigned NumElems = VT.getVectorNumElements();
4298
4299   if ((VT.is128BitVector() && NumElems != 4) ||
4300       (VT.is256BitVector() && NumElems != 8) ||
4301       (VT.is512BitVector() && NumElems != 16))
4302     return false;
4303
4304   // "i+1" is the value the indexed mask element must have
4305   for (unsigned i = 0; i != NumElems; i += 2)
4306     if (!isUndefOrEqual(Mask[i], i+1) ||
4307         !isUndefOrEqual(Mask[i+1], i+1))
4308       return false;
4309
4310   return true;
4311 }
4312
4313 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4314 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4315 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4316 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4317                            const X86Subtarget *Subtarget) {
4318   if (!Subtarget->hasSSE3())
4319     return false;
4320
4321   unsigned NumElems = VT.getVectorNumElements();
4322
4323   if ((VT.is128BitVector() && NumElems != 4) ||
4324       (VT.is256BitVector() && NumElems != 8) ||
4325       (VT.is512BitVector() && NumElems != 16))
4326     return false;
4327
4328   // "i" is the value the indexed mask element must have
4329   for (unsigned i = 0; i != NumElems; i += 2)
4330     if (!isUndefOrEqual(Mask[i], i) ||
4331         !isUndefOrEqual(Mask[i+1], i))
4332       return false;
4333
4334   return true;
4335 }
4336
4337 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4338 /// specifies a shuffle of elements that is suitable for input to 256-bit
4339 /// version of MOVDDUP.
4340 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4341   if (!HasFp256 || !VT.is256BitVector())
4342     return false;
4343
4344   unsigned NumElts = VT.getVectorNumElements();
4345   if (NumElts != 4)
4346     return false;
4347
4348   for (unsigned i = 0; i != NumElts/2; ++i)
4349     if (!isUndefOrEqual(Mask[i], 0))
4350       return false;
4351   for (unsigned i = NumElts/2; i != NumElts; ++i)
4352     if (!isUndefOrEqual(Mask[i], NumElts/2))
4353       return false;
4354   return true;
4355 }
4356
4357 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4358 /// specifies a shuffle of elements that is suitable for input to 128-bit
4359 /// version of MOVDDUP.
4360 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4361   if (!VT.is128BitVector())
4362     return false;
4363
4364   unsigned e = VT.getVectorNumElements() / 2;
4365   for (unsigned i = 0; i != e; ++i)
4366     if (!isUndefOrEqual(Mask[i], i))
4367       return false;
4368   for (unsigned i = 0; i != e; ++i)
4369     if (!isUndefOrEqual(Mask[e+i], i))
4370       return false;
4371   return true;
4372 }
4373
4374 /// isVEXTRACTIndex - Return true if the specified
4375 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4376 /// suitable for instruction that extract 128 or 256 bit vectors
4377 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4378   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4379   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4380     return false;
4381
4382   // The index should be aligned on a vecWidth-bit boundary.
4383   uint64_t Index =
4384     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4385
4386   MVT VT = N->getSimpleValueType(0);
4387   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4388   bool Result = (Index * ElSize) % vecWidth == 0;
4389
4390   return Result;
4391 }
4392
4393 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4394 /// operand specifies a subvector insert that is suitable for input to
4395 /// insertion of 128 or 256-bit subvectors
4396 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4397   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4398   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4399     return false;
4400   // The index should be aligned on a vecWidth-bit boundary.
4401   uint64_t Index =
4402     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4403
4404   MVT VT = N->getSimpleValueType(0);
4405   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4406   bool Result = (Index * ElSize) % vecWidth == 0;
4407
4408   return Result;
4409 }
4410
4411 bool X86::isVINSERT128Index(SDNode *N) {
4412   return isVINSERTIndex(N, 128);
4413 }
4414
4415 bool X86::isVINSERT256Index(SDNode *N) {
4416   return isVINSERTIndex(N, 256);
4417 }
4418
4419 bool X86::isVEXTRACT128Index(SDNode *N) {
4420   return isVEXTRACTIndex(N, 128);
4421 }
4422
4423 bool X86::isVEXTRACT256Index(SDNode *N) {
4424   return isVEXTRACTIndex(N, 256);
4425 }
4426
4427 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4428 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4429 /// Handles 128-bit and 256-bit.
4430 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4431   MVT VT = N->getSimpleValueType(0);
4432
4433   assert((VT.getSizeInBits() >= 128) &&
4434          "Unsupported vector type for PSHUF/SHUFP");
4435
4436   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4437   // independently on 128-bit lanes.
4438   unsigned NumElts = VT.getVectorNumElements();
4439   unsigned NumLanes = VT.getSizeInBits()/128;
4440   unsigned NumLaneElts = NumElts/NumLanes;
4441
4442   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4443          "Only supports 2, 4 or 8 elements per lane");
4444
4445   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4446   unsigned Mask = 0;
4447   for (unsigned i = 0; i != NumElts; ++i) {
4448     int Elt = N->getMaskElt(i);
4449     if (Elt < 0) continue;
4450     Elt &= NumLaneElts - 1;
4451     unsigned ShAmt = (i << Shift) % 8;
4452     Mask |= Elt << ShAmt;
4453   }
4454
4455   return Mask;
4456 }
4457
4458 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4459 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4460 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4461   MVT VT = N->getSimpleValueType(0);
4462
4463   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4464          "Unsupported vector type for PSHUFHW");
4465
4466   unsigned NumElts = VT.getVectorNumElements();
4467
4468   unsigned Mask = 0;
4469   for (unsigned l = 0; l != NumElts; l += 8) {
4470     // 8 nodes per lane, but we only care about the last 4.
4471     for (unsigned i = 0; i < 4; ++i) {
4472       int Elt = N->getMaskElt(l+i+4);
4473       if (Elt < 0) continue;
4474       Elt &= 0x3; // only 2-bits.
4475       Mask |= Elt << (i * 2);
4476     }
4477   }
4478
4479   return Mask;
4480 }
4481
4482 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4483 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4484 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4485   MVT VT = N->getSimpleValueType(0);
4486
4487   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4488          "Unsupported vector type for PSHUFHW");
4489
4490   unsigned NumElts = VT.getVectorNumElements();
4491
4492   unsigned Mask = 0;
4493   for (unsigned l = 0; l != NumElts; l += 8) {
4494     // 8 nodes per lane, but we only care about the first 4.
4495     for (unsigned i = 0; i < 4; ++i) {
4496       int Elt = N->getMaskElt(l+i);
4497       if (Elt < 0) continue;
4498       Elt &= 0x3; // only 2-bits
4499       Mask |= Elt << (i * 2);
4500     }
4501   }
4502
4503   return Mask;
4504 }
4505
4506 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4507 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4508 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4509   MVT VT = SVOp->getSimpleValueType(0);
4510   unsigned EltSize = VT.is512BitVector() ? 1 :
4511     VT.getVectorElementType().getSizeInBits() >> 3;
4512
4513   unsigned NumElts = VT.getVectorNumElements();
4514   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4515   unsigned NumLaneElts = NumElts/NumLanes;
4516
4517   int Val = 0;
4518   unsigned i;
4519   for (i = 0; i != NumElts; ++i) {
4520     Val = SVOp->getMaskElt(i);
4521     if (Val >= 0)
4522       break;
4523   }
4524   if (Val >= (int)NumElts)
4525     Val -= NumElts - NumLaneElts;
4526
4527   assert(Val - i > 0 && "PALIGNR imm should be positive");
4528   return (Val - i) * EltSize;
4529 }
4530
4531 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4532   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4533   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4534     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4535
4536   uint64_t Index =
4537     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4538
4539   MVT VecVT = N->getOperand(0).getSimpleValueType();
4540   MVT ElVT = VecVT.getVectorElementType();
4541
4542   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4543   return Index / NumElemsPerChunk;
4544 }
4545
4546 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4547   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4548   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4549     llvm_unreachable("Illegal insert subvector for VINSERT");
4550
4551   uint64_t Index =
4552     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4553
4554   MVT VecVT = N->getSimpleValueType(0);
4555   MVT ElVT = VecVT.getVectorElementType();
4556
4557   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4558   return Index / NumElemsPerChunk;
4559 }
4560
4561 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4562 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4563 /// and VINSERTI128 instructions.
4564 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4565   return getExtractVEXTRACTImmediate(N, 128);
4566 }
4567
4568 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4569 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4570 /// and VINSERTI64x4 instructions.
4571 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4572   return getExtractVEXTRACTImmediate(N, 256);
4573 }
4574
4575 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4576 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4577 /// and VINSERTI128 instructions.
4578 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4579   return getInsertVINSERTImmediate(N, 128);
4580 }
4581
4582 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4583 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4584 /// and VINSERTI64x4 instructions.
4585 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4586   return getInsertVINSERTImmediate(N, 256);
4587 }
4588
4589 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4590 /// constant +0.0.
4591 bool X86::isZeroNode(SDValue Elt) {
4592   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4593     return CN->isNullValue();
4594   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4595     return CFP->getValueAPF().isPosZero();
4596   return false;
4597 }
4598
4599 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4600 /// their permute mask.
4601 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4602                                     SelectionDAG &DAG) {
4603   MVT VT = SVOp->getSimpleValueType(0);
4604   unsigned NumElems = VT.getVectorNumElements();
4605   SmallVector<int, 8> MaskVec;
4606
4607   for (unsigned i = 0; i != NumElems; ++i) {
4608     int Idx = SVOp->getMaskElt(i);
4609     if (Idx >= 0) {
4610       if (Idx < (int)NumElems)
4611         Idx += NumElems;
4612       else
4613         Idx -= NumElems;
4614     }
4615     MaskVec.push_back(Idx);
4616   }
4617   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4618                               SVOp->getOperand(0), &MaskVec[0]);
4619 }
4620
4621 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4622 /// match movhlps. The lower half elements should come from upper half of
4623 /// V1 (and in order), and the upper half elements should come from the upper
4624 /// half of V2 (and in order).
4625 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4626   if (!VT.is128BitVector())
4627     return false;
4628   if (VT.getVectorNumElements() != 4)
4629     return false;
4630   for (unsigned i = 0, e = 2; i != e; ++i)
4631     if (!isUndefOrEqual(Mask[i], i+2))
4632       return false;
4633   for (unsigned i = 2; i != 4; ++i)
4634     if (!isUndefOrEqual(Mask[i], i+4))
4635       return false;
4636   return true;
4637 }
4638
4639 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4640 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4641 /// required.
4642 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4643   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4644     return false;
4645   N = N->getOperand(0).getNode();
4646   if (!ISD::isNON_EXTLoad(N))
4647     return false;
4648   if (LD)
4649     *LD = cast<LoadSDNode>(N);
4650   return true;
4651 }
4652
4653 // Test whether the given value is a vector value which will be legalized
4654 // into a load.
4655 static bool WillBeConstantPoolLoad(SDNode *N) {
4656   if (N->getOpcode() != ISD::BUILD_VECTOR)
4657     return false;
4658
4659   // Check for any non-constant elements.
4660   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4661     switch (N->getOperand(i).getNode()->getOpcode()) {
4662     case ISD::UNDEF:
4663     case ISD::ConstantFP:
4664     case ISD::Constant:
4665       break;
4666     default:
4667       return false;
4668     }
4669
4670   // Vectors of all-zeros and all-ones are materialized with special
4671   // instructions rather than being loaded.
4672   return !ISD::isBuildVectorAllZeros(N) &&
4673          !ISD::isBuildVectorAllOnes(N);
4674 }
4675
4676 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4677 /// match movlp{s|d}. The lower half elements should come from lower half of
4678 /// V1 (and in order), and the upper half elements should come from the upper
4679 /// half of V2 (and in order). And since V1 will become the source of the
4680 /// MOVLP, it must be either a vector load or a scalar load to vector.
4681 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4682                                ArrayRef<int> Mask, MVT VT) {
4683   if (!VT.is128BitVector())
4684     return false;
4685
4686   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4687     return false;
4688   // Is V2 is a vector load, don't do this transformation. We will try to use
4689   // load folding shufps op.
4690   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4691     return false;
4692
4693   unsigned NumElems = VT.getVectorNumElements();
4694
4695   if (NumElems != 2 && NumElems != 4)
4696     return false;
4697   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4698     if (!isUndefOrEqual(Mask[i], i))
4699       return false;
4700   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4701     if (!isUndefOrEqual(Mask[i], i+NumElems))
4702       return false;
4703   return true;
4704 }
4705
4706 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4707 /// all the same.
4708 static bool isSplatVector(SDNode *N) {
4709   if (N->getOpcode() != ISD::BUILD_VECTOR)
4710     return false;
4711
4712   SDValue SplatValue = N->getOperand(0);
4713   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4714     if (N->getOperand(i) != SplatValue)
4715       return false;
4716   return true;
4717 }
4718
4719 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4720 /// to an zero vector.
4721 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4722 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4723   SDValue V1 = N->getOperand(0);
4724   SDValue V2 = N->getOperand(1);
4725   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4726   for (unsigned i = 0; i != NumElems; ++i) {
4727     int Idx = N->getMaskElt(i);
4728     if (Idx >= (int)NumElems) {
4729       unsigned Opc = V2.getOpcode();
4730       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4731         continue;
4732       if (Opc != ISD::BUILD_VECTOR ||
4733           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4734         return false;
4735     } else if (Idx >= 0) {
4736       unsigned Opc = V1.getOpcode();
4737       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4738         continue;
4739       if (Opc != ISD::BUILD_VECTOR ||
4740           !X86::isZeroNode(V1.getOperand(Idx)))
4741         return false;
4742     }
4743   }
4744   return true;
4745 }
4746
4747 /// getZeroVector - Returns a vector of specified type with all zero elements.
4748 ///
4749 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4750                              SelectionDAG &DAG, SDLoc dl) {
4751   assert(VT.isVector() && "Expected a vector type");
4752
4753   // Always build SSE zero vectors as <4 x i32> bitcasted
4754   // to their dest type. This ensures they get CSE'd.
4755   SDValue Vec;
4756   if (VT.is128BitVector()) {  // SSE
4757     if (Subtarget->hasSSE2()) {  // SSE2
4758       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4759       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4760     } else { // SSE1
4761       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4762       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4763     }
4764   } else if (VT.is256BitVector()) { // AVX
4765     if (Subtarget->hasInt256()) { // AVX2
4766       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4767       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4768       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4769                         array_lengthof(Ops));
4770     } else {
4771       // 256-bit logic and arithmetic instructions in AVX are all
4772       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4773       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4774       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4775       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4776                         array_lengthof(Ops));
4777     }
4778   } else if (VT.is512BitVector()) { // AVX-512
4779       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4780       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4781                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4782       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops, 16);
4783   } else
4784     llvm_unreachable("Unexpected vector type");
4785
4786   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4787 }
4788
4789 /// getOnesVector - Returns a vector of specified type with all bits set.
4790 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4791 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4792 /// Then bitcast to their original type, ensuring they get CSE'd.
4793 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4794                              SDLoc dl) {
4795   assert(VT.isVector() && "Expected a vector type");
4796
4797   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4798   SDValue Vec;
4799   if (VT.is256BitVector()) {
4800     if (HasInt256) { // AVX2
4801       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4802       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4803                         array_lengthof(Ops));
4804     } else { // AVX
4805       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4806       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4807     }
4808   } else if (VT.is128BitVector()) {
4809     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4810   } else
4811     llvm_unreachable("Unexpected vector type");
4812
4813   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4814 }
4815
4816 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4817 /// that point to V2 points to its first element.
4818 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4819   for (unsigned i = 0; i != NumElems; ++i) {
4820     if (Mask[i] > (int)NumElems) {
4821       Mask[i] = NumElems;
4822     }
4823   }
4824 }
4825
4826 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4827 /// operation of specified width.
4828 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4829                        SDValue V2) {
4830   unsigned NumElems = VT.getVectorNumElements();
4831   SmallVector<int, 8> Mask;
4832   Mask.push_back(NumElems);
4833   for (unsigned i = 1; i != NumElems; ++i)
4834     Mask.push_back(i);
4835   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4836 }
4837
4838 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4839 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4840                           SDValue V2) {
4841   unsigned NumElems = VT.getVectorNumElements();
4842   SmallVector<int, 8> Mask;
4843   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4844     Mask.push_back(i);
4845     Mask.push_back(i + NumElems);
4846   }
4847   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4848 }
4849
4850 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4851 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4852                           SDValue V2) {
4853   unsigned NumElems = VT.getVectorNumElements();
4854   SmallVector<int, 8> Mask;
4855   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4856     Mask.push_back(i + Half);
4857     Mask.push_back(i + NumElems + Half);
4858   }
4859   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4860 }
4861
4862 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4863 // a generic shuffle instruction because the target has no such instructions.
4864 // Generate shuffles which repeat i16 and i8 several times until they can be
4865 // represented by v4f32 and then be manipulated by target suported shuffles.
4866 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4867   MVT VT = V.getSimpleValueType();
4868   int NumElems = VT.getVectorNumElements();
4869   SDLoc dl(V);
4870
4871   while (NumElems > 4) {
4872     if (EltNo < NumElems/2) {
4873       V = getUnpackl(DAG, dl, VT, V, V);
4874     } else {
4875       V = getUnpackh(DAG, dl, VT, V, V);
4876       EltNo -= NumElems/2;
4877     }
4878     NumElems >>= 1;
4879   }
4880   return V;
4881 }
4882
4883 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4884 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4885   MVT VT = V.getSimpleValueType();
4886   SDLoc dl(V);
4887
4888   if (VT.is128BitVector()) {
4889     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4890     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4891     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4892                              &SplatMask[0]);
4893   } else if (VT.is256BitVector()) {
4894     // To use VPERMILPS to splat scalars, the second half of indicies must
4895     // refer to the higher part, which is a duplication of the lower one,
4896     // because VPERMILPS can only handle in-lane permutations.
4897     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4898                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4899
4900     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4901     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4902                              &SplatMask[0]);
4903   } else
4904     llvm_unreachable("Vector size not supported");
4905
4906   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4907 }
4908
4909 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4910 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4911   MVT SrcVT = SV->getSimpleValueType(0);
4912   SDValue V1 = SV->getOperand(0);
4913   SDLoc dl(SV);
4914
4915   int EltNo = SV->getSplatIndex();
4916   int NumElems = SrcVT.getVectorNumElements();
4917   bool Is256BitVec = SrcVT.is256BitVector();
4918
4919   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4920          "Unknown how to promote splat for type");
4921
4922   // Extract the 128-bit part containing the splat element and update
4923   // the splat element index when it refers to the higher register.
4924   if (Is256BitVec) {
4925     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4926     if (EltNo >= NumElems/2)
4927       EltNo -= NumElems/2;
4928   }
4929
4930   // All i16 and i8 vector types can't be used directly by a generic shuffle
4931   // instruction because the target has no such instruction. Generate shuffles
4932   // which repeat i16 and i8 several times until they fit in i32, and then can
4933   // be manipulated by target suported shuffles.
4934   MVT EltVT = SrcVT.getVectorElementType();
4935   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4936     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4937
4938   // Recreate the 256-bit vector and place the same 128-bit vector
4939   // into the low and high part. This is necessary because we want
4940   // to use VPERM* to shuffle the vectors
4941   if (Is256BitVec) {
4942     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4943   }
4944
4945   return getLegalSplat(DAG, V1, EltNo);
4946 }
4947
4948 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4949 /// vector of zero or undef vector.  This produces a shuffle where the low
4950 /// element of V2 is swizzled into the zero/undef vector, landing at element
4951 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4952 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4953                                            bool IsZero,
4954                                            const X86Subtarget *Subtarget,
4955                                            SelectionDAG &DAG) {
4956   MVT VT = V2.getSimpleValueType();
4957   SDValue V1 = IsZero
4958     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4959   unsigned NumElems = VT.getVectorNumElements();
4960   SmallVector<int, 16> MaskVec;
4961   for (unsigned i = 0; i != NumElems; ++i)
4962     // If this is the insertion idx, put the low elt of V2 here.
4963     MaskVec.push_back(i == Idx ? NumElems : i);
4964   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4965 }
4966
4967 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4968 /// target specific opcode. Returns true if the Mask could be calculated.
4969 /// Sets IsUnary to true if only uses one source.
4970 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4971                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4972   unsigned NumElems = VT.getVectorNumElements();
4973   SDValue ImmN;
4974
4975   IsUnary = false;
4976   switch(N->getOpcode()) {
4977   case X86ISD::SHUFP:
4978     ImmN = N->getOperand(N->getNumOperands()-1);
4979     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4980     break;
4981   case X86ISD::UNPCKH:
4982     DecodeUNPCKHMask(VT, Mask);
4983     break;
4984   case X86ISD::UNPCKL:
4985     DecodeUNPCKLMask(VT, Mask);
4986     break;
4987   case X86ISD::MOVHLPS:
4988     DecodeMOVHLPSMask(NumElems, Mask);
4989     break;
4990   case X86ISD::MOVLHPS:
4991     DecodeMOVLHPSMask(NumElems, Mask);
4992     break;
4993   case X86ISD::PALIGNR:
4994     ImmN = N->getOperand(N->getNumOperands()-1);
4995     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4996     break;
4997   case X86ISD::PSHUFD:
4998   case X86ISD::VPERMILP:
4999     ImmN = N->getOperand(N->getNumOperands()-1);
5000     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5001     IsUnary = true;
5002     break;
5003   case X86ISD::PSHUFHW:
5004     ImmN = N->getOperand(N->getNumOperands()-1);
5005     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5006     IsUnary = true;
5007     break;
5008   case X86ISD::PSHUFLW:
5009     ImmN = N->getOperand(N->getNumOperands()-1);
5010     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5011     IsUnary = true;
5012     break;
5013   case X86ISD::VPERMI:
5014     ImmN = N->getOperand(N->getNumOperands()-1);
5015     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5016     IsUnary = true;
5017     break;
5018   case X86ISD::MOVSS:
5019   case X86ISD::MOVSD: {
5020     // The index 0 always comes from the first element of the second source,
5021     // this is why MOVSS and MOVSD are used in the first place. The other
5022     // elements come from the other positions of the first source vector
5023     Mask.push_back(NumElems);
5024     for (unsigned i = 1; i != NumElems; ++i) {
5025       Mask.push_back(i);
5026     }
5027     break;
5028   }
5029   case X86ISD::VPERM2X128:
5030     ImmN = N->getOperand(N->getNumOperands()-1);
5031     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5032     if (Mask.empty()) return false;
5033     break;
5034   case X86ISD::MOVDDUP:
5035   case X86ISD::MOVLHPD:
5036   case X86ISD::MOVLPD:
5037   case X86ISD::MOVLPS:
5038   case X86ISD::MOVSHDUP:
5039   case X86ISD::MOVSLDUP:
5040     // Not yet implemented
5041     return false;
5042   default: llvm_unreachable("unknown target shuffle node");
5043   }
5044
5045   return true;
5046 }
5047
5048 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5049 /// element of the result of the vector shuffle.
5050 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5051                                    unsigned Depth) {
5052   if (Depth == 6)
5053     return SDValue();  // Limit search depth.
5054
5055   SDValue V = SDValue(N, 0);
5056   EVT VT = V.getValueType();
5057   unsigned Opcode = V.getOpcode();
5058
5059   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5060   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5061     int Elt = SV->getMaskElt(Index);
5062
5063     if (Elt < 0)
5064       return DAG.getUNDEF(VT.getVectorElementType());
5065
5066     unsigned NumElems = VT.getVectorNumElements();
5067     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5068                                          : SV->getOperand(1);
5069     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5070   }
5071
5072   // Recurse into target specific vector shuffles to find scalars.
5073   if (isTargetShuffle(Opcode)) {
5074     MVT ShufVT = V.getSimpleValueType();
5075     unsigned NumElems = ShufVT.getVectorNumElements();
5076     SmallVector<int, 16> ShuffleMask;
5077     bool IsUnary;
5078
5079     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5080       return SDValue();
5081
5082     int Elt = ShuffleMask[Index];
5083     if (Elt < 0)
5084       return DAG.getUNDEF(ShufVT.getVectorElementType());
5085
5086     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5087                                          : N->getOperand(1);
5088     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5089                                Depth+1);
5090   }
5091
5092   // Actual nodes that may contain scalar elements
5093   if (Opcode == ISD::BITCAST) {
5094     V = V.getOperand(0);
5095     EVT SrcVT = V.getValueType();
5096     unsigned NumElems = VT.getVectorNumElements();
5097
5098     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5099       return SDValue();
5100   }
5101
5102   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5103     return (Index == 0) ? V.getOperand(0)
5104                         : DAG.getUNDEF(VT.getVectorElementType());
5105
5106   if (V.getOpcode() == ISD::BUILD_VECTOR)
5107     return V.getOperand(Index);
5108
5109   return SDValue();
5110 }
5111
5112 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5113 /// shuffle operation which come from a consecutively from a zero. The
5114 /// search can start in two different directions, from left or right.
5115 /// We count undefs as zeros until PreferredNum is reached.
5116 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5117                                          unsigned NumElems, bool ZerosFromLeft,
5118                                          SelectionDAG &DAG,
5119                                          unsigned PreferredNum = -1U) {
5120   unsigned NumZeros = 0;
5121   for (unsigned i = 0; i != NumElems; ++i) {
5122     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5123     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5124     if (!Elt.getNode())
5125       break;
5126
5127     if (X86::isZeroNode(Elt))
5128       ++NumZeros;
5129     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5130       NumZeros = std::min(NumZeros + 1, PreferredNum);
5131     else
5132       break;
5133   }
5134
5135   return NumZeros;
5136 }
5137
5138 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5139 /// correspond consecutively to elements from one of the vector operands,
5140 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5141 static
5142 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5143                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5144                               unsigned NumElems, unsigned &OpNum) {
5145   bool SeenV1 = false;
5146   bool SeenV2 = false;
5147
5148   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5149     int Idx = SVOp->getMaskElt(i);
5150     // Ignore undef indicies
5151     if (Idx < 0)
5152       continue;
5153
5154     if (Idx < (int)NumElems)
5155       SeenV1 = true;
5156     else
5157       SeenV2 = true;
5158
5159     // Only accept consecutive elements from the same vector
5160     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5161       return false;
5162   }
5163
5164   OpNum = SeenV1 ? 0 : 1;
5165   return true;
5166 }
5167
5168 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5169 /// logical left shift of a vector.
5170 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5171                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5172   unsigned NumElems =
5173     SVOp->getSimpleValueType(0).getVectorNumElements();
5174   unsigned NumZeros = getNumOfConsecutiveZeros(
5175       SVOp, NumElems, false /* check zeros from right */, DAG,
5176       SVOp->getMaskElt(0));
5177   unsigned OpSrc;
5178
5179   if (!NumZeros)
5180     return false;
5181
5182   // Considering the elements in the mask that are not consecutive zeros,
5183   // check if they consecutively come from only one of the source vectors.
5184   //
5185   //               V1 = {X, A, B, C}     0
5186   //                         \  \  \    /
5187   //   vector_shuffle V1, V2 <1, 2, 3, X>
5188   //
5189   if (!isShuffleMaskConsecutive(SVOp,
5190             0,                   // Mask Start Index
5191             NumElems-NumZeros,   // Mask End Index(exclusive)
5192             NumZeros,            // Where to start looking in the src vector
5193             NumElems,            // Number of elements in vector
5194             OpSrc))              // Which source operand ?
5195     return false;
5196
5197   isLeft = false;
5198   ShAmt = NumZeros;
5199   ShVal = SVOp->getOperand(OpSrc);
5200   return true;
5201 }
5202
5203 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5204 /// logical left shift of a vector.
5205 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5206                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5207   unsigned NumElems =
5208     SVOp->getSimpleValueType(0).getVectorNumElements();
5209   unsigned NumZeros = getNumOfConsecutiveZeros(
5210       SVOp, NumElems, true /* check zeros from left */, DAG,
5211       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5212   unsigned OpSrc;
5213
5214   if (!NumZeros)
5215     return false;
5216
5217   // Considering the elements in the mask that are not consecutive zeros,
5218   // check if they consecutively come from only one of the source vectors.
5219   //
5220   //                           0    { A, B, X, X } = V2
5221   //                          / \    /  /
5222   //   vector_shuffle V1, V2 <X, X, 4, 5>
5223   //
5224   if (!isShuffleMaskConsecutive(SVOp,
5225             NumZeros,     // Mask Start Index
5226             NumElems,     // Mask End Index(exclusive)
5227             0,            // Where to start looking in the src vector
5228             NumElems,     // Number of elements in vector
5229             OpSrc))       // Which source operand ?
5230     return false;
5231
5232   isLeft = true;
5233   ShAmt = NumZeros;
5234   ShVal = SVOp->getOperand(OpSrc);
5235   return true;
5236 }
5237
5238 /// isVectorShift - Returns true if the shuffle can be implemented as a
5239 /// logical left or right shift of a vector.
5240 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5241                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5242   // Although the logic below support any bitwidth size, there are no
5243   // shift instructions which handle more than 128-bit vectors.
5244   if (!SVOp->getSimpleValueType(0).is128BitVector())
5245     return false;
5246
5247   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5248       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5249     return true;
5250
5251   return false;
5252 }
5253
5254 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5255 ///
5256 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5257                                        unsigned NumNonZero, unsigned NumZero,
5258                                        SelectionDAG &DAG,
5259                                        const X86Subtarget* Subtarget,
5260                                        const TargetLowering &TLI) {
5261   if (NumNonZero > 8)
5262     return SDValue();
5263
5264   SDLoc dl(Op);
5265   SDValue V(0, 0);
5266   bool First = true;
5267   for (unsigned i = 0; i < 16; ++i) {
5268     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5269     if (ThisIsNonZero && First) {
5270       if (NumZero)
5271         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5272       else
5273         V = DAG.getUNDEF(MVT::v8i16);
5274       First = false;
5275     }
5276
5277     if ((i & 1) != 0) {
5278       SDValue ThisElt(0, 0), LastElt(0, 0);
5279       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5280       if (LastIsNonZero) {
5281         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5282                               MVT::i16, Op.getOperand(i-1));
5283       }
5284       if (ThisIsNonZero) {
5285         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5286         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5287                               ThisElt, DAG.getConstant(8, MVT::i8));
5288         if (LastIsNonZero)
5289           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5290       } else
5291         ThisElt = LastElt;
5292
5293       if (ThisElt.getNode())
5294         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5295                         DAG.getIntPtrConstant(i/2));
5296     }
5297   }
5298
5299   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5300 }
5301
5302 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5303 ///
5304 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5305                                      unsigned NumNonZero, unsigned NumZero,
5306                                      SelectionDAG &DAG,
5307                                      const X86Subtarget* Subtarget,
5308                                      const TargetLowering &TLI) {
5309   if (NumNonZero > 4)
5310     return SDValue();
5311
5312   SDLoc dl(Op);
5313   SDValue V(0, 0);
5314   bool First = true;
5315   for (unsigned i = 0; i < 8; ++i) {
5316     bool isNonZero = (NonZeros & (1 << i)) != 0;
5317     if (isNonZero) {
5318       if (First) {
5319         if (NumZero)
5320           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5321         else
5322           V = DAG.getUNDEF(MVT::v8i16);
5323         First = false;
5324       }
5325       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5326                       MVT::v8i16, V, Op.getOperand(i),
5327                       DAG.getIntPtrConstant(i));
5328     }
5329   }
5330
5331   return V;
5332 }
5333
5334 /// getVShift - Return a vector logical shift node.
5335 ///
5336 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5337                          unsigned NumBits, SelectionDAG &DAG,
5338                          const TargetLowering &TLI, SDLoc dl) {
5339   assert(VT.is128BitVector() && "Unknown type for VShift");
5340   EVT ShVT = MVT::v2i64;
5341   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5342   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5343   return DAG.getNode(ISD::BITCAST, dl, VT,
5344                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5345                              DAG.getConstant(NumBits,
5346                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5347 }
5348
5349 static SDValue
5350 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5351
5352   // Check if the scalar load can be widened into a vector load. And if
5353   // the address is "base + cst" see if the cst can be "absorbed" into
5354   // the shuffle mask.
5355   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5356     SDValue Ptr = LD->getBasePtr();
5357     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5358       return SDValue();
5359     EVT PVT = LD->getValueType(0);
5360     if (PVT != MVT::i32 && PVT != MVT::f32)
5361       return SDValue();
5362
5363     int FI = -1;
5364     int64_t Offset = 0;
5365     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5366       FI = FINode->getIndex();
5367       Offset = 0;
5368     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5369                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5370       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5371       Offset = Ptr.getConstantOperandVal(1);
5372       Ptr = Ptr.getOperand(0);
5373     } else {
5374       return SDValue();
5375     }
5376
5377     // FIXME: 256-bit vector instructions don't require a strict alignment,
5378     // improve this code to support it better.
5379     unsigned RequiredAlign = VT.getSizeInBits()/8;
5380     SDValue Chain = LD->getChain();
5381     // Make sure the stack object alignment is at least 16 or 32.
5382     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5383     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5384       if (MFI->isFixedObjectIndex(FI)) {
5385         // Can't change the alignment. FIXME: It's possible to compute
5386         // the exact stack offset and reference FI + adjust offset instead.
5387         // If someone *really* cares about this. That's the way to implement it.
5388         return SDValue();
5389       } else {
5390         MFI->setObjectAlignment(FI, RequiredAlign);
5391       }
5392     }
5393
5394     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5395     // Ptr + (Offset & ~15).
5396     if (Offset < 0)
5397       return SDValue();
5398     if ((Offset % RequiredAlign) & 3)
5399       return SDValue();
5400     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5401     if (StartOffset)
5402       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5403                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5404
5405     int EltNo = (Offset - StartOffset) >> 2;
5406     unsigned NumElems = VT.getVectorNumElements();
5407
5408     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5409     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5410                              LD->getPointerInfo().getWithOffset(StartOffset),
5411                              false, false, false, 0);
5412
5413     SmallVector<int, 8> Mask;
5414     for (unsigned i = 0; i != NumElems; ++i)
5415       Mask.push_back(EltNo);
5416
5417     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5418   }
5419
5420   return SDValue();
5421 }
5422
5423 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5424 /// vector of type 'VT', see if the elements can be replaced by a single large
5425 /// load which has the same value as a build_vector whose operands are 'elts'.
5426 ///
5427 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5428 ///
5429 /// FIXME: we'd also like to handle the case where the last elements are zero
5430 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5431 /// There's even a handy isZeroNode for that purpose.
5432 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5433                                         SDLoc &DL, SelectionDAG &DAG,
5434                                         bool isAfterLegalize) {
5435   EVT EltVT = VT.getVectorElementType();
5436   unsigned NumElems = Elts.size();
5437
5438   LoadSDNode *LDBase = NULL;
5439   unsigned LastLoadedElt = -1U;
5440
5441   // For each element in the initializer, see if we've found a load or an undef.
5442   // If we don't find an initial load element, or later load elements are
5443   // non-consecutive, bail out.
5444   for (unsigned i = 0; i < NumElems; ++i) {
5445     SDValue Elt = Elts[i];
5446
5447     if (!Elt.getNode() ||
5448         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5449       return SDValue();
5450     if (!LDBase) {
5451       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5452         return SDValue();
5453       LDBase = cast<LoadSDNode>(Elt.getNode());
5454       LastLoadedElt = i;
5455       continue;
5456     }
5457     if (Elt.getOpcode() == ISD::UNDEF)
5458       continue;
5459
5460     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5461     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5462       return SDValue();
5463     LastLoadedElt = i;
5464   }
5465
5466   // If we have found an entire vector of loads and undefs, then return a large
5467   // load of the entire vector width starting at the base pointer.  If we found
5468   // consecutive loads for the low half, generate a vzext_load node.
5469   if (LastLoadedElt == NumElems - 1) {
5470
5471     if (isAfterLegalize &&
5472         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5473       return SDValue();
5474
5475     SDValue NewLd = SDValue();
5476
5477     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5478       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5479                           LDBase->getPointerInfo(),
5480                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5481                           LDBase->isInvariant(), 0);
5482     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5483                         LDBase->getPointerInfo(),
5484                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5485                         LDBase->isInvariant(), LDBase->getAlignment());
5486
5487     if (LDBase->hasAnyUseOfValue(1)) {
5488       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5489                                      SDValue(LDBase, 1),
5490                                      SDValue(NewLd.getNode(), 1));
5491       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5492       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5493                              SDValue(NewLd.getNode(), 1));
5494     }
5495
5496     return NewLd;
5497   }
5498   if (NumElems == 4 && LastLoadedElt == 1 &&
5499       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5500     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5501     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5502     SDValue ResNode =
5503         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5504                                 array_lengthof(Ops), MVT::i64,
5505                                 LDBase->getPointerInfo(),
5506                                 LDBase->getAlignment(),
5507                                 false/*isVolatile*/, true/*ReadMem*/,
5508                                 false/*WriteMem*/);
5509
5510     // Make sure the newly-created LOAD is in the same position as LDBase in
5511     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5512     // update uses of LDBase's output chain to use the TokenFactor.
5513     if (LDBase->hasAnyUseOfValue(1)) {
5514       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5515                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5516       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5517       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5518                              SDValue(ResNode.getNode(), 1));
5519     }
5520
5521     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5522   }
5523   return SDValue();
5524 }
5525
5526 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5527 /// to generate a splat value for the following cases:
5528 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5529 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5530 /// a scalar load, or a constant.
5531 /// The VBROADCAST node is returned when a pattern is found,
5532 /// or SDValue() otherwise.
5533 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5534                                     SelectionDAG &DAG) {
5535   if (!Subtarget->hasFp256())
5536     return SDValue();
5537
5538   MVT VT = Op.getSimpleValueType();
5539   SDLoc dl(Op);
5540
5541   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5542          "Unsupported vector type for broadcast.");
5543
5544   SDValue Ld;
5545   bool ConstSplatVal;
5546
5547   switch (Op.getOpcode()) {
5548     default:
5549       // Unknown pattern found.
5550       return SDValue();
5551
5552     case ISD::BUILD_VECTOR: {
5553       // The BUILD_VECTOR node must be a splat.
5554       if (!isSplatVector(Op.getNode()))
5555         return SDValue();
5556
5557       Ld = Op.getOperand(0);
5558       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5559                      Ld.getOpcode() == ISD::ConstantFP);
5560
5561       // The suspected load node has several users. Make sure that all
5562       // of its users are from the BUILD_VECTOR node.
5563       // Constants may have multiple users.
5564       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5565         return SDValue();
5566       break;
5567     }
5568
5569     case ISD::VECTOR_SHUFFLE: {
5570       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5571
5572       // Shuffles must have a splat mask where the first element is
5573       // broadcasted.
5574       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5575         return SDValue();
5576
5577       SDValue Sc = Op.getOperand(0);
5578       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5579           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5580
5581         if (!Subtarget->hasInt256())
5582           return SDValue();
5583
5584         // Use the register form of the broadcast instruction available on AVX2.
5585         if (VT.getSizeInBits() >= 256)
5586           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5587         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5588       }
5589
5590       Ld = Sc.getOperand(0);
5591       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5592                        Ld.getOpcode() == ISD::ConstantFP);
5593
5594       // The scalar_to_vector node and the suspected
5595       // load node must have exactly one user.
5596       // Constants may have multiple users.
5597
5598       // AVX-512 has register version of the broadcast
5599       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5600         Ld.getValueType().getSizeInBits() >= 32;
5601       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5602           !hasRegVer))
5603         return SDValue();
5604       break;
5605     }
5606   }
5607
5608   bool IsGE256 = (VT.getSizeInBits() >= 256);
5609
5610   // Handle the broadcasting a single constant scalar from the constant pool
5611   // into a vector. On Sandybridge it is still better to load a constant vector
5612   // from the constant pool and not to broadcast it from a scalar.
5613   if (ConstSplatVal && Subtarget->hasInt256()) {
5614     EVT CVT = Ld.getValueType();
5615     assert(!CVT.isVector() && "Must not broadcast a vector type");
5616     unsigned ScalarSize = CVT.getSizeInBits();
5617
5618     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5619       const Constant *C = 0;
5620       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5621         C = CI->getConstantIntValue();
5622       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5623         C = CF->getConstantFPValue();
5624
5625       assert(C && "Invalid constant type");
5626
5627       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5628       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5629       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5630       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5631                        MachinePointerInfo::getConstantPool(),
5632                        false, false, false, Alignment);
5633
5634       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5635     }
5636   }
5637
5638   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5639   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5640
5641   // Handle AVX2 in-register broadcasts.
5642   if (!IsLoad && Subtarget->hasInt256() &&
5643       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5644     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5645
5646   // The scalar source must be a normal load.
5647   if (!IsLoad)
5648     return SDValue();
5649
5650   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5651     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5652
5653   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5654   // double since there is no vbroadcastsd xmm
5655   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5656     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5657       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5658   }
5659
5660   // Unsupported broadcast.
5661   return SDValue();
5662 }
5663
5664 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5665   MVT VT = Op.getSimpleValueType();
5666
5667   // Skip if insert_vec_elt is not supported.
5668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5669   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5670     return SDValue();
5671
5672   SDLoc DL(Op);
5673   unsigned NumElems = Op.getNumOperands();
5674
5675   SDValue VecIn1;
5676   SDValue VecIn2;
5677   SmallVector<unsigned, 4> InsertIndices;
5678   SmallVector<int, 8> Mask(NumElems, -1);
5679
5680   for (unsigned i = 0; i != NumElems; ++i) {
5681     unsigned Opc = Op.getOperand(i).getOpcode();
5682
5683     if (Opc == ISD::UNDEF)
5684       continue;
5685
5686     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5687       // Quit if more than 1 elements need inserting.
5688       if (InsertIndices.size() > 1)
5689         return SDValue();
5690
5691       InsertIndices.push_back(i);
5692       continue;
5693     }
5694
5695     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5696     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5697
5698     // Quit if extracted from vector of different type.
5699     if (ExtractedFromVec.getValueType() != VT)
5700       return SDValue();
5701
5702     // Quit if non-constant index.
5703     if (!isa<ConstantSDNode>(ExtIdx))
5704       return SDValue();
5705
5706     if (VecIn1.getNode() == 0)
5707       VecIn1 = ExtractedFromVec;
5708     else if (VecIn1 != ExtractedFromVec) {
5709       if (VecIn2.getNode() == 0)
5710         VecIn2 = ExtractedFromVec;
5711       else if (VecIn2 != ExtractedFromVec)
5712         // Quit if more than 2 vectors to shuffle
5713         return SDValue();
5714     }
5715
5716     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5717
5718     if (ExtractedFromVec == VecIn1)
5719       Mask[i] = Idx;
5720     else if (ExtractedFromVec == VecIn2)
5721       Mask[i] = Idx + NumElems;
5722   }
5723
5724   if (VecIn1.getNode() == 0)
5725     return SDValue();
5726
5727   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5728   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5729   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5730     unsigned Idx = InsertIndices[i];
5731     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5732                      DAG.getIntPtrConstant(Idx));
5733   }
5734
5735   return NV;
5736 }
5737
5738 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5739 SDValue
5740 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5741
5742   MVT VT = Op.getSimpleValueType();
5743   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5744          "Unexpected type in LowerBUILD_VECTORvXi1!");
5745
5746   SDLoc dl(Op);
5747   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5748     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5749     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5750                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5751     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5752                        Ops, VT.getVectorNumElements());
5753   }
5754
5755   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5756     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5757     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5758                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5759     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5760                        Ops, VT.getVectorNumElements());
5761   }
5762
5763   bool AllContants = true;
5764   uint64_t Immediate = 0;
5765   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5766     SDValue In = Op.getOperand(idx);
5767     if (In.getOpcode() == ISD::UNDEF)
5768       continue;
5769     if (!isa<ConstantSDNode>(In)) {
5770       AllContants = false;
5771       break;
5772     }
5773     if (cast<ConstantSDNode>(In)->getZExtValue())
5774       Immediate |= (1ULL << idx);
5775   }
5776
5777   if (AllContants) {
5778     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5779       DAG.getConstant(Immediate, MVT::i16));
5780     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5781                        DAG.getIntPtrConstant(0));
5782   }
5783
5784   // Splat vector (with undefs)
5785   SDValue In = Op.getOperand(0);
5786   for (unsigned i = 1, e = Op.getNumOperands(); i != e; ++i) {
5787     if (Op.getOperand(i) != In && Op.getOperand(i).getOpcode() != ISD::UNDEF)
5788       llvm_unreachable("Unsupported predicate operation");
5789   }
5790
5791   SDValue EFLAGS, X86CC;
5792   if (In.getOpcode() == ISD::SETCC) {
5793     SDValue Op0 = In.getOperand(0);
5794     SDValue Op1 = In.getOperand(1);
5795     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5796     bool isFP = Op1.getValueType().isFloatingPoint();
5797     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5798
5799     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5800
5801     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5802     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5803     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5804   } else if (In.getOpcode() == X86ISD::SETCC) {
5805     X86CC = In.getOperand(0);
5806     EFLAGS = In.getOperand(1);
5807   } else {
5808     // The algorithm:
5809     //   Bit1 = In & 0x1
5810     //   if (Bit1 != 0)
5811     //     ZF = 0
5812     //   else
5813     //     ZF = 1
5814     //   if (ZF == 0)
5815     //     res = allOnes ### CMOVNE -1, %res
5816     //   else
5817     //     res = allZero
5818     MVT InVT = In.getSimpleValueType();
5819     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5820     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5821     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5822   }
5823
5824   if (VT == MVT::v16i1) {
5825     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5826     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5827     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5828           Cst0, Cst1, X86CC, EFLAGS);
5829     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5830   }
5831
5832   if (VT == MVT::v8i1) {
5833     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5834     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5835     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5836           Cst0, Cst1, X86CC, EFLAGS);
5837     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5838     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5839   }
5840   llvm_unreachable("Unsupported predicate operation");
5841 }
5842
5843 SDValue
5844 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5845   SDLoc dl(Op);
5846
5847   MVT VT = Op.getSimpleValueType();
5848   MVT ExtVT = VT.getVectorElementType();
5849   unsigned NumElems = Op.getNumOperands();
5850
5851   // Generate vectors for predicate vectors.
5852   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5853     return LowerBUILD_VECTORvXi1(Op, DAG);
5854
5855   // Vectors containing all zeros can be matched by pxor and xorps later
5856   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5857     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5858     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5859     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5860       return Op;
5861
5862     return getZeroVector(VT, Subtarget, DAG, dl);
5863   }
5864
5865   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5866   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5867   // vpcmpeqd on 256-bit vectors.
5868   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5869     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5870       return Op;
5871
5872     if (!VT.is512BitVector())
5873       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5874   }
5875
5876   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5877   if (Broadcast.getNode())
5878     return Broadcast;
5879
5880   unsigned EVTBits = ExtVT.getSizeInBits();
5881
5882   unsigned NumZero  = 0;
5883   unsigned NumNonZero = 0;
5884   unsigned NonZeros = 0;
5885   bool IsAllConstants = true;
5886   SmallSet<SDValue, 8> Values;
5887   for (unsigned i = 0; i < NumElems; ++i) {
5888     SDValue Elt = Op.getOperand(i);
5889     if (Elt.getOpcode() == ISD::UNDEF)
5890       continue;
5891     Values.insert(Elt);
5892     if (Elt.getOpcode() != ISD::Constant &&
5893         Elt.getOpcode() != ISD::ConstantFP)
5894       IsAllConstants = false;
5895     if (X86::isZeroNode(Elt))
5896       NumZero++;
5897     else {
5898       NonZeros |= (1 << i);
5899       NumNonZero++;
5900     }
5901   }
5902
5903   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5904   if (NumNonZero == 0)
5905     return DAG.getUNDEF(VT);
5906
5907   // Special case for single non-zero, non-undef, element.
5908   if (NumNonZero == 1) {
5909     unsigned Idx = countTrailingZeros(NonZeros);
5910     SDValue Item = Op.getOperand(Idx);
5911
5912     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5913     // the value are obviously zero, truncate the value to i32 and do the
5914     // insertion that way.  Only do this if the value is non-constant or if the
5915     // value is a constant being inserted into element 0.  It is cheaper to do
5916     // a constant pool load than it is to do a movd + shuffle.
5917     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5918         (!IsAllConstants || Idx == 0)) {
5919       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5920         // Handle SSE only.
5921         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5922         EVT VecVT = MVT::v4i32;
5923         unsigned VecElts = 4;
5924
5925         // Truncate the value (which may itself be a constant) to i32, and
5926         // convert it to a vector with movd (S2V+shuffle to zero extend).
5927         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5928         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5929         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5930
5931         // Now we have our 32-bit value zero extended in the low element of
5932         // a vector.  If Idx != 0, swizzle it into place.
5933         if (Idx != 0) {
5934           SmallVector<int, 4> Mask;
5935           Mask.push_back(Idx);
5936           for (unsigned i = 1; i != VecElts; ++i)
5937             Mask.push_back(i);
5938           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5939                                       &Mask[0]);
5940         }
5941         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5942       }
5943     }
5944
5945     // If we have a constant or non-constant insertion into the low element of
5946     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5947     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5948     // depending on what the source datatype is.
5949     if (Idx == 0) {
5950       if (NumZero == 0)
5951         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5952
5953       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5954           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5955         if (VT.is256BitVector() || VT.is512BitVector()) {
5956           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5957           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5958                              Item, DAG.getIntPtrConstant(0));
5959         }
5960         assert(VT.is128BitVector() && "Expected an SSE value type!");
5961         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5962         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5963         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5964       }
5965
5966       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5967         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5968         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5969         if (VT.is256BitVector()) {
5970           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5971           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5972         } else {
5973           assert(VT.is128BitVector() && "Expected an SSE value type!");
5974           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5975         }
5976         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5977       }
5978     }
5979
5980     // Is it a vector logical left shift?
5981     if (NumElems == 2 && Idx == 1 &&
5982         X86::isZeroNode(Op.getOperand(0)) &&
5983         !X86::isZeroNode(Op.getOperand(1))) {
5984       unsigned NumBits = VT.getSizeInBits();
5985       return getVShift(true, VT,
5986                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5987                                    VT, Op.getOperand(1)),
5988                        NumBits/2, DAG, *this, dl);
5989     }
5990
5991     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5992       return SDValue();
5993
5994     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5995     // is a non-constant being inserted into an element other than the low one,
5996     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5997     // movd/movss) to move this into the low element, then shuffle it into
5998     // place.
5999     if (EVTBits == 32) {
6000       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6001
6002       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6003       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6004       SmallVector<int, 8> MaskVec;
6005       for (unsigned i = 0; i != NumElems; ++i)
6006         MaskVec.push_back(i == Idx ? 0 : 1);
6007       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6008     }
6009   }
6010
6011   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6012   if (Values.size() == 1) {
6013     if (EVTBits == 32) {
6014       // Instead of a shuffle like this:
6015       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6016       // Check if it's possible to issue this instead.
6017       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6018       unsigned Idx = countTrailingZeros(NonZeros);
6019       SDValue Item = Op.getOperand(Idx);
6020       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6021         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6022     }
6023     return SDValue();
6024   }
6025
6026   // A vector full of immediates; various special cases are already
6027   // handled, so this is best done with a single constant-pool load.
6028   if (IsAllConstants)
6029     return SDValue();
6030
6031   // For AVX-length vectors, build the individual 128-bit pieces and use
6032   // shuffles to put them in place.
6033   if (VT.is256BitVector()) {
6034     SmallVector<SDValue, 32> V;
6035     for (unsigned i = 0; i != NumElems; ++i)
6036       V.push_back(Op.getOperand(i));
6037
6038     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6039
6040     // Build both the lower and upper subvector.
6041     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
6042     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
6043                                 NumElems/2);
6044
6045     // Recreate the wider vector with the lower and upper part.
6046     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6047   }
6048
6049   // Let legalizer expand 2-wide build_vectors.
6050   if (EVTBits == 64) {
6051     if (NumNonZero == 1) {
6052       // One half is zero or undef.
6053       unsigned Idx = countTrailingZeros(NonZeros);
6054       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6055                                  Op.getOperand(Idx));
6056       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6057     }
6058     return SDValue();
6059   }
6060
6061   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6062   if (EVTBits == 8 && NumElems == 16) {
6063     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6064                                         Subtarget, *this);
6065     if (V.getNode()) return V;
6066   }
6067
6068   if (EVTBits == 16 && NumElems == 8) {
6069     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6070                                       Subtarget, *this);
6071     if (V.getNode()) return V;
6072   }
6073
6074   // If element VT is == 32 bits, turn it into a number of shuffles.
6075   SmallVector<SDValue, 8> V(NumElems);
6076   if (NumElems == 4 && NumZero > 0) {
6077     for (unsigned i = 0; i < 4; ++i) {
6078       bool isZero = !(NonZeros & (1 << i));
6079       if (isZero)
6080         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6081       else
6082         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6083     }
6084
6085     for (unsigned i = 0; i < 2; ++i) {
6086       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6087         default: break;
6088         case 0:
6089           V[i] = V[i*2];  // Must be a zero vector.
6090           break;
6091         case 1:
6092           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6093           break;
6094         case 2:
6095           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6096           break;
6097         case 3:
6098           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6099           break;
6100       }
6101     }
6102
6103     bool Reverse1 = (NonZeros & 0x3) == 2;
6104     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6105     int MaskVec[] = {
6106       Reverse1 ? 1 : 0,
6107       Reverse1 ? 0 : 1,
6108       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6109       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6110     };
6111     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6112   }
6113
6114   if (Values.size() > 1 && VT.is128BitVector()) {
6115     // Check for a build vector of consecutive loads.
6116     for (unsigned i = 0; i < NumElems; ++i)
6117       V[i] = Op.getOperand(i);
6118
6119     // Check for elements which are consecutive loads.
6120     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6121     if (LD.getNode())
6122       return LD;
6123
6124     // Check for a build vector from mostly shuffle plus few inserting.
6125     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6126     if (Sh.getNode())
6127       return Sh;
6128
6129     // For SSE 4.1, use insertps to put the high elements into the low element.
6130     if (getSubtarget()->hasSSE41()) {
6131       SDValue Result;
6132       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6133         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6134       else
6135         Result = DAG.getUNDEF(VT);
6136
6137       for (unsigned i = 1; i < NumElems; ++i) {
6138         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6139         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6140                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6141       }
6142       return Result;
6143     }
6144
6145     // Otherwise, expand into a number of unpckl*, start by extending each of
6146     // our (non-undef) elements to the full vector width with the element in the
6147     // bottom slot of the vector (which generates no code for SSE).
6148     for (unsigned i = 0; i < NumElems; ++i) {
6149       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6150         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6151       else
6152         V[i] = DAG.getUNDEF(VT);
6153     }
6154
6155     // Next, we iteratively mix elements, e.g. for v4f32:
6156     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6157     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6158     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6159     unsigned EltStride = NumElems >> 1;
6160     while (EltStride != 0) {
6161       for (unsigned i = 0; i < EltStride; ++i) {
6162         // If V[i+EltStride] is undef and this is the first round of mixing,
6163         // then it is safe to just drop this shuffle: V[i] is already in the
6164         // right place, the one element (since it's the first round) being
6165         // inserted as undef can be dropped.  This isn't safe for successive
6166         // rounds because they will permute elements within both vectors.
6167         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6168             EltStride == NumElems/2)
6169           continue;
6170
6171         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6172       }
6173       EltStride >>= 1;
6174     }
6175     return V[0];
6176   }
6177   return SDValue();
6178 }
6179
6180 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6181 // to create 256-bit vectors from two other 128-bit ones.
6182 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6183   SDLoc dl(Op);
6184   MVT ResVT = Op.getSimpleValueType();
6185
6186   assert((ResVT.is256BitVector() ||
6187           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6188
6189   SDValue V1 = Op.getOperand(0);
6190   SDValue V2 = Op.getOperand(1);
6191   unsigned NumElems = ResVT.getVectorNumElements();
6192   if(ResVT.is256BitVector())
6193     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6194
6195   if (Op.getNumOperands() == 4) {
6196     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6197                                 ResVT.getVectorNumElements()/2);
6198     SDValue V3 = Op.getOperand(2);
6199     SDValue V4 = Op.getOperand(3);
6200     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6201       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6202   }
6203   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6204 }
6205
6206 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6207   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6208   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6209          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6210           Op.getNumOperands() == 4)));
6211
6212   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6213   // from two other 128-bit ones.
6214
6215   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6216   return LowerAVXCONCAT_VECTORS(Op, DAG);
6217 }
6218
6219 // Try to lower a shuffle node into a simple blend instruction.
6220 static SDValue
6221 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6222                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6223   SDValue V1 = SVOp->getOperand(0);
6224   SDValue V2 = SVOp->getOperand(1);
6225   SDLoc dl(SVOp);
6226   MVT VT = SVOp->getSimpleValueType(0);
6227   MVT EltVT = VT.getVectorElementType();
6228   unsigned NumElems = VT.getVectorNumElements();
6229
6230   // There is no blend with immediate in AVX-512.
6231   if (VT.is512BitVector())
6232     return SDValue();
6233
6234   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6235     return SDValue();
6236   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6237     return SDValue();
6238
6239   // Check the mask for BLEND and build the value.
6240   unsigned MaskValue = 0;
6241   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6242   unsigned NumLanes = (NumElems-1)/8 + 1;
6243   unsigned NumElemsInLane = NumElems / NumLanes;
6244
6245   // Blend for v16i16 should be symetric for the both lanes.
6246   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6247
6248     int SndLaneEltIdx = (NumLanes == 2) ?
6249       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6250     int EltIdx = SVOp->getMaskElt(i);
6251
6252     if ((EltIdx < 0 || EltIdx == (int)i) &&
6253         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6254       continue;
6255
6256     if (((unsigned)EltIdx == (i + NumElems)) &&
6257         (SndLaneEltIdx < 0 ||
6258          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6259       MaskValue |= (1<<i);
6260     else
6261       return SDValue();
6262   }
6263
6264   // Convert i32 vectors to floating point if it is not AVX2.
6265   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6266   MVT BlendVT = VT;
6267   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6268     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6269                                NumElems);
6270     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6271     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6272   }
6273
6274   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6275                             DAG.getConstant(MaskValue, MVT::i32));
6276   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6277 }
6278
6279 // v8i16 shuffles - Prefer shuffles in the following order:
6280 // 1. [all]   pshuflw, pshufhw, optional move
6281 // 2. [ssse3] 1 x pshufb
6282 // 3. [ssse3] 2 x pshufb + 1 x por
6283 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6284 static SDValue
6285 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6286                          SelectionDAG &DAG) {
6287   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6288   SDValue V1 = SVOp->getOperand(0);
6289   SDValue V2 = SVOp->getOperand(1);
6290   SDLoc dl(SVOp);
6291   SmallVector<int, 8> MaskVals;
6292
6293   // Determine if more than 1 of the words in each of the low and high quadwords
6294   // of the result come from the same quadword of one of the two inputs.  Undef
6295   // mask values count as coming from any quadword, for better codegen.
6296   unsigned LoQuad[] = { 0, 0, 0, 0 };
6297   unsigned HiQuad[] = { 0, 0, 0, 0 };
6298   std::bitset<4> InputQuads;
6299   for (unsigned i = 0; i < 8; ++i) {
6300     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6301     int EltIdx = SVOp->getMaskElt(i);
6302     MaskVals.push_back(EltIdx);
6303     if (EltIdx < 0) {
6304       ++Quad[0];
6305       ++Quad[1];
6306       ++Quad[2];
6307       ++Quad[3];
6308       continue;
6309     }
6310     ++Quad[EltIdx / 4];
6311     InputQuads.set(EltIdx / 4);
6312   }
6313
6314   int BestLoQuad = -1;
6315   unsigned MaxQuad = 1;
6316   for (unsigned i = 0; i < 4; ++i) {
6317     if (LoQuad[i] > MaxQuad) {
6318       BestLoQuad = i;
6319       MaxQuad = LoQuad[i];
6320     }
6321   }
6322
6323   int BestHiQuad = -1;
6324   MaxQuad = 1;
6325   for (unsigned i = 0; i < 4; ++i) {
6326     if (HiQuad[i] > MaxQuad) {
6327       BestHiQuad = i;
6328       MaxQuad = HiQuad[i];
6329     }
6330   }
6331
6332   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6333   // of the two input vectors, shuffle them into one input vector so only a
6334   // single pshufb instruction is necessary. If There are more than 2 input
6335   // quads, disable the next transformation since it does not help SSSE3.
6336   bool V1Used = InputQuads[0] || InputQuads[1];
6337   bool V2Used = InputQuads[2] || InputQuads[3];
6338   if (Subtarget->hasSSSE3()) {
6339     if (InputQuads.count() == 2 && V1Used && V2Used) {
6340       BestLoQuad = InputQuads[0] ? 0 : 1;
6341       BestHiQuad = InputQuads[2] ? 2 : 3;
6342     }
6343     if (InputQuads.count() > 2) {
6344       BestLoQuad = -1;
6345       BestHiQuad = -1;
6346     }
6347   }
6348
6349   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6350   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6351   // words from all 4 input quadwords.
6352   SDValue NewV;
6353   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6354     int MaskV[] = {
6355       BestLoQuad < 0 ? 0 : BestLoQuad,
6356       BestHiQuad < 0 ? 1 : BestHiQuad
6357     };
6358     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6359                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6360                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6361     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6362
6363     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6364     // source words for the shuffle, to aid later transformations.
6365     bool AllWordsInNewV = true;
6366     bool InOrder[2] = { true, true };
6367     for (unsigned i = 0; i != 8; ++i) {
6368       int idx = MaskVals[i];
6369       if (idx != (int)i)
6370         InOrder[i/4] = false;
6371       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6372         continue;
6373       AllWordsInNewV = false;
6374       break;
6375     }
6376
6377     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6378     if (AllWordsInNewV) {
6379       for (int i = 0; i != 8; ++i) {
6380         int idx = MaskVals[i];
6381         if (idx < 0)
6382           continue;
6383         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6384         if ((idx != i) && idx < 4)
6385           pshufhw = false;
6386         if ((idx != i) && idx > 3)
6387           pshuflw = false;
6388       }
6389       V1 = NewV;
6390       V2Used = false;
6391       BestLoQuad = 0;
6392       BestHiQuad = 1;
6393     }
6394
6395     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6396     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6397     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6398       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6399       unsigned TargetMask = 0;
6400       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6401                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6402       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6403       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6404                              getShufflePSHUFLWImmediate(SVOp);
6405       V1 = NewV.getOperand(0);
6406       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6407     }
6408   }
6409
6410   // Promote splats to a larger type which usually leads to more efficient code.
6411   // FIXME: Is this true if pshufb is available?
6412   if (SVOp->isSplat())
6413     return PromoteSplat(SVOp, DAG);
6414
6415   // If we have SSSE3, and all words of the result are from 1 input vector,
6416   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6417   // is present, fall back to case 4.
6418   if (Subtarget->hasSSSE3()) {
6419     SmallVector<SDValue,16> pshufbMask;
6420
6421     // If we have elements from both input vectors, set the high bit of the
6422     // shuffle mask element to zero out elements that come from V2 in the V1
6423     // mask, and elements that come from V1 in the V2 mask, so that the two
6424     // results can be OR'd together.
6425     bool TwoInputs = V1Used && V2Used;
6426     for (unsigned i = 0; i != 8; ++i) {
6427       int EltIdx = MaskVals[i] * 2;
6428       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6429       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6430       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6431       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6432     }
6433     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6434     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6435                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6436                                  MVT::v16i8, &pshufbMask[0], 16));
6437     if (!TwoInputs)
6438       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6439
6440     // Calculate the shuffle mask for the second input, shuffle it, and
6441     // OR it with the first shuffled input.
6442     pshufbMask.clear();
6443     for (unsigned i = 0; i != 8; ++i) {
6444       int EltIdx = MaskVals[i] * 2;
6445       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6446       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6447       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6448       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6449     }
6450     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6451     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6452                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6453                                  MVT::v16i8, &pshufbMask[0], 16));
6454     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6455     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6456   }
6457
6458   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6459   // and update MaskVals with new element order.
6460   std::bitset<8> InOrder;
6461   if (BestLoQuad >= 0) {
6462     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6463     for (int i = 0; i != 4; ++i) {
6464       int idx = MaskVals[i];
6465       if (idx < 0) {
6466         InOrder.set(i);
6467       } else if ((idx / 4) == BestLoQuad) {
6468         MaskV[i] = idx & 3;
6469         InOrder.set(i);
6470       }
6471     }
6472     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6473                                 &MaskV[0]);
6474
6475     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6476       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6477       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6478                                   NewV.getOperand(0),
6479                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6480     }
6481   }
6482
6483   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6484   // and update MaskVals with the new element order.
6485   if (BestHiQuad >= 0) {
6486     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6487     for (unsigned i = 4; i != 8; ++i) {
6488       int idx = MaskVals[i];
6489       if (idx < 0) {
6490         InOrder.set(i);
6491       } else if ((idx / 4) == BestHiQuad) {
6492         MaskV[i] = (idx & 3) + 4;
6493         InOrder.set(i);
6494       }
6495     }
6496     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6497                                 &MaskV[0]);
6498
6499     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6500       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6501       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6502                                   NewV.getOperand(0),
6503                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6504     }
6505   }
6506
6507   // In case BestHi & BestLo were both -1, which means each quadword has a word
6508   // from each of the four input quadwords, calculate the InOrder bitvector now
6509   // before falling through to the insert/extract cleanup.
6510   if (BestLoQuad == -1 && BestHiQuad == -1) {
6511     NewV = V1;
6512     for (int i = 0; i != 8; ++i)
6513       if (MaskVals[i] < 0 || MaskVals[i] == i)
6514         InOrder.set(i);
6515   }
6516
6517   // The other elements are put in the right place using pextrw and pinsrw.
6518   for (unsigned i = 0; i != 8; ++i) {
6519     if (InOrder[i])
6520       continue;
6521     int EltIdx = MaskVals[i];
6522     if (EltIdx < 0)
6523       continue;
6524     SDValue ExtOp = (EltIdx < 8) ?
6525       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6526                   DAG.getIntPtrConstant(EltIdx)) :
6527       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6528                   DAG.getIntPtrConstant(EltIdx - 8));
6529     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6530                        DAG.getIntPtrConstant(i));
6531   }
6532   return NewV;
6533 }
6534
6535 // v16i8 shuffles - Prefer shuffles in the following order:
6536 // 1. [ssse3] 1 x pshufb
6537 // 2. [ssse3] 2 x pshufb + 1 x por
6538 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6539 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6540                                         const X86Subtarget* Subtarget,
6541                                         SelectionDAG &DAG) {
6542   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6543   SDValue V1 = SVOp->getOperand(0);
6544   SDValue V2 = SVOp->getOperand(1);
6545   SDLoc dl(SVOp);
6546   ArrayRef<int> MaskVals = SVOp->getMask();
6547
6548   // Promote splats to a larger type which usually leads to more efficient code.
6549   // FIXME: Is this true if pshufb is available?
6550   if (SVOp->isSplat())
6551     return PromoteSplat(SVOp, DAG);
6552
6553   // If we have SSSE3, case 1 is generated when all result bytes come from
6554   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6555   // present, fall back to case 3.
6556
6557   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6558   if (Subtarget->hasSSSE3()) {
6559     SmallVector<SDValue,16> pshufbMask;
6560
6561     // If all result elements are from one input vector, then only translate
6562     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6563     //
6564     // Otherwise, we have elements from both input vectors, and must zero out
6565     // elements that come from V2 in the first mask, and V1 in the second mask
6566     // so that we can OR them together.
6567     for (unsigned i = 0; i != 16; ++i) {
6568       int EltIdx = MaskVals[i];
6569       if (EltIdx < 0 || EltIdx >= 16)
6570         EltIdx = 0x80;
6571       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6572     }
6573     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6574                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6575                                  MVT::v16i8, &pshufbMask[0], 16));
6576
6577     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6578     // the 2nd operand if it's undefined or zero.
6579     if (V2.getOpcode() == ISD::UNDEF ||
6580         ISD::isBuildVectorAllZeros(V2.getNode()))
6581       return V1;
6582
6583     // Calculate the shuffle mask for the second input, shuffle it, and
6584     // OR it with the first shuffled input.
6585     pshufbMask.clear();
6586     for (unsigned i = 0; i != 16; ++i) {
6587       int EltIdx = MaskVals[i];
6588       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6589       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6590     }
6591     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6592                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6593                                  MVT::v16i8, &pshufbMask[0], 16));
6594     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6595   }
6596
6597   // No SSSE3 - Calculate in place words and then fix all out of place words
6598   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6599   // the 16 different words that comprise the two doublequadword input vectors.
6600   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6601   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6602   SDValue NewV = V1;
6603   for (int i = 0; i != 8; ++i) {
6604     int Elt0 = MaskVals[i*2];
6605     int Elt1 = MaskVals[i*2+1];
6606
6607     // This word of the result is all undef, skip it.
6608     if (Elt0 < 0 && Elt1 < 0)
6609       continue;
6610
6611     // This word of the result is already in the correct place, skip it.
6612     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6613       continue;
6614
6615     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6616     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6617     SDValue InsElt;
6618
6619     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6620     // using a single extract together, load it and store it.
6621     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6622       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6623                            DAG.getIntPtrConstant(Elt1 / 2));
6624       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6625                         DAG.getIntPtrConstant(i));
6626       continue;
6627     }
6628
6629     // If Elt1 is defined, extract it from the appropriate source.  If the
6630     // source byte is not also odd, shift the extracted word left 8 bits
6631     // otherwise clear the bottom 8 bits if we need to do an or.
6632     if (Elt1 >= 0) {
6633       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6634                            DAG.getIntPtrConstant(Elt1 / 2));
6635       if ((Elt1 & 1) == 0)
6636         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6637                              DAG.getConstant(8,
6638                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6639       else if (Elt0 >= 0)
6640         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6641                              DAG.getConstant(0xFF00, MVT::i16));
6642     }
6643     // If Elt0 is defined, extract it from the appropriate source.  If the
6644     // source byte is not also even, shift the extracted word right 8 bits. If
6645     // Elt1 was also defined, OR the extracted values together before
6646     // inserting them in the result.
6647     if (Elt0 >= 0) {
6648       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6649                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6650       if ((Elt0 & 1) != 0)
6651         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6652                               DAG.getConstant(8,
6653                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6654       else if (Elt1 >= 0)
6655         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6656                              DAG.getConstant(0x00FF, MVT::i16));
6657       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6658                          : InsElt0;
6659     }
6660     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6661                        DAG.getIntPtrConstant(i));
6662   }
6663   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6664 }
6665
6666 // v32i8 shuffles - Translate to VPSHUFB if possible.
6667 static
6668 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6669                                  const X86Subtarget *Subtarget,
6670                                  SelectionDAG &DAG) {
6671   MVT VT = SVOp->getSimpleValueType(0);
6672   SDValue V1 = SVOp->getOperand(0);
6673   SDValue V2 = SVOp->getOperand(1);
6674   SDLoc dl(SVOp);
6675   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6676
6677   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6678   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6679   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6680
6681   // VPSHUFB may be generated if
6682   // (1) one of input vector is undefined or zeroinitializer.
6683   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6684   // And (2) the mask indexes don't cross the 128-bit lane.
6685   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6686       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6687     return SDValue();
6688
6689   if (V1IsAllZero && !V2IsAllZero) {
6690     CommuteVectorShuffleMask(MaskVals, 32);
6691     V1 = V2;
6692   }
6693   SmallVector<SDValue, 32> pshufbMask;
6694   for (unsigned i = 0; i != 32; i++) {
6695     int EltIdx = MaskVals[i];
6696     if (EltIdx < 0 || EltIdx >= 32)
6697       EltIdx = 0x80;
6698     else {
6699       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6700         // Cross lane is not allowed.
6701         return SDValue();
6702       EltIdx &= 0xf;
6703     }
6704     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6705   }
6706   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6707                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6708                                   MVT::v32i8, &pshufbMask[0], 32));
6709 }
6710
6711 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6712 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6713 /// done when every pair / quad of shuffle mask elements point to elements in
6714 /// the right sequence. e.g.
6715 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6716 static
6717 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6718                                  SelectionDAG &DAG) {
6719   MVT VT = SVOp->getSimpleValueType(0);
6720   SDLoc dl(SVOp);
6721   unsigned NumElems = VT.getVectorNumElements();
6722   MVT NewVT;
6723   unsigned Scale;
6724   switch (VT.SimpleTy) {
6725   default: llvm_unreachable("Unexpected!");
6726   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6727   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6728   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6729   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6730   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6731   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6732   }
6733
6734   SmallVector<int, 8> MaskVec;
6735   for (unsigned i = 0; i != NumElems; i += Scale) {
6736     int StartIdx = -1;
6737     for (unsigned j = 0; j != Scale; ++j) {
6738       int EltIdx = SVOp->getMaskElt(i+j);
6739       if (EltIdx < 0)
6740         continue;
6741       if (StartIdx < 0)
6742         StartIdx = (EltIdx / Scale);
6743       if (EltIdx != (int)(StartIdx*Scale + j))
6744         return SDValue();
6745     }
6746     MaskVec.push_back(StartIdx);
6747   }
6748
6749   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6750   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6751   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6752 }
6753
6754 /// getVZextMovL - Return a zero-extending vector move low node.
6755 ///
6756 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6757                             SDValue SrcOp, SelectionDAG &DAG,
6758                             const X86Subtarget *Subtarget, SDLoc dl) {
6759   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6760     LoadSDNode *LD = NULL;
6761     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6762       LD = dyn_cast<LoadSDNode>(SrcOp);
6763     if (!LD) {
6764       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6765       // instead.
6766       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6767       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6768           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6769           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6770           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6771         // PR2108
6772         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6773         return DAG.getNode(ISD::BITCAST, dl, VT,
6774                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6775                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6776                                                    OpVT,
6777                                                    SrcOp.getOperand(0)
6778                                                           .getOperand(0))));
6779       }
6780     }
6781   }
6782
6783   return DAG.getNode(ISD::BITCAST, dl, VT,
6784                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6785                                  DAG.getNode(ISD::BITCAST, dl,
6786                                              OpVT, SrcOp)));
6787 }
6788
6789 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6790 /// which could not be matched by any known target speficic shuffle
6791 static SDValue
6792 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6793
6794   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6795   if (NewOp.getNode())
6796     return NewOp;
6797
6798   MVT VT = SVOp->getSimpleValueType(0);
6799
6800   unsigned NumElems = VT.getVectorNumElements();
6801   unsigned NumLaneElems = NumElems / 2;
6802
6803   SDLoc dl(SVOp);
6804   MVT EltVT = VT.getVectorElementType();
6805   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6806   SDValue Output[2];
6807
6808   SmallVector<int, 16> Mask;
6809   for (unsigned l = 0; l < 2; ++l) {
6810     // Build a shuffle mask for the output, discovering on the fly which
6811     // input vectors to use as shuffle operands (recorded in InputUsed).
6812     // If building a suitable shuffle vector proves too hard, then bail
6813     // out with UseBuildVector set.
6814     bool UseBuildVector = false;
6815     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6816     unsigned LaneStart = l * NumLaneElems;
6817     for (unsigned i = 0; i != NumLaneElems; ++i) {
6818       // The mask element.  This indexes into the input.
6819       int Idx = SVOp->getMaskElt(i+LaneStart);
6820       if (Idx < 0) {
6821         // the mask element does not index into any input vector.
6822         Mask.push_back(-1);
6823         continue;
6824       }
6825
6826       // The input vector this mask element indexes into.
6827       int Input = Idx / NumLaneElems;
6828
6829       // Turn the index into an offset from the start of the input vector.
6830       Idx -= Input * NumLaneElems;
6831
6832       // Find or create a shuffle vector operand to hold this input.
6833       unsigned OpNo;
6834       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6835         if (InputUsed[OpNo] == Input)
6836           // This input vector is already an operand.
6837           break;
6838         if (InputUsed[OpNo] < 0) {
6839           // Create a new operand for this input vector.
6840           InputUsed[OpNo] = Input;
6841           break;
6842         }
6843       }
6844
6845       if (OpNo >= array_lengthof(InputUsed)) {
6846         // More than two input vectors used!  Give up on trying to create a
6847         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6848         UseBuildVector = true;
6849         break;
6850       }
6851
6852       // Add the mask index for the new shuffle vector.
6853       Mask.push_back(Idx + OpNo * NumLaneElems);
6854     }
6855
6856     if (UseBuildVector) {
6857       SmallVector<SDValue, 16> SVOps;
6858       for (unsigned i = 0; i != NumLaneElems; ++i) {
6859         // The mask element.  This indexes into the input.
6860         int Idx = SVOp->getMaskElt(i+LaneStart);
6861         if (Idx < 0) {
6862           SVOps.push_back(DAG.getUNDEF(EltVT));
6863           continue;
6864         }
6865
6866         // The input vector this mask element indexes into.
6867         int Input = Idx / NumElems;
6868
6869         // Turn the index into an offset from the start of the input vector.
6870         Idx -= Input * NumElems;
6871
6872         // Extract the vector element by hand.
6873         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6874                                     SVOp->getOperand(Input),
6875                                     DAG.getIntPtrConstant(Idx)));
6876       }
6877
6878       // Construct the output using a BUILD_VECTOR.
6879       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6880                               SVOps.size());
6881     } else if (InputUsed[0] < 0) {
6882       // No input vectors were used! The result is undefined.
6883       Output[l] = DAG.getUNDEF(NVT);
6884     } else {
6885       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6886                                         (InputUsed[0] % 2) * NumLaneElems,
6887                                         DAG, dl);
6888       // If only one input was used, use an undefined vector for the other.
6889       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6890         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6891                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6892       // At least one input vector was used. Create a new shuffle vector.
6893       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6894     }
6895
6896     Mask.clear();
6897   }
6898
6899   // Concatenate the result back
6900   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6901 }
6902
6903 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6904 /// 4 elements, and match them with several different shuffle types.
6905 static SDValue
6906 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6907   SDValue V1 = SVOp->getOperand(0);
6908   SDValue V2 = SVOp->getOperand(1);
6909   SDLoc dl(SVOp);
6910   MVT VT = SVOp->getSimpleValueType(0);
6911
6912   assert(VT.is128BitVector() && "Unsupported vector size");
6913
6914   std::pair<int, int> Locs[4];
6915   int Mask1[] = { -1, -1, -1, -1 };
6916   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6917
6918   unsigned NumHi = 0;
6919   unsigned NumLo = 0;
6920   for (unsigned i = 0; i != 4; ++i) {
6921     int Idx = PermMask[i];
6922     if (Idx < 0) {
6923       Locs[i] = std::make_pair(-1, -1);
6924     } else {
6925       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6926       if (Idx < 4) {
6927         Locs[i] = std::make_pair(0, NumLo);
6928         Mask1[NumLo] = Idx;
6929         NumLo++;
6930       } else {
6931         Locs[i] = std::make_pair(1, NumHi);
6932         if (2+NumHi < 4)
6933           Mask1[2+NumHi] = Idx;
6934         NumHi++;
6935       }
6936     }
6937   }
6938
6939   if (NumLo <= 2 && NumHi <= 2) {
6940     // If no more than two elements come from either vector. This can be
6941     // implemented with two shuffles. First shuffle gather the elements.
6942     // The second shuffle, which takes the first shuffle as both of its
6943     // vector operands, put the elements into the right order.
6944     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6945
6946     int Mask2[] = { -1, -1, -1, -1 };
6947
6948     for (unsigned i = 0; i != 4; ++i)
6949       if (Locs[i].first != -1) {
6950         unsigned Idx = (i < 2) ? 0 : 4;
6951         Idx += Locs[i].first * 2 + Locs[i].second;
6952         Mask2[i] = Idx;
6953       }
6954
6955     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6956   }
6957
6958   if (NumLo == 3 || NumHi == 3) {
6959     // Otherwise, we must have three elements from one vector, call it X, and
6960     // one element from the other, call it Y.  First, use a shufps to build an
6961     // intermediate vector with the one element from Y and the element from X
6962     // that will be in the same half in the final destination (the indexes don't
6963     // matter). Then, use a shufps to build the final vector, taking the half
6964     // containing the element from Y from the intermediate, and the other half
6965     // from X.
6966     if (NumHi == 3) {
6967       // Normalize it so the 3 elements come from V1.
6968       CommuteVectorShuffleMask(PermMask, 4);
6969       std::swap(V1, V2);
6970     }
6971
6972     // Find the element from V2.
6973     unsigned HiIndex;
6974     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6975       int Val = PermMask[HiIndex];
6976       if (Val < 0)
6977         continue;
6978       if (Val >= 4)
6979         break;
6980     }
6981
6982     Mask1[0] = PermMask[HiIndex];
6983     Mask1[1] = -1;
6984     Mask1[2] = PermMask[HiIndex^1];
6985     Mask1[3] = -1;
6986     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6987
6988     if (HiIndex >= 2) {
6989       Mask1[0] = PermMask[0];
6990       Mask1[1] = PermMask[1];
6991       Mask1[2] = HiIndex & 1 ? 6 : 4;
6992       Mask1[3] = HiIndex & 1 ? 4 : 6;
6993       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6994     }
6995
6996     Mask1[0] = HiIndex & 1 ? 2 : 0;
6997     Mask1[1] = HiIndex & 1 ? 0 : 2;
6998     Mask1[2] = PermMask[2];
6999     Mask1[3] = PermMask[3];
7000     if (Mask1[2] >= 0)
7001       Mask1[2] += 4;
7002     if (Mask1[3] >= 0)
7003       Mask1[3] += 4;
7004     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7005   }
7006
7007   // Break it into (shuffle shuffle_hi, shuffle_lo).
7008   int LoMask[] = { -1, -1, -1, -1 };
7009   int HiMask[] = { -1, -1, -1, -1 };
7010
7011   int *MaskPtr = LoMask;
7012   unsigned MaskIdx = 0;
7013   unsigned LoIdx = 0;
7014   unsigned HiIdx = 2;
7015   for (unsigned i = 0; i != 4; ++i) {
7016     if (i == 2) {
7017       MaskPtr = HiMask;
7018       MaskIdx = 1;
7019       LoIdx = 0;
7020       HiIdx = 2;
7021     }
7022     int Idx = PermMask[i];
7023     if (Idx < 0) {
7024       Locs[i] = std::make_pair(-1, -1);
7025     } else if (Idx < 4) {
7026       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7027       MaskPtr[LoIdx] = Idx;
7028       LoIdx++;
7029     } else {
7030       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7031       MaskPtr[HiIdx] = Idx;
7032       HiIdx++;
7033     }
7034   }
7035
7036   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7037   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7038   int MaskOps[] = { -1, -1, -1, -1 };
7039   for (unsigned i = 0; i != 4; ++i)
7040     if (Locs[i].first != -1)
7041       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7042   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7043 }
7044
7045 static bool MayFoldVectorLoad(SDValue V) {
7046   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7047     V = V.getOperand(0);
7048
7049   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7050     V = V.getOperand(0);
7051   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7052       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7053     // BUILD_VECTOR (load), undef
7054     V = V.getOperand(0);
7055
7056   return MayFoldLoad(V);
7057 }
7058
7059 static
7060 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7061   MVT VT = Op.getSimpleValueType();
7062
7063   // Canonizalize to v2f64.
7064   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7065   return DAG.getNode(ISD::BITCAST, dl, VT,
7066                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7067                                           V1, DAG));
7068 }
7069
7070 static
7071 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7072                         bool HasSSE2) {
7073   SDValue V1 = Op.getOperand(0);
7074   SDValue V2 = Op.getOperand(1);
7075   MVT VT = Op.getSimpleValueType();
7076
7077   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7078
7079   if (HasSSE2 && VT == MVT::v2f64)
7080     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7081
7082   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7083   return DAG.getNode(ISD::BITCAST, dl, VT,
7084                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7085                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7086                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7087 }
7088
7089 static
7090 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7091   SDValue V1 = Op.getOperand(0);
7092   SDValue V2 = Op.getOperand(1);
7093   MVT VT = Op.getSimpleValueType();
7094
7095   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7096          "unsupported shuffle type");
7097
7098   if (V2.getOpcode() == ISD::UNDEF)
7099     V2 = V1;
7100
7101   // v4i32 or v4f32
7102   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7103 }
7104
7105 static
7106 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7107   SDValue V1 = Op.getOperand(0);
7108   SDValue V2 = Op.getOperand(1);
7109   MVT VT = Op.getSimpleValueType();
7110   unsigned NumElems = VT.getVectorNumElements();
7111
7112   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7113   // operand of these instructions is only memory, so check if there's a
7114   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7115   // same masks.
7116   bool CanFoldLoad = false;
7117
7118   // Trivial case, when V2 comes from a load.
7119   if (MayFoldVectorLoad(V2))
7120     CanFoldLoad = true;
7121
7122   // When V1 is a load, it can be folded later into a store in isel, example:
7123   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7124   //    turns into:
7125   //  (MOVLPSmr addr:$src1, VR128:$src2)
7126   // So, recognize this potential and also use MOVLPS or MOVLPD
7127   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7128     CanFoldLoad = true;
7129
7130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7131   if (CanFoldLoad) {
7132     if (HasSSE2 && NumElems == 2)
7133       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7134
7135     if (NumElems == 4)
7136       // If we don't care about the second element, proceed to use movss.
7137       if (SVOp->getMaskElt(1) != -1)
7138         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7139   }
7140
7141   // movl and movlp will both match v2i64, but v2i64 is never matched by
7142   // movl earlier because we make it strict to avoid messing with the movlp load
7143   // folding logic (see the code above getMOVLP call). Match it here then,
7144   // this is horrible, but will stay like this until we move all shuffle
7145   // matching to x86 specific nodes. Note that for the 1st condition all
7146   // types are matched with movsd.
7147   if (HasSSE2) {
7148     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7149     // as to remove this logic from here, as much as possible
7150     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7151       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7152     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7153   }
7154
7155   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7156
7157   // Invert the operand order and use SHUFPS to match it.
7158   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7159                               getShuffleSHUFImmediate(SVOp), DAG);
7160 }
7161
7162 // Reduce a vector shuffle to zext.
7163 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7164                                     SelectionDAG &DAG) {
7165   // PMOVZX is only available from SSE41.
7166   if (!Subtarget->hasSSE41())
7167     return SDValue();
7168
7169   MVT VT = Op.getSimpleValueType();
7170
7171   // Only AVX2 support 256-bit vector integer extending.
7172   if (!Subtarget->hasInt256() && VT.is256BitVector())
7173     return SDValue();
7174
7175   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7176   SDLoc DL(Op);
7177   SDValue V1 = Op.getOperand(0);
7178   SDValue V2 = Op.getOperand(1);
7179   unsigned NumElems = VT.getVectorNumElements();
7180
7181   // Extending is an unary operation and the element type of the source vector
7182   // won't be equal to or larger than i64.
7183   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7184       VT.getVectorElementType() == MVT::i64)
7185     return SDValue();
7186
7187   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7188   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7189   while ((1U << Shift) < NumElems) {
7190     if (SVOp->getMaskElt(1U << Shift) == 1)
7191       break;
7192     Shift += 1;
7193     // The maximal ratio is 8, i.e. from i8 to i64.
7194     if (Shift > 3)
7195       return SDValue();
7196   }
7197
7198   // Check the shuffle mask.
7199   unsigned Mask = (1U << Shift) - 1;
7200   for (unsigned i = 0; i != NumElems; ++i) {
7201     int EltIdx = SVOp->getMaskElt(i);
7202     if ((i & Mask) != 0 && EltIdx != -1)
7203       return SDValue();
7204     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7205       return SDValue();
7206   }
7207
7208   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7209   MVT NeVT = MVT::getIntegerVT(NBits);
7210   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7211
7212   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7213     return SDValue();
7214
7215   // Simplify the operand as it's prepared to be fed into shuffle.
7216   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7217   if (V1.getOpcode() == ISD::BITCAST &&
7218       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7219       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7220       V1.getOperand(0).getOperand(0)
7221         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7222     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7223     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7224     ConstantSDNode *CIdx =
7225       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7226     // If it's foldable, i.e. normal load with single use, we will let code
7227     // selection to fold it. Otherwise, we will short the conversion sequence.
7228     if (CIdx && CIdx->getZExtValue() == 0 &&
7229         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7230       MVT FullVT = V.getSimpleValueType();
7231       MVT V1VT = V1.getSimpleValueType();
7232       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7233         // The "ext_vec_elt" node is wider than the result node.
7234         // In this case we should extract subvector from V.
7235         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7236         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7237         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7238                                         FullVT.getVectorNumElements()/Ratio);
7239         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7240                         DAG.getIntPtrConstant(0));
7241       }
7242       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7243     }
7244   }
7245
7246   return DAG.getNode(ISD::BITCAST, DL, VT,
7247                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7248 }
7249
7250 static SDValue
7251 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7252                        SelectionDAG &DAG) {
7253   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7254   MVT VT = Op.getSimpleValueType();
7255   SDLoc dl(Op);
7256   SDValue V1 = Op.getOperand(0);
7257   SDValue V2 = Op.getOperand(1);
7258
7259   if (isZeroShuffle(SVOp))
7260     return getZeroVector(VT, Subtarget, DAG, dl);
7261
7262   // Handle splat operations
7263   if (SVOp->isSplat()) {
7264     // Use vbroadcast whenever the splat comes from a foldable load
7265     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7266     if (Broadcast.getNode())
7267       return Broadcast;
7268   }
7269
7270   // Check integer expanding shuffles.
7271   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7272   if (NewOp.getNode())
7273     return NewOp;
7274
7275   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7276   // do it!
7277   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7278       VT == MVT::v16i16 || VT == MVT::v32i8) {
7279     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7280     if (NewOp.getNode())
7281       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7282   } else if ((VT == MVT::v4i32 ||
7283              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7284     // FIXME: Figure out a cleaner way to do this.
7285     // Try to make use of movq to zero out the top part.
7286     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7287       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7288       if (NewOp.getNode()) {
7289         MVT NewVT = NewOp.getSimpleValueType();
7290         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7291                                NewVT, true, false))
7292           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7293                               DAG, Subtarget, dl);
7294       }
7295     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7296       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7297       if (NewOp.getNode()) {
7298         MVT NewVT = NewOp.getSimpleValueType();
7299         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7300           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7301                               DAG, Subtarget, dl);
7302       }
7303     }
7304   }
7305   return SDValue();
7306 }
7307
7308 SDValue
7309 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7310   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7311   SDValue V1 = Op.getOperand(0);
7312   SDValue V2 = Op.getOperand(1);
7313   MVT VT = Op.getSimpleValueType();
7314   SDLoc dl(Op);
7315   unsigned NumElems = VT.getVectorNumElements();
7316   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7317   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7318   bool V1IsSplat = false;
7319   bool V2IsSplat = false;
7320   bool HasSSE2 = Subtarget->hasSSE2();
7321   bool HasFp256    = Subtarget->hasFp256();
7322   bool HasInt256   = Subtarget->hasInt256();
7323   MachineFunction &MF = DAG.getMachineFunction();
7324   bool OptForSize = MF.getFunction()->getAttributes().
7325     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7326
7327   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7328
7329   if (V1IsUndef && V2IsUndef)
7330     return DAG.getUNDEF(VT);
7331
7332   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7333
7334   // Vector shuffle lowering takes 3 steps:
7335   //
7336   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7337   //    narrowing and commutation of operands should be handled.
7338   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7339   //    shuffle nodes.
7340   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7341   //    so the shuffle can be broken into other shuffles and the legalizer can
7342   //    try the lowering again.
7343   //
7344   // The general idea is that no vector_shuffle operation should be left to
7345   // be matched during isel, all of them must be converted to a target specific
7346   // node here.
7347
7348   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7349   // narrowing and commutation of operands should be handled. The actual code
7350   // doesn't include all of those, work in progress...
7351   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7352   if (NewOp.getNode())
7353     return NewOp;
7354
7355   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7356
7357   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7358   // unpckh_undef). Only use pshufd if speed is more important than size.
7359   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7360     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7361   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7362     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7363
7364   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7365       V2IsUndef && MayFoldVectorLoad(V1))
7366     return getMOVDDup(Op, dl, V1, DAG);
7367
7368   if (isMOVHLPS_v_undef_Mask(M, VT))
7369     return getMOVHighToLow(Op, dl, DAG);
7370
7371   // Use to match splats
7372   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7373       (VT == MVT::v2f64 || VT == MVT::v2i64))
7374     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7375
7376   if (isPSHUFDMask(M, VT)) {
7377     // The actual implementation will match the mask in the if above and then
7378     // during isel it can match several different instructions, not only pshufd
7379     // as its name says, sad but true, emulate the behavior for now...
7380     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7381       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7382
7383     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7384
7385     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7386       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7387
7388     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7389       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7390                                   DAG);
7391
7392     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7393                                 TargetMask, DAG);
7394   }
7395
7396   if (isPALIGNRMask(M, VT, Subtarget))
7397     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7398                                 getShufflePALIGNRImmediate(SVOp),
7399                                 DAG);
7400
7401   // Check if this can be converted into a logical shift.
7402   bool isLeft = false;
7403   unsigned ShAmt = 0;
7404   SDValue ShVal;
7405   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7406   if (isShift && ShVal.hasOneUse()) {
7407     // If the shifted value has multiple uses, it may be cheaper to use
7408     // v_set0 + movlhps or movhlps, etc.
7409     MVT EltVT = VT.getVectorElementType();
7410     ShAmt *= EltVT.getSizeInBits();
7411     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7412   }
7413
7414   if (isMOVLMask(M, VT)) {
7415     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7416       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7417     if (!isMOVLPMask(M, VT)) {
7418       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7419         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7420
7421       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7422         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7423     }
7424   }
7425
7426   // FIXME: fold these into legal mask.
7427   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7428     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7429
7430   if (isMOVHLPSMask(M, VT))
7431     return getMOVHighToLow(Op, dl, DAG);
7432
7433   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7434     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7435
7436   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7437     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7438
7439   if (isMOVLPMask(M, VT))
7440     return getMOVLP(Op, dl, DAG, HasSSE2);
7441
7442   if (ShouldXformToMOVHLPS(M, VT) ||
7443       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7444     return CommuteVectorShuffle(SVOp, DAG);
7445
7446   if (isShift) {
7447     // No better options. Use a vshldq / vsrldq.
7448     MVT EltVT = VT.getVectorElementType();
7449     ShAmt *= EltVT.getSizeInBits();
7450     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7451   }
7452
7453   bool Commuted = false;
7454   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7455   // 1,1,1,1 -> v8i16 though.
7456   V1IsSplat = isSplatVector(V1.getNode());
7457   V2IsSplat = isSplatVector(V2.getNode());
7458
7459   // Canonicalize the splat or undef, if present, to be on the RHS.
7460   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7461     CommuteVectorShuffleMask(M, NumElems);
7462     std::swap(V1, V2);
7463     std::swap(V1IsSplat, V2IsSplat);
7464     Commuted = true;
7465   }
7466
7467   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7468     // Shuffling low element of v1 into undef, just return v1.
7469     if (V2IsUndef)
7470       return V1;
7471     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7472     // the instruction selector will not match, so get a canonical MOVL with
7473     // swapped operands to undo the commute.
7474     return getMOVL(DAG, dl, VT, V2, V1);
7475   }
7476
7477   if (isUNPCKLMask(M, VT, HasInt256))
7478     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7479
7480   if (isUNPCKHMask(M, VT, HasInt256))
7481     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7482
7483   if (V2IsSplat) {
7484     // Normalize mask so all entries that point to V2 points to its first
7485     // element then try to match unpck{h|l} again. If match, return a
7486     // new vector_shuffle with the corrected mask.p
7487     SmallVector<int, 8> NewMask(M.begin(), M.end());
7488     NormalizeMask(NewMask, NumElems);
7489     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7490       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7491     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7492       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7493   }
7494
7495   if (Commuted) {
7496     // Commute is back and try unpck* again.
7497     // FIXME: this seems wrong.
7498     CommuteVectorShuffleMask(M, NumElems);
7499     std::swap(V1, V2);
7500     std::swap(V1IsSplat, V2IsSplat);
7501     Commuted = false;
7502
7503     if (isUNPCKLMask(M, VT, HasInt256))
7504       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7505
7506     if (isUNPCKHMask(M, VT, HasInt256))
7507       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7508   }
7509
7510   // Normalize the node to match x86 shuffle ops if needed
7511   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7512     return CommuteVectorShuffle(SVOp, DAG);
7513
7514   // The checks below are all present in isShuffleMaskLegal, but they are
7515   // inlined here right now to enable us to directly emit target specific
7516   // nodes, and remove one by one until they don't return Op anymore.
7517
7518   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7519       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7520     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7521       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7522   }
7523
7524   if (isPSHUFHWMask(M, VT, HasInt256))
7525     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7526                                 getShufflePSHUFHWImmediate(SVOp),
7527                                 DAG);
7528
7529   if (isPSHUFLWMask(M, VT, HasInt256))
7530     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7531                                 getShufflePSHUFLWImmediate(SVOp),
7532                                 DAG);
7533
7534   if (isSHUFPMask(M, VT))
7535     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7536                                 getShuffleSHUFImmediate(SVOp), DAG);
7537
7538   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7539     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7540   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7541     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7542
7543   //===--------------------------------------------------------------------===//
7544   // Generate target specific nodes for 128 or 256-bit shuffles only
7545   // supported in the AVX instruction set.
7546   //
7547
7548   // Handle VMOVDDUPY permutations
7549   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7550     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7551
7552   // Handle VPERMILPS/D* permutations
7553   if (isVPERMILPMask(M, VT)) {
7554     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7555       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7556                                   getShuffleSHUFImmediate(SVOp), DAG);
7557     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7558                                 getShuffleSHUFImmediate(SVOp), DAG);
7559   }
7560
7561   // Handle VPERM2F128/VPERM2I128 permutations
7562   if (isVPERM2X128Mask(M, VT, HasFp256))
7563     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7564                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7565
7566   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7567   if (BlendOp.getNode())
7568     return BlendOp;
7569
7570   unsigned Imm8;
7571   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7572     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7573
7574   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7575       VT.is512BitVector()) {
7576     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7577     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7578     SmallVector<SDValue, 16> permclMask;
7579     for (unsigned i = 0; i != NumElems; ++i) {
7580       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7581     }
7582
7583     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7584                                 &permclMask[0], NumElems);
7585     if (V2IsUndef)
7586       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7587       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7588                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7589     return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7590                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7591   }
7592
7593   //===--------------------------------------------------------------------===//
7594   // Since no target specific shuffle was selected for this generic one,
7595   // lower it into other known shuffles. FIXME: this isn't true yet, but
7596   // this is the plan.
7597   //
7598
7599   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7600   if (VT == MVT::v8i16) {
7601     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7602     if (NewOp.getNode())
7603       return NewOp;
7604   }
7605
7606   if (VT == MVT::v16i8) {
7607     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7608     if (NewOp.getNode())
7609       return NewOp;
7610   }
7611
7612   if (VT == MVT::v32i8) {
7613     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7614     if (NewOp.getNode())
7615       return NewOp;
7616   }
7617
7618   // Handle all 128-bit wide vectors with 4 elements, and match them with
7619   // several different shuffle types.
7620   if (NumElems == 4 && VT.is128BitVector())
7621     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7622
7623   // Handle general 256-bit shuffles
7624   if (VT.is256BitVector())
7625     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7626
7627   return SDValue();
7628 }
7629
7630 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7631   MVT VT = Op.getSimpleValueType();
7632   SDLoc dl(Op);
7633
7634   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7635     return SDValue();
7636
7637   if (VT.getSizeInBits() == 8) {
7638     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7639                                   Op.getOperand(0), Op.getOperand(1));
7640     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7641                                   DAG.getValueType(VT));
7642     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7643   }
7644
7645   if (VT.getSizeInBits() == 16) {
7646     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7647     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7648     if (Idx == 0)
7649       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7650                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7651                                      DAG.getNode(ISD::BITCAST, dl,
7652                                                  MVT::v4i32,
7653                                                  Op.getOperand(0)),
7654                                      Op.getOperand(1)));
7655     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7656                                   Op.getOperand(0), Op.getOperand(1));
7657     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7658                                   DAG.getValueType(VT));
7659     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7660   }
7661
7662   if (VT == MVT::f32) {
7663     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7664     // the result back to FR32 register. It's only worth matching if the
7665     // result has a single use which is a store or a bitcast to i32.  And in
7666     // the case of a store, it's not worth it if the index is a constant 0,
7667     // because a MOVSSmr can be used instead, which is smaller and faster.
7668     if (!Op.hasOneUse())
7669       return SDValue();
7670     SDNode *User = *Op.getNode()->use_begin();
7671     if ((User->getOpcode() != ISD::STORE ||
7672          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7673           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7674         (User->getOpcode() != ISD::BITCAST ||
7675          User->getValueType(0) != MVT::i32))
7676       return SDValue();
7677     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7678                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7679                                               Op.getOperand(0)),
7680                                               Op.getOperand(1));
7681     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7682   }
7683
7684   if (VT == MVT::i32 || VT == MVT::i64) {
7685     // ExtractPS/pextrq works with constant index.
7686     if (isa<ConstantSDNode>(Op.getOperand(1)))
7687       return Op;
7688   }
7689   return SDValue();
7690 }
7691
7692 /// Extract one bit from mask vector, like v16i1 or v8i1.
7693 /// AVX-512 feature.
7694 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) {
7695   SDValue Vec = Op.getOperand(0);
7696   SDLoc dl(Vec);
7697   MVT VecVT = Vec.getSimpleValueType();
7698   SDValue Idx = Op.getOperand(1);
7699   MVT EltVT = Op.getSimpleValueType();
7700
7701   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7702
7703   // variable index can't be handled in mask registers,
7704   // extend vector to VR512
7705   if (!isa<ConstantSDNode>(Idx)) {
7706     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7707     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7708     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7709                               ExtVT.getVectorElementType(), Ext, Idx);
7710     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7711   }
7712
7713   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7714   if (IdxVal) {
7715     unsigned MaxSift = VecVT.getSizeInBits() - 1;
7716     Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7717                       DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7718     Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7719                       DAG.getConstant(MaxSift, MVT::i8));
7720   }
7721   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i1, Vec,
7722                        DAG.getIntPtrConstant(0));
7723 }
7724
7725 SDValue
7726 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7727                                            SelectionDAG &DAG) const {
7728   SDLoc dl(Op);
7729   SDValue Vec = Op.getOperand(0);
7730   MVT VecVT = Vec.getSimpleValueType();
7731   SDValue Idx = Op.getOperand(1);
7732
7733   if (Op.getSimpleValueType() == MVT::i1)
7734     return ExtractBitFromMaskVector(Op, DAG);
7735
7736   if (!isa<ConstantSDNode>(Idx)) {
7737     if (VecVT.is512BitVector() ||
7738         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7739          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7740
7741       MVT MaskEltVT =
7742         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7743       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7744                                     MaskEltVT.getSizeInBits());
7745
7746       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7747       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7748                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7749                                 Idx, DAG.getConstant(0, getPointerTy()));
7750       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7751       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7752                         Perm, DAG.getConstant(0, getPointerTy()));
7753     }
7754     return SDValue();
7755   }
7756
7757   // If this is a 256-bit vector result, first extract the 128-bit vector and
7758   // then extract the element from the 128-bit vector.
7759   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7760
7761     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7762     // Get the 128-bit vector.
7763     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7764     MVT EltVT = VecVT.getVectorElementType();
7765
7766     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7767
7768     //if (IdxVal >= NumElems/2)
7769     //  IdxVal -= NumElems/2;
7770     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7771     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7772                        DAG.getConstant(IdxVal, MVT::i32));
7773   }
7774
7775   assert(VecVT.is128BitVector() && "Unexpected vector length");
7776
7777   if (Subtarget->hasSSE41()) {
7778     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7779     if (Res.getNode())
7780       return Res;
7781   }
7782
7783   MVT VT = Op.getSimpleValueType();
7784   // TODO: handle v16i8.
7785   if (VT.getSizeInBits() == 16) {
7786     SDValue Vec = Op.getOperand(0);
7787     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7788     if (Idx == 0)
7789       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7790                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7791                                      DAG.getNode(ISD::BITCAST, dl,
7792                                                  MVT::v4i32, Vec),
7793                                      Op.getOperand(1)));
7794     // Transform it so it match pextrw which produces a 32-bit result.
7795     MVT EltVT = MVT::i32;
7796     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7797                                   Op.getOperand(0), Op.getOperand(1));
7798     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7799                                   DAG.getValueType(VT));
7800     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7801   }
7802
7803   if (VT.getSizeInBits() == 32) {
7804     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7805     if (Idx == 0)
7806       return Op;
7807
7808     // SHUFPS the element to the lowest double word, then movss.
7809     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7810     MVT VVT = Op.getOperand(0).getSimpleValueType();
7811     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7812                                        DAG.getUNDEF(VVT), Mask);
7813     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7814                        DAG.getIntPtrConstant(0));
7815   }
7816
7817   if (VT.getSizeInBits() == 64) {
7818     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7819     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7820     //        to match extract_elt for f64.
7821     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7822     if (Idx == 0)
7823       return Op;
7824
7825     // UNPCKHPD the element to the lowest double word, then movsd.
7826     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7827     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7828     int Mask[2] = { 1, -1 };
7829     MVT VVT = Op.getOperand(0).getSimpleValueType();
7830     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7831                                        DAG.getUNDEF(VVT), Mask);
7832     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7833                        DAG.getIntPtrConstant(0));
7834   }
7835
7836   return SDValue();
7837 }
7838
7839 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7840   MVT VT = Op.getSimpleValueType();
7841   MVT EltVT = VT.getVectorElementType();
7842   SDLoc dl(Op);
7843
7844   SDValue N0 = Op.getOperand(0);
7845   SDValue N1 = Op.getOperand(1);
7846   SDValue N2 = Op.getOperand(2);
7847
7848   if (!VT.is128BitVector())
7849     return SDValue();
7850
7851   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7852       isa<ConstantSDNode>(N2)) {
7853     unsigned Opc;
7854     if (VT == MVT::v8i16)
7855       Opc = X86ISD::PINSRW;
7856     else if (VT == MVT::v16i8)
7857       Opc = X86ISD::PINSRB;
7858     else
7859       Opc = X86ISD::PINSRB;
7860
7861     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7862     // argument.
7863     if (N1.getValueType() != MVT::i32)
7864       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7865     if (N2.getValueType() != MVT::i32)
7866       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7867     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7868   }
7869
7870   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7871     // Bits [7:6] of the constant are the source select.  This will always be
7872     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7873     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7874     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7875     // Bits [5:4] of the constant are the destination select.  This is the
7876     //  value of the incoming immediate.
7877     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7878     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7879     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7880     // Create this as a scalar to vector..
7881     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7882     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7883   }
7884
7885   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7886     // PINSR* works with constant index.
7887     return Op;
7888   }
7889   return SDValue();
7890 }
7891
7892 SDValue
7893 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7894   MVT VT = Op.getSimpleValueType();
7895   MVT EltVT = VT.getVectorElementType();
7896
7897   SDLoc dl(Op);
7898   SDValue N0 = Op.getOperand(0);
7899   SDValue N1 = Op.getOperand(1);
7900   SDValue N2 = Op.getOperand(2);
7901
7902   // If this is a 256-bit vector result, first extract the 128-bit vector,
7903   // insert the element into the extracted half and then place it back.
7904   if (VT.is256BitVector() || VT.is512BitVector()) {
7905     if (!isa<ConstantSDNode>(N2))
7906       return SDValue();
7907
7908     // Get the desired 128-bit vector half.
7909     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7910     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7911
7912     // Insert the element into the desired half.
7913     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7914     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7915
7916     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7917                     DAG.getConstant(IdxIn128, MVT::i32));
7918
7919     // Insert the changed part back to the 256-bit vector
7920     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7921   }
7922
7923   if (Subtarget->hasSSE41())
7924     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7925
7926   if (EltVT == MVT::i8)
7927     return SDValue();
7928
7929   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7930     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7931     // as its second argument.
7932     if (N1.getValueType() != MVT::i32)
7933       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7934     if (N2.getValueType() != MVT::i32)
7935       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7936     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7937   }
7938   return SDValue();
7939 }
7940
7941 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7942   SDLoc dl(Op);
7943   MVT OpVT = Op.getSimpleValueType();
7944
7945   // If this is a 256-bit vector result, first insert into a 128-bit
7946   // vector and then insert into the 256-bit vector.
7947   if (!OpVT.is128BitVector()) {
7948     // Insert into a 128-bit vector.
7949     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7950     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7951                                  OpVT.getVectorNumElements() / SizeFactor);
7952
7953     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7954
7955     // Insert the 128-bit vector.
7956     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7957   }
7958
7959   if (OpVT == MVT::v1i64 &&
7960       Op.getOperand(0).getValueType() == MVT::i64)
7961     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7962
7963   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7964   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7965   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7966                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7967 }
7968
7969 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7970 // a simple subregister reference or explicit instructions to grab
7971 // upper bits of a vector.
7972 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7973                                       SelectionDAG &DAG) {
7974   SDLoc dl(Op);
7975   SDValue In =  Op.getOperand(0);
7976   SDValue Idx = Op.getOperand(1);
7977   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7978   MVT ResVT   = Op.getSimpleValueType();
7979   MVT InVT    = In.getSimpleValueType();
7980
7981   if (Subtarget->hasFp256()) {
7982     if (ResVT.is128BitVector() &&
7983         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7984         isa<ConstantSDNode>(Idx)) {
7985       return Extract128BitVector(In, IdxVal, DAG, dl);
7986     }
7987     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7988         isa<ConstantSDNode>(Idx)) {
7989       return Extract256BitVector(In, IdxVal, DAG, dl);
7990     }
7991   }
7992   return SDValue();
7993 }
7994
7995 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7996 // simple superregister reference or explicit instructions to insert
7997 // the upper bits of a vector.
7998 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7999                                      SelectionDAG &DAG) {
8000   if (Subtarget->hasFp256()) {
8001     SDLoc dl(Op.getNode());
8002     SDValue Vec = Op.getNode()->getOperand(0);
8003     SDValue SubVec = Op.getNode()->getOperand(1);
8004     SDValue Idx = Op.getNode()->getOperand(2);
8005
8006     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8007          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8008         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8009         isa<ConstantSDNode>(Idx)) {
8010       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8011       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8012     }
8013
8014     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8015         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8016         isa<ConstantSDNode>(Idx)) {
8017       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8018       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8019     }
8020   }
8021   return SDValue();
8022 }
8023
8024 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8025 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8026 // one of the above mentioned nodes. It has to be wrapped because otherwise
8027 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8028 // be used to form addressing mode. These wrapped nodes will be selected
8029 // into MOV32ri.
8030 SDValue
8031 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8032   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8033
8034   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8035   // global base reg.
8036   unsigned char OpFlag = 0;
8037   unsigned WrapperKind = X86ISD::Wrapper;
8038   CodeModel::Model M = getTargetMachine().getCodeModel();
8039
8040   if (Subtarget->isPICStyleRIPRel() &&
8041       (M == CodeModel::Small || M == CodeModel::Kernel))
8042     WrapperKind = X86ISD::WrapperRIP;
8043   else if (Subtarget->isPICStyleGOT())
8044     OpFlag = X86II::MO_GOTOFF;
8045   else if (Subtarget->isPICStyleStubPIC())
8046     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8047
8048   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8049                                              CP->getAlignment(),
8050                                              CP->getOffset(), OpFlag);
8051   SDLoc DL(CP);
8052   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8053   // With PIC, the address is actually $g + Offset.
8054   if (OpFlag) {
8055     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8056                          DAG.getNode(X86ISD::GlobalBaseReg,
8057                                      SDLoc(), getPointerTy()),
8058                          Result);
8059   }
8060
8061   return Result;
8062 }
8063
8064 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8065   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8066
8067   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8068   // global base reg.
8069   unsigned char OpFlag = 0;
8070   unsigned WrapperKind = X86ISD::Wrapper;
8071   CodeModel::Model M = getTargetMachine().getCodeModel();
8072
8073   if (Subtarget->isPICStyleRIPRel() &&
8074       (M == CodeModel::Small || M == CodeModel::Kernel))
8075     WrapperKind = X86ISD::WrapperRIP;
8076   else if (Subtarget->isPICStyleGOT())
8077     OpFlag = X86II::MO_GOTOFF;
8078   else if (Subtarget->isPICStyleStubPIC())
8079     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8080
8081   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8082                                           OpFlag);
8083   SDLoc DL(JT);
8084   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8085
8086   // With PIC, the address is actually $g + Offset.
8087   if (OpFlag)
8088     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8089                          DAG.getNode(X86ISD::GlobalBaseReg,
8090                                      SDLoc(), getPointerTy()),
8091                          Result);
8092
8093   return Result;
8094 }
8095
8096 SDValue
8097 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8098   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8099
8100   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8101   // global base reg.
8102   unsigned char OpFlag = 0;
8103   unsigned WrapperKind = X86ISD::Wrapper;
8104   CodeModel::Model M = getTargetMachine().getCodeModel();
8105
8106   if (Subtarget->isPICStyleRIPRel() &&
8107       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8108     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8109       OpFlag = X86II::MO_GOTPCREL;
8110     WrapperKind = X86ISD::WrapperRIP;
8111   } else if (Subtarget->isPICStyleGOT()) {
8112     OpFlag = X86II::MO_GOT;
8113   } else if (Subtarget->isPICStyleStubPIC()) {
8114     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8115   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8116     OpFlag = X86II::MO_DARWIN_NONLAZY;
8117   }
8118
8119   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8120
8121   SDLoc DL(Op);
8122   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8123
8124   // With PIC, the address is actually $g + Offset.
8125   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8126       !Subtarget->is64Bit()) {
8127     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8128                          DAG.getNode(X86ISD::GlobalBaseReg,
8129                                      SDLoc(), getPointerTy()),
8130                          Result);
8131   }
8132
8133   // For symbols that require a load from a stub to get the address, emit the
8134   // load.
8135   if (isGlobalStubReference(OpFlag))
8136     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8137                          MachinePointerInfo::getGOT(), false, false, false, 0);
8138
8139   return Result;
8140 }
8141
8142 SDValue
8143 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8144   // Create the TargetBlockAddressAddress node.
8145   unsigned char OpFlags =
8146     Subtarget->ClassifyBlockAddressReference();
8147   CodeModel::Model M = getTargetMachine().getCodeModel();
8148   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8149   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8150   SDLoc dl(Op);
8151   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8152                                              OpFlags);
8153
8154   if (Subtarget->isPICStyleRIPRel() &&
8155       (M == CodeModel::Small || M == CodeModel::Kernel))
8156     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8157   else
8158     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8159
8160   // With PIC, the address is actually $g + Offset.
8161   if (isGlobalRelativeToPICBase(OpFlags)) {
8162     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8163                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8164                          Result);
8165   }
8166
8167   return Result;
8168 }
8169
8170 SDValue
8171 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8172                                       int64_t Offset, SelectionDAG &DAG) const {
8173   // Create the TargetGlobalAddress node, folding in the constant
8174   // offset if it is legal.
8175   unsigned char OpFlags =
8176     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8177   CodeModel::Model M = getTargetMachine().getCodeModel();
8178   SDValue Result;
8179   if (OpFlags == X86II::MO_NO_FLAG &&
8180       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8181     // A direct static reference to a global.
8182     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8183     Offset = 0;
8184   } else {
8185     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8186   }
8187
8188   if (Subtarget->isPICStyleRIPRel() &&
8189       (M == CodeModel::Small || M == CodeModel::Kernel))
8190     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8191   else
8192     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8193
8194   // With PIC, the address is actually $g + Offset.
8195   if (isGlobalRelativeToPICBase(OpFlags)) {
8196     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8197                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8198                          Result);
8199   }
8200
8201   // For globals that require a load from a stub to get the address, emit the
8202   // load.
8203   if (isGlobalStubReference(OpFlags))
8204     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8205                          MachinePointerInfo::getGOT(), false, false, false, 0);
8206
8207   // If there was a non-zero offset that we didn't fold, create an explicit
8208   // addition for it.
8209   if (Offset != 0)
8210     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8211                          DAG.getConstant(Offset, getPointerTy()));
8212
8213   return Result;
8214 }
8215
8216 SDValue
8217 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8218   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8219   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8220   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8221 }
8222
8223 static SDValue
8224 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8225            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8226            unsigned char OperandFlags, bool LocalDynamic = false) {
8227   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8228   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8229   SDLoc dl(GA);
8230   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8231                                            GA->getValueType(0),
8232                                            GA->getOffset(),
8233                                            OperandFlags);
8234
8235   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8236                                            : X86ISD::TLSADDR;
8237
8238   if (InFlag) {
8239     SDValue Ops[] = { Chain,  TGA, *InFlag };
8240     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8241   } else {
8242     SDValue Ops[]  = { Chain, TGA };
8243     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8244   }
8245
8246   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8247   MFI->setAdjustsStack(true);
8248
8249   SDValue Flag = Chain.getValue(1);
8250   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8251 }
8252
8253 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8254 static SDValue
8255 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8256                                 const EVT PtrVT) {
8257   SDValue InFlag;
8258   SDLoc dl(GA);  // ? function entry point might be better
8259   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8260                                    DAG.getNode(X86ISD::GlobalBaseReg,
8261                                                SDLoc(), PtrVT), InFlag);
8262   InFlag = Chain.getValue(1);
8263
8264   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8265 }
8266
8267 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8268 static SDValue
8269 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8270                                 const EVT PtrVT) {
8271   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8272                     X86::RAX, X86II::MO_TLSGD);
8273 }
8274
8275 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8276                                            SelectionDAG &DAG,
8277                                            const EVT PtrVT,
8278                                            bool is64Bit) {
8279   SDLoc dl(GA);
8280
8281   // Get the start address of the TLS block for this module.
8282   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8283       .getInfo<X86MachineFunctionInfo>();
8284   MFI->incNumLocalDynamicTLSAccesses();
8285
8286   SDValue Base;
8287   if (is64Bit) {
8288     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8289                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8290   } else {
8291     SDValue InFlag;
8292     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8293         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8294     InFlag = Chain.getValue(1);
8295     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8296                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8297   }
8298
8299   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8300   // of Base.
8301
8302   // Build x@dtpoff.
8303   unsigned char OperandFlags = X86II::MO_DTPOFF;
8304   unsigned WrapperKind = X86ISD::Wrapper;
8305   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8306                                            GA->getValueType(0),
8307                                            GA->getOffset(), OperandFlags);
8308   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8309
8310   // Add x@dtpoff with the base.
8311   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8312 }
8313
8314 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8315 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8316                                    const EVT PtrVT, TLSModel::Model model,
8317                                    bool is64Bit, bool isPIC) {
8318   SDLoc dl(GA);
8319
8320   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8321   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8322                                                          is64Bit ? 257 : 256));
8323
8324   SDValue ThreadPointer =
8325       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8326                   MachinePointerInfo(Ptr), false, false, false, 0);
8327
8328   unsigned char OperandFlags = 0;
8329   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8330   // initialexec.
8331   unsigned WrapperKind = X86ISD::Wrapper;
8332   if (model == TLSModel::LocalExec) {
8333     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8334   } else if (model == TLSModel::InitialExec) {
8335     if (is64Bit) {
8336       OperandFlags = X86II::MO_GOTTPOFF;
8337       WrapperKind = X86ISD::WrapperRIP;
8338     } else {
8339       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8340     }
8341   } else {
8342     llvm_unreachable("Unexpected model");
8343   }
8344
8345   // emit "addl x@ntpoff,%eax" (local exec)
8346   // or "addl x@indntpoff,%eax" (initial exec)
8347   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8348   SDValue TGA =
8349       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8350                                  GA->getOffset(), OperandFlags);
8351   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8352
8353   if (model == TLSModel::InitialExec) {
8354     if (isPIC && !is64Bit) {
8355       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8356                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8357                            Offset);
8358     }
8359
8360     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8361                          MachinePointerInfo::getGOT(), false, false, false, 0);
8362   }
8363
8364   // The address of the thread local variable is the add of the thread
8365   // pointer with the offset of the variable.
8366   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8367 }
8368
8369 SDValue
8370 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8371
8372   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8373   const GlobalValue *GV = GA->getGlobal();
8374
8375   if (Subtarget->isTargetELF()) {
8376     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8377
8378     switch (model) {
8379       case TLSModel::GeneralDynamic:
8380         if (Subtarget->is64Bit())
8381           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8382         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8383       case TLSModel::LocalDynamic:
8384         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8385                                            Subtarget->is64Bit());
8386       case TLSModel::InitialExec:
8387       case TLSModel::LocalExec:
8388         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8389                                    Subtarget->is64Bit(),
8390                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8391     }
8392     llvm_unreachable("Unknown TLS model.");
8393   }
8394
8395   if (Subtarget->isTargetDarwin()) {
8396     // Darwin only has one model of TLS.  Lower to that.
8397     unsigned char OpFlag = 0;
8398     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8399                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8400
8401     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8402     // global base reg.
8403     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8404                   !Subtarget->is64Bit();
8405     if (PIC32)
8406       OpFlag = X86II::MO_TLVP_PIC_BASE;
8407     else
8408       OpFlag = X86II::MO_TLVP;
8409     SDLoc DL(Op);
8410     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8411                                                 GA->getValueType(0),
8412                                                 GA->getOffset(), OpFlag);
8413     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8414
8415     // With PIC32, the address is actually $g + Offset.
8416     if (PIC32)
8417       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8418                            DAG.getNode(X86ISD::GlobalBaseReg,
8419                                        SDLoc(), getPointerTy()),
8420                            Offset);
8421
8422     // Lowering the machine isd will make sure everything is in the right
8423     // location.
8424     SDValue Chain = DAG.getEntryNode();
8425     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8426     SDValue Args[] = { Chain, Offset };
8427     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8428
8429     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8430     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8431     MFI->setAdjustsStack(true);
8432
8433     // And our return value (tls address) is in the standard call return value
8434     // location.
8435     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8436     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8437                               Chain.getValue(1));
8438   }
8439
8440   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8441     // Just use the implicit TLS architecture
8442     // Need to generate someting similar to:
8443     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8444     //                                  ; from TEB
8445     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8446     //   mov     rcx, qword [rdx+rcx*8]
8447     //   mov     eax, .tls$:tlsvar
8448     //   [rax+rcx] contains the address
8449     // Windows 64bit: gs:0x58
8450     // Windows 32bit: fs:__tls_array
8451
8452     // If GV is an alias then use the aliasee for determining
8453     // thread-localness.
8454     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8455       GV = GA->resolveAliasedGlobal(false);
8456     SDLoc dl(GA);
8457     SDValue Chain = DAG.getEntryNode();
8458
8459     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8460     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8461     // use its literal value of 0x2C.
8462     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8463                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8464                                                              256)
8465                                         : Type::getInt32PtrTy(*DAG.getContext(),
8466                                                               257));
8467
8468     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8469       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8470         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8471
8472     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8473                                         MachinePointerInfo(Ptr),
8474                                         false, false, false, 0);
8475
8476     // Load the _tls_index variable
8477     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8478     if (Subtarget->is64Bit())
8479       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8480                            IDX, MachinePointerInfo(), MVT::i32,
8481                            false, false, 0);
8482     else
8483       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8484                         false, false, false, 0);
8485
8486     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8487                                     getPointerTy());
8488     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8489
8490     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8491     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8492                       false, false, false, 0);
8493
8494     // Get the offset of start of .tls section
8495     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8496                                              GA->getValueType(0),
8497                                              GA->getOffset(), X86II::MO_SECREL);
8498     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8499
8500     // The address of the thread local variable is the add of the thread
8501     // pointer with the offset of the variable.
8502     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8503   }
8504
8505   llvm_unreachable("TLS not implemented for this target.");
8506 }
8507
8508 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8509 /// and take a 2 x i32 value to shift plus a shift amount.
8510 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8511   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8512   MVT VT = Op.getSimpleValueType();
8513   unsigned VTBits = VT.getSizeInBits();
8514   SDLoc dl(Op);
8515   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8516   SDValue ShOpLo = Op.getOperand(0);
8517   SDValue ShOpHi = Op.getOperand(1);
8518   SDValue ShAmt  = Op.getOperand(2);
8519   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8520   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8521   // during isel.
8522   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8523                                   DAG.getConstant(VTBits - 1, MVT::i8));
8524   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8525                                      DAG.getConstant(VTBits - 1, MVT::i8))
8526                        : DAG.getConstant(0, VT);
8527
8528   SDValue Tmp2, Tmp3;
8529   if (Op.getOpcode() == ISD::SHL_PARTS) {
8530     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8531     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8532   } else {
8533     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8534     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8535   }
8536
8537   // If the shift amount is larger or equal than the width of a part we can't
8538   // rely on the results of shld/shrd. Insert a test and select the appropriate
8539   // values for large shift amounts.
8540   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8541                                 DAG.getConstant(VTBits, MVT::i8));
8542   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8543                              AndNode, DAG.getConstant(0, MVT::i8));
8544
8545   SDValue Hi, Lo;
8546   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8547   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8548   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8549
8550   if (Op.getOpcode() == ISD::SHL_PARTS) {
8551     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8552     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8553   } else {
8554     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8555     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8556   }
8557
8558   SDValue Ops[2] = { Lo, Hi };
8559   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8560 }
8561
8562 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8563                                            SelectionDAG &DAG) const {
8564   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8565
8566   if (SrcVT.isVector())
8567     return SDValue();
8568
8569   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8570          "Unknown SINT_TO_FP to lower!");
8571
8572   // These are really Legal; return the operand so the caller accepts it as
8573   // Legal.
8574   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8575     return Op;
8576   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8577       Subtarget->is64Bit()) {
8578     return Op;
8579   }
8580
8581   SDLoc dl(Op);
8582   unsigned Size = SrcVT.getSizeInBits()/8;
8583   MachineFunction &MF = DAG.getMachineFunction();
8584   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8585   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8586   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8587                                StackSlot,
8588                                MachinePointerInfo::getFixedStack(SSFI),
8589                                false, false, 0);
8590   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8591 }
8592
8593 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8594                                      SDValue StackSlot,
8595                                      SelectionDAG &DAG) const {
8596   // Build the FILD
8597   SDLoc DL(Op);
8598   SDVTList Tys;
8599   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8600   if (useSSE)
8601     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8602   else
8603     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8604
8605   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8606
8607   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8608   MachineMemOperand *MMO;
8609   if (FI) {
8610     int SSFI = FI->getIndex();
8611     MMO =
8612       DAG.getMachineFunction()
8613       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8614                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8615   } else {
8616     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8617     StackSlot = StackSlot.getOperand(1);
8618   }
8619   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8620   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8621                                            X86ISD::FILD, DL,
8622                                            Tys, Ops, array_lengthof(Ops),
8623                                            SrcVT, MMO);
8624
8625   if (useSSE) {
8626     Chain = Result.getValue(1);
8627     SDValue InFlag = Result.getValue(2);
8628
8629     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8630     // shouldn't be necessary except that RFP cannot be live across
8631     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8632     MachineFunction &MF = DAG.getMachineFunction();
8633     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8634     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8635     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8636     Tys = DAG.getVTList(MVT::Other);
8637     SDValue Ops[] = {
8638       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8639     };
8640     MachineMemOperand *MMO =
8641       DAG.getMachineFunction()
8642       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8643                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8644
8645     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8646                                     Ops, array_lengthof(Ops),
8647                                     Op.getValueType(), MMO);
8648     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8649                          MachinePointerInfo::getFixedStack(SSFI),
8650                          false, false, false, 0);
8651   }
8652
8653   return Result;
8654 }
8655
8656 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8657 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8658                                                SelectionDAG &DAG) const {
8659   // This algorithm is not obvious. Here it is what we're trying to output:
8660   /*
8661      movq       %rax,  %xmm0
8662      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8663      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8664      #ifdef __SSE3__
8665        haddpd   %xmm0, %xmm0
8666      #else
8667        pshufd   $0x4e, %xmm0, %xmm1
8668        addpd    %xmm1, %xmm0
8669      #endif
8670   */
8671
8672   SDLoc dl(Op);
8673   LLVMContext *Context = DAG.getContext();
8674
8675   // Build some magic constants.
8676   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8677   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8678   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8679
8680   SmallVector<Constant*,2> CV1;
8681   CV1.push_back(
8682     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8683                                       APInt(64, 0x4330000000000000ULL))));
8684   CV1.push_back(
8685     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8686                                       APInt(64, 0x4530000000000000ULL))));
8687   Constant *C1 = ConstantVector::get(CV1);
8688   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8689
8690   // Load the 64-bit value into an XMM register.
8691   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8692                             Op.getOperand(0));
8693   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8694                               MachinePointerInfo::getConstantPool(),
8695                               false, false, false, 16);
8696   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8697                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8698                               CLod0);
8699
8700   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8701                               MachinePointerInfo::getConstantPool(),
8702                               false, false, false, 16);
8703   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8704   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8705   SDValue Result;
8706
8707   if (Subtarget->hasSSE3()) {
8708     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8709     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8710   } else {
8711     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8712     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8713                                            S2F, 0x4E, DAG);
8714     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8715                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8716                          Sub);
8717   }
8718
8719   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8720                      DAG.getIntPtrConstant(0));
8721 }
8722
8723 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8724 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8725                                                SelectionDAG &DAG) const {
8726   SDLoc dl(Op);
8727   // FP constant to bias correct the final result.
8728   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8729                                    MVT::f64);
8730
8731   // Load the 32-bit value into an XMM register.
8732   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8733                              Op.getOperand(0));
8734
8735   // Zero out the upper parts of the register.
8736   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8737
8738   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8739                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8740                      DAG.getIntPtrConstant(0));
8741
8742   // Or the load with the bias.
8743   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8744                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8745                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8746                                                    MVT::v2f64, Load)),
8747                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8748                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8749                                                    MVT::v2f64, Bias)));
8750   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8751                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8752                    DAG.getIntPtrConstant(0));
8753
8754   // Subtract the bias.
8755   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8756
8757   // Handle final rounding.
8758   EVT DestVT = Op.getValueType();
8759
8760   if (DestVT.bitsLT(MVT::f64))
8761     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8762                        DAG.getIntPtrConstant(0));
8763   if (DestVT.bitsGT(MVT::f64))
8764     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8765
8766   // Handle final rounding.
8767   return Sub;
8768 }
8769
8770 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8771                                                SelectionDAG &DAG) const {
8772   SDValue N0 = Op.getOperand(0);
8773   MVT SVT = N0.getSimpleValueType();
8774   SDLoc dl(Op);
8775
8776   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8777           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8778          "Custom UINT_TO_FP is not supported!");
8779
8780   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
8781   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8782                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8783 }
8784
8785 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8786                                            SelectionDAG &DAG) const {
8787   SDValue N0 = Op.getOperand(0);
8788   SDLoc dl(Op);
8789
8790   if (Op.getValueType().isVector())
8791     return lowerUINT_TO_FP_vec(Op, DAG);
8792
8793   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8794   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8795   // the optimization here.
8796   if (DAG.SignBitIsZero(N0))
8797     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8798
8799   MVT SrcVT = N0.getSimpleValueType();
8800   MVT DstVT = Op.getSimpleValueType();
8801   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8802     return LowerUINT_TO_FP_i64(Op, DAG);
8803   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8804     return LowerUINT_TO_FP_i32(Op, DAG);
8805   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8806     return SDValue();
8807
8808   // Make a 64-bit buffer, and use it to build an FILD.
8809   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8810   if (SrcVT == MVT::i32) {
8811     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8812     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8813                                      getPointerTy(), StackSlot, WordOff);
8814     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8815                                   StackSlot, MachinePointerInfo(),
8816                                   false, false, 0);
8817     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8818                                   OffsetSlot, MachinePointerInfo(),
8819                                   false, false, 0);
8820     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8821     return Fild;
8822   }
8823
8824   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8825   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8826                                StackSlot, MachinePointerInfo(),
8827                                false, false, 0);
8828   // For i64 source, we need to add the appropriate power of 2 if the input
8829   // was negative.  This is the same as the optimization in
8830   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8831   // we must be careful to do the computation in x87 extended precision, not
8832   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8833   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8834   MachineMemOperand *MMO =
8835     DAG.getMachineFunction()
8836     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8837                           MachineMemOperand::MOLoad, 8, 8);
8838
8839   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8840   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8841   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8842                                          array_lengthof(Ops), MVT::i64, MMO);
8843
8844   APInt FF(32, 0x5F800000ULL);
8845
8846   // Check whether the sign bit is set.
8847   SDValue SignSet = DAG.getSetCC(dl,
8848                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8849                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8850                                  ISD::SETLT);
8851
8852   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8853   SDValue FudgePtr = DAG.getConstantPool(
8854                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8855                                          getPointerTy());
8856
8857   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8858   SDValue Zero = DAG.getIntPtrConstant(0);
8859   SDValue Four = DAG.getIntPtrConstant(4);
8860   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8861                                Zero, Four);
8862   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8863
8864   // Load the value out, extending it from f32 to f80.
8865   // FIXME: Avoid the extend by constructing the right constant pool?
8866   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8867                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8868                                  MVT::f32, false, false, 4);
8869   // Extend everything to 80 bits to force it to be done on x87.
8870   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8871   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8872 }
8873
8874 std::pair<SDValue,SDValue>
8875 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8876                                     bool IsSigned, bool IsReplace) const {
8877   SDLoc DL(Op);
8878
8879   EVT DstTy = Op.getValueType();
8880
8881   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8882     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8883     DstTy = MVT::i64;
8884   }
8885
8886   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8887          DstTy.getSimpleVT() >= MVT::i16 &&
8888          "Unknown FP_TO_INT to lower!");
8889
8890   // These are really Legal.
8891   if (DstTy == MVT::i32 &&
8892       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8893     return std::make_pair(SDValue(), SDValue());
8894   if (Subtarget->is64Bit() &&
8895       DstTy == MVT::i64 &&
8896       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8897     return std::make_pair(SDValue(), SDValue());
8898
8899   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8900   // stack slot, or into the FTOL runtime function.
8901   MachineFunction &MF = DAG.getMachineFunction();
8902   unsigned MemSize = DstTy.getSizeInBits()/8;
8903   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8904   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8905
8906   unsigned Opc;
8907   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8908     Opc = X86ISD::WIN_FTOL;
8909   else
8910     switch (DstTy.getSimpleVT().SimpleTy) {
8911     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8912     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8913     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8914     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8915     }
8916
8917   SDValue Chain = DAG.getEntryNode();
8918   SDValue Value = Op.getOperand(0);
8919   EVT TheVT = Op.getOperand(0).getValueType();
8920   // FIXME This causes a redundant load/store if the SSE-class value is already
8921   // in memory, such as if it is on the callstack.
8922   if (isScalarFPTypeInSSEReg(TheVT)) {
8923     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8924     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8925                          MachinePointerInfo::getFixedStack(SSFI),
8926                          false, false, 0);
8927     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8928     SDValue Ops[] = {
8929       Chain, StackSlot, DAG.getValueType(TheVT)
8930     };
8931
8932     MachineMemOperand *MMO =
8933       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8934                               MachineMemOperand::MOLoad, MemSize, MemSize);
8935     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8936                                     array_lengthof(Ops), DstTy, MMO);
8937     Chain = Value.getValue(1);
8938     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8939     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8940   }
8941
8942   MachineMemOperand *MMO =
8943     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8944                             MachineMemOperand::MOStore, MemSize, MemSize);
8945
8946   if (Opc != X86ISD::WIN_FTOL) {
8947     // Build the FP_TO_INT*_IN_MEM
8948     SDValue Ops[] = { Chain, Value, StackSlot };
8949     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8950                                            Ops, array_lengthof(Ops), DstTy,
8951                                            MMO);
8952     return std::make_pair(FIST, StackSlot);
8953   } else {
8954     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8955       DAG.getVTList(MVT::Other, MVT::Glue),
8956       Chain, Value);
8957     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8958       MVT::i32, ftol.getValue(1));
8959     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8960       MVT::i32, eax.getValue(2));
8961     SDValue Ops[] = { eax, edx };
8962     SDValue pair = IsReplace
8963       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8964       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8965     return std::make_pair(pair, SDValue());
8966   }
8967 }
8968
8969 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8970                               const X86Subtarget *Subtarget) {
8971   MVT VT = Op->getSimpleValueType(0);
8972   SDValue In = Op->getOperand(0);
8973   MVT InVT = In.getSimpleValueType();
8974   SDLoc dl(Op);
8975
8976   // Optimize vectors in AVX mode:
8977   //
8978   //   v8i16 -> v8i32
8979   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8980   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8981   //   Concat upper and lower parts.
8982   //
8983   //   v4i32 -> v4i64
8984   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8985   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8986   //   Concat upper and lower parts.
8987   //
8988
8989   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
8990       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8991       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8992     return SDValue();
8993
8994   if (Subtarget->hasInt256())
8995     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8996
8997   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8998   SDValue Undef = DAG.getUNDEF(InVT);
8999   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9000   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9001   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9002
9003   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9004                              VT.getVectorNumElements()/2);
9005
9006   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9007   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9008
9009   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9010 }
9011
9012 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9013                                         SelectionDAG &DAG) {
9014   MVT VT = Op->getSimpleValueType(0);
9015   SDValue In = Op->getOperand(0);
9016   MVT InVT = In.getSimpleValueType();
9017   SDLoc DL(Op);
9018   unsigned int NumElts = VT.getVectorNumElements();
9019   if (NumElts != 8 && NumElts != 16)
9020     return SDValue();
9021
9022   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9023     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9024
9025   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9026   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9027   // Now we have only mask extension
9028   assert(InVT.getVectorElementType() == MVT::i1);
9029   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9030   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9031   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9032   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9033   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9034                            MachinePointerInfo::getConstantPool(),
9035                            false, false, false, Alignment);
9036
9037   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9038   if (VT.is512BitVector())
9039     return Brcst;
9040   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9041 }
9042
9043 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9044                                SelectionDAG &DAG) {
9045   if (Subtarget->hasFp256()) {
9046     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9047     if (Res.getNode())
9048       return Res;
9049   }
9050
9051   return SDValue();
9052 }
9053
9054 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9055                                 SelectionDAG &DAG) {
9056   SDLoc DL(Op);
9057   MVT VT = Op.getSimpleValueType();
9058   SDValue In = Op.getOperand(0);
9059   MVT SVT = In.getSimpleValueType();
9060
9061   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9062     return LowerZERO_EXTEND_AVX512(Op, DAG);
9063
9064   if (Subtarget->hasFp256()) {
9065     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9066     if (Res.getNode())
9067       return Res;
9068   }
9069
9070   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9071          VT.getVectorNumElements() != SVT.getVectorNumElements());
9072   return SDValue();
9073 }
9074
9075 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9076   SDLoc DL(Op);
9077   MVT VT = Op.getSimpleValueType();
9078   SDValue In = Op.getOperand(0);
9079   MVT InVT = In.getSimpleValueType();
9080
9081   if (VT == MVT::i1) {
9082     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9083            "Invalid scalar TRUNCATE operation");
9084     if (InVT == MVT::i32)
9085       return SDValue();
9086     if (InVT.getSizeInBits() == 64)
9087       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9088     else if (InVT.getSizeInBits() < 32)
9089       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9090     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9091   }
9092   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9093          "Invalid TRUNCATE operation");
9094
9095   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9096     if (VT.getVectorElementType().getSizeInBits() >=8)
9097       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9098
9099     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9100     unsigned NumElts = InVT.getVectorNumElements();
9101     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9102     if (InVT.getSizeInBits() < 512) {
9103       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9104       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9105       InVT = ExtVT;
9106     }
9107     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9108     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9109     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9110     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9111     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9112                            MachinePointerInfo::getConstantPool(),
9113                            false, false, false, Alignment);
9114     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9115     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9116     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9117   }
9118
9119   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9120     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9121     if (Subtarget->hasInt256()) {
9122       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9123       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9124       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9125                                 ShufMask);
9126       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9127                          DAG.getIntPtrConstant(0));
9128     }
9129
9130     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
9131     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9132                                DAG.getIntPtrConstant(0));
9133     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9134                                DAG.getIntPtrConstant(2));
9135
9136     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9137     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9138
9139     // The PSHUFD mask:
9140     static const int ShufMask1[] = {0, 2, 0, 0};
9141     SDValue Undef = DAG.getUNDEF(VT);
9142     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
9143     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
9144
9145     // The MOVLHPS mask:
9146     static const int ShufMask2[] = {0, 1, 4, 5};
9147     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
9148   }
9149
9150   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9151     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9152     if (Subtarget->hasInt256()) {
9153       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9154
9155       SmallVector<SDValue,32> pshufbMask;
9156       for (unsigned i = 0; i < 2; ++i) {
9157         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9158         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9159         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9160         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9161         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9162         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9163         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9164         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9165         for (unsigned j = 0; j < 8; ++j)
9166           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9167       }
9168       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
9169                                &pshufbMask[0], 32);
9170       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9171       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9172
9173       static const int ShufMask[] = {0,  2,  -1,  -1};
9174       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9175                                 &ShufMask[0]);
9176       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9177                        DAG.getIntPtrConstant(0));
9178       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9179     }
9180
9181     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9182                                DAG.getIntPtrConstant(0));
9183
9184     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9185                                DAG.getIntPtrConstant(4));
9186
9187     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9188     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9189
9190     // The PSHUFB mask:
9191     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9192                                    -1, -1, -1, -1, -1, -1, -1, -1};
9193
9194     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9195     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9196     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9197
9198     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9199     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9200
9201     // The MOVLHPS Mask:
9202     static const int ShufMask2[] = {0, 1, 4, 5};
9203     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9204     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9205   }
9206
9207   // Handle truncation of V256 to V128 using shuffles.
9208   if (!VT.is128BitVector() || !InVT.is256BitVector())
9209     return SDValue();
9210
9211   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9212
9213   unsigned NumElems = VT.getVectorNumElements();
9214   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9215
9216   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9217   // Prepare truncation shuffle mask
9218   for (unsigned i = 0; i != NumElems; ++i)
9219     MaskVec[i] = i * 2;
9220   SDValue V = DAG.getVectorShuffle(NVT, DL,
9221                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9222                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9223   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9224                      DAG.getIntPtrConstant(0));
9225 }
9226
9227 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9228                                            SelectionDAG &DAG) const {
9229   MVT VT = Op.getSimpleValueType();
9230   if (VT.isVector()) {
9231     if (VT == MVT::v8i16)
9232       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
9233                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
9234                                      MVT::v8i32, Op.getOperand(0)));
9235     return SDValue();
9236   }
9237
9238   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9239     /*IsSigned=*/ true, /*IsReplace=*/ false);
9240   SDValue FIST = Vals.first, StackSlot = Vals.second;
9241   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9242   if (FIST.getNode() == 0) return Op;
9243
9244   if (StackSlot.getNode())
9245     // Load the result.
9246     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9247                        FIST, StackSlot, MachinePointerInfo(),
9248                        false, false, false, 0);
9249
9250   // The node is the result.
9251   return FIST;
9252 }
9253
9254 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9255                                            SelectionDAG &DAG) const {
9256   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9257     /*IsSigned=*/ false, /*IsReplace=*/ false);
9258   SDValue FIST = Vals.first, StackSlot = Vals.second;
9259   assert(FIST.getNode() && "Unexpected failure");
9260
9261   if (StackSlot.getNode())
9262     // Load the result.
9263     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9264                        FIST, StackSlot, MachinePointerInfo(),
9265                        false, false, false, 0);
9266
9267   // The node is the result.
9268   return FIST;
9269 }
9270
9271 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9272   SDLoc DL(Op);
9273   MVT VT = Op.getSimpleValueType();
9274   SDValue In = Op.getOperand(0);
9275   MVT SVT = In.getSimpleValueType();
9276
9277   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9278
9279   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9280                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9281                                  In, DAG.getUNDEF(SVT)));
9282 }
9283
9284 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9285   LLVMContext *Context = DAG.getContext();
9286   SDLoc dl(Op);
9287   MVT VT = Op.getSimpleValueType();
9288   MVT EltVT = VT;
9289   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9290   if (VT.isVector()) {
9291     EltVT = VT.getVectorElementType();
9292     NumElts = VT.getVectorNumElements();
9293   }
9294   Constant *C;
9295   if (EltVT == MVT::f64)
9296     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9297                                           APInt(64, ~(1ULL << 63))));
9298   else
9299     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9300                                           APInt(32, ~(1U << 31))));
9301   C = ConstantVector::getSplat(NumElts, C);
9302   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9303   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9304   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9305   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9306                              MachinePointerInfo::getConstantPool(),
9307                              false, false, false, Alignment);
9308   if (VT.isVector()) {
9309     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9310     return DAG.getNode(ISD::BITCAST, dl, VT,
9311                        DAG.getNode(ISD::AND, dl, ANDVT,
9312                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9313                                                Op.getOperand(0)),
9314                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9315   }
9316   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9317 }
9318
9319 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9320   LLVMContext *Context = DAG.getContext();
9321   SDLoc dl(Op);
9322   MVT VT = Op.getSimpleValueType();
9323   MVT EltVT = VT;
9324   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9325   if (VT.isVector()) {
9326     EltVT = VT.getVectorElementType();
9327     NumElts = VT.getVectorNumElements();
9328   }
9329   Constant *C;
9330   if (EltVT == MVT::f64)
9331     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9332                                           APInt(64, 1ULL << 63)));
9333   else
9334     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9335                                           APInt(32, 1U << 31)));
9336   C = ConstantVector::getSplat(NumElts, C);
9337   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9338   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9339   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9340   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9341                              MachinePointerInfo::getConstantPool(),
9342                              false, false, false, Alignment);
9343   if (VT.isVector()) {
9344     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9345     return DAG.getNode(ISD::BITCAST, dl, VT,
9346                        DAG.getNode(ISD::XOR, dl, XORVT,
9347                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9348                                                Op.getOperand(0)),
9349                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9350   }
9351
9352   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9353 }
9354
9355 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9356   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9357   LLVMContext *Context = DAG.getContext();
9358   SDValue Op0 = Op.getOperand(0);
9359   SDValue Op1 = Op.getOperand(1);
9360   SDLoc dl(Op);
9361   MVT VT = Op.getSimpleValueType();
9362   MVT SrcVT = Op1.getSimpleValueType();
9363
9364   // If second operand is smaller, extend it first.
9365   if (SrcVT.bitsLT(VT)) {
9366     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9367     SrcVT = VT;
9368   }
9369   // And if it is bigger, shrink it first.
9370   if (SrcVT.bitsGT(VT)) {
9371     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9372     SrcVT = VT;
9373   }
9374
9375   // At this point the operands and the result should have the same
9376   // type, and that won't be f80 since that is not custom lowered.
9377
9378   // First get the sign bit of second operand.
9379   SmallVector<Constant*,4> CV;
9380   if (SrcVT == MVT::f64) {
9381     const fltSemantics &Sem = APFloat::IEEEdouble;
9382     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9383     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9384   } else {
9385     const fltSemantics &Sem = APFloat::IEEEsingle;
9386     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9387     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9388     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9389     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9390   }
9391   Constant *C = ConstantVector::get(CV);
9392   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9393   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9394                               MachinePointerInfo::getConstantPool(),
9395                               false, false, false, 16);
9396   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9397
9398   // Shift sign bit right or left if the two operands have different types.
9399   if (SrcVT.bitsGT(VT)) {
9400     // Op0 is MVT::f32, Op1 is MVT::f64.
9401     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9402     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9403                           DAG.getConstant(32, MVT::i32));
9404     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9405     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9406                           DAG.getIntPtrConstant(0));
9407   }
9408
9409   // Clear first operand sign bit.
9410   CV.clear();
9411   if (VT == MVT::f64) {
9412     const fltSemantics &Sem = APFloat::IEEEdouble;
9413     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9414                                                    APInt(64, ~(1ULL << 63)))));
9415     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9416   } else {
9417     const fltSemantics &Sem = APFloat::IEEEsingle;
9418     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9419                                                    APInt(32, ~(1U << 31)))));
9420     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9421     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9422     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9423   }
9424   C = ConstantVector::get(CV);
9425   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9426   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9427                               MachinePointerInfo::getConstantPool(),
9428                               false, false, false, 16);
9429   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9430
9431   // Or the value with the sign bit.
9432   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9433 }
9434
9435 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9436   SDValue N0 = Op.getOperand(0);
9437   SDLoc dl(Op);
9438   MVT VT = Op.getSimpleValueType();
9439
9440   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9441   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9442                                   DAG.getConstant(1, VT));
9443   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9444 }
9445
9446 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9447 //
9448 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9449                                       SelectionDAG &DAG) {
9450   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9451
9452   if (!Subtarget->hasSSE41())
9453     return SDValue();
9454
9455   if (!Op->hasOneUse())
9456     return SDValue();
9457
9458   SDNode *N = Op.getNode();
9459   SDLoc DL(N);
9460
9461   SmallVector<SDValue, 8> Opnds;
9462   DenseMap<SDValue, unsigned> VecInMap;
9463   EVT VT = MVT::Other;
9464
9465   // Recognize a special case where a vector is casted into wide integer to
9466   // test all 0s.
9467   Opnds.push_back(N->getOperand(0));
9468   Opnds.push_back(N->getOperand(1));
9469
9470   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9471     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9472     // BFS traverse all OR'd operands.
9473     if (I->getOpcode() == ISD::OR) {
9474       Opnds.push_back(I->getOperand(0));
9475       Opnds.push_back(I->getOperand(1));
9476       // Re-evaluate the number of nodes to be traversed.
9477       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9478       continue;
9479     }
9480
9481     // Quit if a non-EXTRACT_VECTOR_ELT
9482     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9483       return SDValue();
9484
9485     // Quit if without a constant index.
9486     SDValue Idx = I->getOperand(1);
9487     if (!isa<ConstantSDNode>(Idx))
9488       return SDValue();
9489
9490     SDValue ExtractedFromVec = I->getOperand(0);
9491     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9492     if (M == VecInMap.end()) {
9493       VT = ExtractedFromVec.getValueType();
9494       // Quit if not 128/256-bit vector.
9495       if (!VT.is128BitVector() && !VT.is256BitVector())
9496         return SDValue();
9497       // Quit if not the same type.
9498       if (VecInMap.begin() != VecInMap.end() &&
9499           VT != VecInMap.begin()->first.getValueType())
9500         return SDValue();
9501       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9502     }
9503     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9504   }
9505
9506   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9507          "Not extracted from 128-/256-bit vector.");
9508
9509   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9510   SmallVector<SDValue, 8> VecIns;
9511
9512   for (DenseMap<SDValue, unsigned>::const_iterator
9513         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9514     // Quit if not all elements are used.
9515     if (I->second != FullMask)
9516       return SDValue();
9517     VecIns.push_back(I->first);
9518   }
9519
9520   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9521
9522   // Cast all vectors into TestVT for PTEST.
9523   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9524     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9525
9526   // If more than one full vectors are evaluated, OR them first before PTEST.
9527   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9528     // Each iteration will OR 2 nodes and append the result until there is only
9529     // 1 node left, i.e. the final OR'd value of all vectors.
9530     SDValue LHS = VecIns[Slot];
9531     SDValue RHS = VecIns[Slot + 1];
9532     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9533   }
9534
9535   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9536                      VecIns.back(), VecIns.back());
9537 }
9538
9539 /// Emit nodes that will be selected as "test Op0,Op0", or something
9540 /// equivalent.
9541 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9542                                     SelectionDAG &DAG) const {
9543   SDLoc dl(Op);
9544
9545   // CF and OF aren't always set the way we want. Determine which
9546   // of these we need.
9547   bool NeedCF = false;
9548   bool NeedOF = false;
9549   switch (X86CC) {
9550   default: break;
9551   case X86::COND_A: case X86::COND_AE:
9552   case X86::COND_B: case X86::COND_BE:
9553     NeedCF = true;
9554     break;
9555   case X86::COND_G: case X86::COND_GE:
9556   case X86::COND_L: case X86::COND_LE:
9557   case X86::COND_O: case X86::COND_NO:
9558     NeedOF = true;
9559     break;
9560   }
9561
9562   // See if we can use the EFLAGS value from the operand instead of
9563   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9564   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9565   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9566     // Emit a CMP with 0, which is the TEST pattern.
9567     if (Op.getValueType() == MVT::i1)
9568       return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9569                          DAG.getConstant(0, MVT::i1));
9570     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9571                        DAG.getConstant(0, Op.getValueType()));
9572   }
9573   unsigned Opcode = 0;
9574   unsigned NumOperands = 0;
9575
9576   // Truncate operations may prevent the merge of the SETCC instruction
9577   // and the arithmetic instruction before it. Attempt to truncate the operands
9578   // of the arithmetic instruction and use a reduced bit-width instruction.
9579   bool NeedTruncation = false;
9580   SDValue ArithOp = Op;
9581   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9582     SDValue Arith = Op->getOperand(0);
9583     // Both the trunc and the arithmetic op need to have one user each.
9584     if (Arith->hasOneUse())
9585       switch (Arith.getOpcode()) {
9586         default: break;
9587         case ISD::ADD:
9588         case ISD::SUB:
9589         case ISD::AND:
9590         case ISD::OR:
9591         case ISD::XOR: {
9592           NeedTruncation = true;
9593           ArithOp = Arith;
9594         }
9595       }
9596   }
9597
9598   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9599   // which may be the result of a CAST.  We use the variable 'Op', which is the
9600   // non-casted variable when we check for possible users.
9601   switch (ArithOp.getOpcode()) {
9602   case ISD::ADD:
9603     // Due to an isel shortcoming, be conservative if this add is likely to be
9604     // selected as part of a load-modify-store instruction. When the root node
9605     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9606     // uses of other nodes in the match, such as the ADD in this case. This
9607     // leads to the ADD being left around and reselected, with the result being
9608     // two adds in the output.  Alas, even if none our users are stores, that
9609     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9610     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9611     // climbing the DAG back to the root, and it doesn't seem to be worth the
9612     // effort.
9613     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9614          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9615       if (UI->getOpcode() != ISD::CopyToReg &&
9616           UI->getOpcode() != ISD::SETCC &&
9617           UI->getOpcode() != ISD::STORE)
9618         goto default_case;
9619
9620     if (ConstantSDNode *C =
9621         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9622       // An add of one will be selected as an INC.
9623       if (C->getAPIntValue() == 1) {
9624         Opcode = X86ISD::INC;
9625         NumOperands = 1;
9626         break;
9627       }
9628
9629       // An add of negative one (subtract of one) will be selected as a DEC.
9630       if (C->getAPIntValue().isAllOnesValue()) {
9631         Opcode = X86ISD::DEC;
9632         NumOperands = 1;
9633         break;
9634       }
9635     }
9636
9637     // Otherwise use a regular EFLAGS-setting add.
9638     Opcode = X86ISD::ADD;
9639     NumOperands = 2;
9640     break;
9641   case ISD::AND: {
9642     // If the primary and result isn't used, don't bother using X86ISD::AND,
9643     // because a TEST instruction will be better.
9644     bool NonFlagUse = false;
9645     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9646            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9647       SDNode *User = *UI;
9648       unsigned UOpNo = UI.getOperandNo();
9649       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9650         // Look pass truncate.
9651         UOpNo = User->use_begin().getOperandNo();
9652         User = *User->use_begin();
9653       }
9654
9655       if (User->getOpcode() != ISD::BRCOND &&
9656           User->getOpcode() != ISD::SETCC &&
9657           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9658         NonFlagUse = true;
9659         break;
9660       }
9661     }
9662
9663     if (!NonFlagUse)
9664       break;
9665   }
9666     // FALL THROUGH
9667   case ISD::SUB:
9668   case ISD::OR:
9669   case ISD::XOR:
9670     // Due to the ISEL shortcoming noted above, be conservative if this op is
9671     // likely to be selected as part of a load-modify-store instruction.
9672     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9673            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9674       if (UI->getOpcode() == ISD::STORE)
9675         goto default_case;
9676
9677     // Otherwise use a regular EFLAGS-setting instruction.
9678     switch (ArithOp.getOpcode()) {
9679     default: llvm_unreachable("unexpected operator!");
9680     case ISD::SUB: Opcode = X86ISD::SUB; break;
9681     case ISD::XOR: Opcode = X86ISD::XOR; break;
9682     case ISD::AND: Opcode = X86ISD::AND; break;
9683     case ISD::OR: {
9684       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9685         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9686         if (EFLAGS.getNode())
9687           return EFLAGS;
9688       }
9689       Opcode = X86ISD::OR;
9690       break;
9691     }
9692     }
9693
9694     NumOperands = 2;
9695     break;
9696   case X86ISD::ADD:
9697   case X86ISD::SUB:
9698   case X86ISD::INC:
9699   case X86ISD::DEC:
9700   case X86ISD::OR:
9701   case X86ISD::XOR:
9702   case X86ISD::AND:
9703     return SDValue(Op.getNode(), 1);
9704   default:
9705   default_case:
9706     break;
9707   }
9708
9709   // If we found that truncation is beneficial, perform the truncation and
9710   // update 'Op'.
9711   if (NeedTruncation) {
9712     EVT VT = Op.getValueType();
9713     SDValue WideVal = Op->getOperand(0);
9714     EVT WideVT = WideVal.getValueType();
9715     unsigned ConvertedOp = 0;
9716     // Use a target machine opcode to prevent further DAGCombine
9717     // optimizations that may separate the arithmetic operations
9718     // from the setcc node.
9719     switch (WideVal.getOpcode()) {
9720       default: break;
9721       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9722       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9723       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9724       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9725       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9726     }
9727
9728     if (ConvertedOp) {
9729       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9730       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9731         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9732         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9733         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9734       }
9735     }
9736   }
9737
9738   if (Opcode == 0)
9739     // Emit a CMP with 0, which is the TEST pattern.
9740     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9741                        DAG.getConstant(0, Op.getValueType()));
9742
9743   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9744   SmallVector<SDValue, 4> Ops;
9745   for (unsigned i = 0; i != NumOperands; ++i)
9746     Ops.push_back(Op.getOperand(i));
9747
9748   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9749   DAG.ReplaceAllUsesWith(Op, New);
9750   return SDValue(New.getNode(), 1);
9751 }
9752
9753 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9754 /// equivalent.
9755 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9756                                    SelectionDAG &DAG) const {
9757   SDLoc dl(Op0);
9758   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
9759     if (C->getAPIntValue() == 0)
9760       return EmitTest(Op0, X86CC, DAG);
9761
9762      if (Op0.getValueType() == MVT::i1) {
9763       Op0 = DAG.getNode(ISD::XOR, dl, MVT::i1, Op0,
9764                         DAG.getConstant(-1, MVT::i1));
9765       return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op0,
9766                          DAG.getConstant(0, MVT::i1));
9767      }
9768   }
9769  
9770   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9771        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9772     // Do the comparison at i32 if it's smaller. This avoids subregister
9773     // aliasing issues. Keep the smaller reference if we're optimizing for
9774     // size, however, as that'll allow better folding of memory operations.
9775     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
9776         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
9777              AttributeSet::FunctionIndex, Attribute::MinSize)) {
9778       unsigned ExtendOp =
9779           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
9780       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
9781       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
9782     }
9783     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9784     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9785     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9786                               Op0, Op1);
9787     return SDValue(Sub.getNode(), 1);
9788   }
9789   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9790 }
9791
9792 /// Convert a comparison if required by the subtarget.
9793 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9794                                                  SelectionDAG &DAG) const {
9795   // If the subtarget does not support the FUCOMI instruction, floating-point
9796   // comparisons have to be converted.
9797   if (Subtarget->hasCMov() ||
9798       Cmp.getOpcode() != X86ISD::CMP ||
9799       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9800       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9801     return Cmp;
9802
9803   // The instruction selector will select an FUCOM instruction instead of
9804   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9805   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9806   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9807   SDLoc dl(Cmp);
9808   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9809   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9810   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9811                             DAG.getConstant(8, MVT::i8));
9812   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9813   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9814 }
9815
9816 static bool isAllOnes(SDValue V) {
9817   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9818   return C && C->isAllOnesValue();
9819 }
9820
9821 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9822 /// if it's possible.
9823 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9824                                      SDLoc dl, SelectionDAG &DAG) const {
9825   SDValue Op0 = And.getOperand(0);
9826   SDValue Op1 = And.getOperand(1);
9827   if (Op0.getOpcode() == ISD::TRUNCATE)
9828     Op0 = Op0.getOperand(0);
9829   if (Op1.getOpcode() == ISD::TRUNCATE)
9830     Op1 = Op1.getOperand(0);
9831
9832   SDValue LHS, RHS;
9833   if (Op1.getOpcode() == ISD::SHL)
9834     std::swap(Op0, Op1);
9835   if (Op0.getOpcode() == ISD::SHL) {
9836     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9837       if (And00C->getZExtValue() == 1) {
9838         // If we looked past a truncate, check that it's only truncating away
9839         // known zeros.
9840         unsigned BitWidth = Op0.getValueSizeInBits();
9841         unsigned AndBitWidth = And.getValueSizeInBits();
9842         if (BitWidth > AndBitWidth) {
9843           APInt Zeros, Ones;
9844           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9845           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9846             return SDValue();
9847         }
9848         LHS = Op1;
9849         RHS = Op0.getOperand(1);
9850       }
9851   } else if (Op1.getOpcode() == ISD::Constant) {
9852     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9853     uint64_t AndRHSVal = AndRHS->getZExtValue();
9854     SDValue AndLHS = Op0;
9855
9856     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9857       LHS = AndLHS.getOperand(0);
9858       RHS = AndLHS.getOperand(1);
9859     }
9860
9861     // Use BT if the immediate can't be encoded in a TEST instruction.
9862     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9863       LHS = AndLHS;
9864       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9865     }
9866   }
9867
9868   if (LHS.getNode()) {
9869     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9870     // instruction.  Since the shift amount is in-range-or-undefined, we know
9871     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9872     // the encoding for the i16 version is larger than the i32 version.
9873     // Also promote i16 to i32 for performance / code size reason.
9874     if (LHS.getValueType() == MVT::i8 ||
9875         LHS.getValueType() == MVT::i16)
9876       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9877
9878     // If the operand types disagree, extend the shift amount to match.  Since
9879     // BT ignores high bits (like shifts) we can use anyextend.
9880     if (LHS.getValueType() != RHS.getValueType())
9881       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9882
9883     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9884     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9885     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9886                        DAG.getConstant(Cond, MVT::i8), BT);
9887   }
9888
9889   return SDValue();
9890 }
9891
9892 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9893 /// mask CMPs.
9894 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9895                               SDValue &Op1) {
9896   unsigned SSECC;
9897   bool Swap = false;
9898
9899   // SSE Condition code mapping:
9900   //  0 - EQ
9901   //  1 - LT
9902   //  2 - LE
9903   //  3 - UNORD
9904   //  4 - NEQ
9905   //  5 - NLT
9906   //  6 - NLE
9907   //  7 - ORD
9908   switch (SetCCOpcode) {
9909   default: llvm_unreachable("Unexpected SETCC condition");
9910   case ISD::SETOEQ:
9911   case ISD::SETEQ:  SSECC = 0; break;
9912   case ISD::SETOGT:
9913   case ISD::SETGT:  Swap = true; // Fallthrough
9914   case ISD::SETLT:
9915   case ISD::SETOLT: SSECC = 1; break;
9916   case ISD::SETOGE:
9917   case ISD::SETGE:  Swap = true; // Fallthrough
9918   case ISD::SETLE:
9919   case ISD::SETOLE: SSECC = 2; break;
9920   case ISD::SETUO:  SSECC = 3; break;
9921   case ISD::SETUNE:
9922   case ISD::SETNE:  SSECC = 4; break;
9923   case ISD::SETULE: Swap = true; // Fallthrough
9924   case ISD::SETUGE: SSECC = 5; break;
9925   case ISD::SETULT: Swap = true; // Fallthrough
9926   case ISD::SETUGT: SSECC = 6; break;
9927   case ISD::SETO:   SSECC = 7; break;
9928   case ISD::SETUEQ:
9929   case ISD::SETONE: SSECC = 8; break;
9930   }
9931   if (Swap)
9932     std::swap(Op0, Op1);
9933
9934   return SSECC;
9935 }
9936
9937 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9938 // ones, and then concatenate the result back.
9939 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9940   MVT VT = Op.getSimpleValueType();
9941
9942   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9943          "Unsupported value type for operation");
9944
9945   unsigned NumElems = VT.getVectorNumElements();
9946   SDLoc dl(Op);
9947   SDValue CC = Op.getOperand(2);
9948
9949   // Extract the LHS vectors
9950   SDValue LHS = Op.getOperand(0);
9951   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9952   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9953
9954   // Extract the RHS vectors
9955   SDValue RHS = Op.getOperand(1);
9956   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9957   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9958
9959   // Issue the operation on the smaller types and concatenate the result back
9960   MVT EltVT = VT.getVectorElementType();
9961   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9962   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9963                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9964                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9965 }
9966
9967 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9968   SDValue Op0 = Op.getOperand(0);
9969   SDValue Op1 = Op.getOperand(1);
9970   SDValue CC = Op.getOperand(2);
9971   MVT VT = Op.getSimpleValueType();
9972
9973   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9974          Op.getValueType().getScalarType() == MVT::i1 &&
9975          "Cannot set masked compare for this operation");
9976
9977   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9978   SDLoc dl(Op);
9979
9980   bool Unsigned = false;
9981   unsigned SSECC;
9982   switch (SetCCOpcode) {
9983   default: llvm_unreachable("Unexpected SETCC condition");
9984   case ISD::SETNE:  SSECC = 4; break;
9985   case ISD::SETEQ:  SSECC = 0; break;
9986   case ISD::SETUGT: Unsigned = true;
9987   case ISD::SETGT:  SSECC = 6; break; // NLE
9988   case ISD::SETULT: Unsigned = true;
9989   case ISD::SETLT:  SSECC = 1; break;
9990   case ISD::SETUGE: Unsigned = true;
9991   case ISD::SETGE:  SSECC = 5; break; // NLT
9992   case ISD::SETULE: Unsigned = true;
9993   case ISD::SETLE:  SSECC = 2; break;
9994   }
9995   unsigned  Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9996   return DAG.getNode(Opc, dl, VT, Op0, Op1,
9997                      DAG.getConstant(SSECC, MVT::i8));
9998
9999 }
10000
10001 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10002                            SelectionDAG &DAG) {
10003   SDValue Op0 = Op.getOperand(0);
10004   SDValue Op1 = Op.getOperand(1);
10005   SDValue CC = Op.getOperand(2);
10006   MVT VT = Op.getSimpleValueType();
10007   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10008   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10009   SDLoc dl(Op);
10010
10011   if (isFP) {
10012 #ifndef NDEBUG
10013     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10014     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10015 #endif
10016
10017     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10018     unsigned Opc = X86ISD::CMPP;
10019     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10020       assert(VT.getVectorNumElements() <= 16);
10021       Opc = X86ISD::CMPM;
10022     }
10023     // In the two special cases we can't handle, emit two comparisons.
10024     if (SSECC == 8) {
10025       unsigned CC0, CC1;
10026       unsigned CombineOpc;
10027       if (SetCCOpcode == ISD::SETUEQ) {
10028         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10029       } else {
10030         assert(SetCCOpcode == ISD::SETONE);
10031         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10032       }
10033
10034       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10035                                  DAG.getConstant(CC0, MVT::i8));
10036       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10037                                  DAG.getConstant(CC1, MVT::i8));
10038       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10039     }
10040     // Handle all other FP comparisons here.
10041     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10042                        DAG.getConstant(SSECC, MVT::i8));
10043   }
10044
10045   // Break 256-bit integer vector compare into smaller ones.
10046   if (VT.is256BitVector() && !Subtarget->hasInt256())
10047     return Lower256IntVSETCC(Op, DAG);
10048
10049   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10050   EVT OpVT = Op1.getValueType();
10051   if (Subtarget->hasAVX512()) {
10052     if (Op1.getValueType().is512BitVector() ||
10053         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10054       return LowerIntVSETCC_AVX512(Op, DAG);
10055
10056     // In AVX-512 architecture setcc returns mask with i1 elements,
10057     // But there is no compare instruction for i8 and i16 elements.
10058     // We are not talking about 512-bit operands in this case, these
10059     // types are illegal.
10060     if (MaskResult &&
10061         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10062          OpVT.getVectorElementType().getSizeInBits() >= 8))
10063       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10064                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10065   }
10066
10067   // We are handling one of the integer comparisons here.  Since SSE only has
10068   // GT and EQ comparisons for integer, swapping operands and multiple
10069   // operations may be required for some comparisons.
10070   unsigned Opc;
10071   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10072
10073   switch (SetCCOpcode) {
10074   default: llvm_unreachable("Unexpected SETCC condition");
10075   case ISD::SETNE:  Invert = true;
10076   case ISD::SETEQ:  Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
10077   case ISD::SETLT:  Swap = true;
10078   case ISD::SETGT:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
10079   case ISD::SETGE:  Swap = true;
10080   case ISD::SETLE:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10081                     Invert = true; break;
10082   case ISD::SETULT: Swap = true;
10083   case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10084                     FlipSigns = true; break;
10085   case ISD::SETUGE: Swap = true;
10086   case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
10087                     FlipSigns = true; Invert = true; break;
10088   }
10089
10090   // Special case: Use min/max operations for SETULE/SETUGE
10091   MVT VET = VT.getVectorElementType();
10092   bool hasMinMax =
10093        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10094     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10095
10096   if (hasMinMax) {
10097     switch (SetCCOpcode) {
10098     default: break;
10099     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10100     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10101     }
10102
10103     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10104   }
10105
10106   if (Swap)
10107     std::swap(Op0, Op1);
10108
10109   // Check that the operation in question is available (most are plain SSE2,
10110   // but PCMPGTQ and PCMPEQQ have different requirements).
10111   if (VT == MVT::v2i64) {
10112     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10113       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10114
10115       // First cast everything to the right type.
10116       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10117       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10118
10119       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10120       // bits of the inputs before performing those operations. The lower
10121       // compare is always unsigned.
10122       SDValue SB;
10123       if (FlipSigns) {
10124         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10125       } else {
10126         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10127         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10128         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10129                          Sign, Zero, Sign, Zero);
10130       }
10131       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10132       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10133
10134       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10135       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10136       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10137
10138       // Create masks for only the low parts/high parts of the 64 bit integers.
10139       static const int MaskHi[] = { 1, 1, 3, 3 };
10140       static const int MaskLo[] = { 0, 0, 2, 2 };
10141       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10142       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10143       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10144
10145       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10146       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10147
10148       if (Invert)
10149         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10150
10151       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10152     }
10153
10154     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10155       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10156       // pcmpeqd + pshufd + pand.
10157       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10158
10159       // First cast everything to the right type.
10160       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10161       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10162
10163       // Do the compare.
10164       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10165
10166       // Make sure the lower and upper halves are both all-ones.
10167       static const int Mask[] = { 1, 0, 3, 2 };
10168       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10169       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10170
10171       if (Invert)
10172         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10173
10174       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10175     }
10176   }
10177
10178   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10179   // bits of the inputs before performing those operations.
10180   if (FlipSigns) {
10181     EVT EltVT = VT.getVectorElementType();
10182     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10183     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10184     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10185   }
10186
10187   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10188
10189   // If the logical-not of the result is required, perform that now.
10190   if (Invert)
10191     Result = DAG.getNOT(dl, Result, VT);
10192
10193   if (MinMax)
10194     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10195
10196   return Result;
10197 }
10198
10199 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10200
10201   MVT VT = Op.getSimpleValueType();
10202
10203   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10204
10205   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10206          && "SetCC type must be 8-bit or 1-bit integer");
10207   SDValue Op0 = Op.getOperand(0);
10208   SDValue Op1 = Op.getOperand(1);
10209   SDLoc dl(Op);
10210   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10211
10212   // Optimize to BT if possible.
10213   // Lower (X & (1 << N)) == 0 to BT(X, N).
10214   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10215   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10216   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10217       Op1.getOpcode() == ISD::Constant &&
10218       cast<ConstantSDNode>(Op1)->isNullValue() &&
10219       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10220     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10221     if (NewSetCC.getNode())
10222       return NewSetCC;
10223   }
10224
10225   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10226   // these.
10227   if (Op1.getOpcode() == ISD::Constant &&
10228       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10229        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10230       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10231
10232     // If the input is a setcc, then reuse the input setcc or use a new one with
10233     // the inverted condition.
10234     if (Op0.getOpcode() == X86ISD::SETCC) {
10235       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10236       bool Invert = (CC == ISD::SETNE) ^
10237         cast<ConstantSDNode>(Op1)->isNullValue();
10238       if (!Invert) return Op0;
10239
10240       CCode = X86::GetOppositeBranchCondition(CCode);
10241       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10242                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
10243       if (VT == MVT::i1)
10244         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10245       return SetCC;
10246     }
10247   }
10248
10249   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10250   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10251   if (X86CC == X86::COND_INVALID)
10252     return SDValue();
10253
10254   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10255   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10256   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10257                       DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10258   if (VT == MVT::i1)
10259     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10260   return SetCC;
10261 }
10262
10263 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10264 static bool isX86LogicalCmp(SDValue Op) {
10265   unsigned Opc = Op.getNode()->getOpcode();
10266   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10267       Opc == X86ISD::SAHF)
10268     return true;
10269   if (Op.getResNo() == 1 &&
10270       (Opc == X86ISD::ADD ||
10271        Opc == X86ISD::SUB ||
10272        Opc == X86ISD::ADC ||
10273        Opc == X86ISD::SBB ||
10274        Opc == X86ISD::SMUL ||
10275        Opc == X86ISD::UMUL ||
10276        Opc == X86ISD::INC ||
10277        Opc == X86ISD::DEC ||
10278        Opc == X86ISD::OR ||
10279        Opc == X86ISD::XOR ||
10280        Opc == X86ISD::AND))
10281     return true;
10282
10283   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10284     return true;
10285
10286   return false;
10287 }
10288
10289 static bool isZero(SDValue V) {
10290   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10291   return C && C->isNullValue();
10292 }
10293
10294 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10295   if (V.getOpcode() != ISD::TRUNCATE)
10296     return false;
10297
10298   SDValue VOp0 = V.getOperand(0);
10299   unsigned InBits = VOp0.getValueSizeInBits();
10300   unsigned Bits = V.getValueSizeInBits();
10301   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10302 }
10303
10304 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10305   bool addTest = true;
10306   SDValue Cond  = Op.getOperand(0);
10307   SDValue Op1 = Op.getOperand(1);
10308   SDValue Op2 = Op.getOperand(2);
10309   SDLoc DL(Op);
10310   EVT VT = Op1.getValueType();
10311   SDValue CC;
10312
10313   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10314   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10315   // sequence later on.
10316   if (Cond.getOpcode() == ISD::SETCC &&
10317       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10318        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10319       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10320     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10321     int SSECC = translateX86FSETCC(
10322         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10323
10324     if (SSECC != 8) {
10325       if (Subtarget->hasAVX512()) {
10326         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10327                                   DAG.getConstant(SSECC, MVT::i8));
10328         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10329       }
10330       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10331                                 DAG.getConstant(SSECC, MVT::i8));
10332       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10333       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10334       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10335     }
10336   }
10337
10338   if (Cond.getOpcode() == ISD::SETCC) {
10339     SDValue NewCond = LowerSETCC(Cond, DAG);
10340     if (NewCond.getNode())
10341       Cond = NewCond;
10342   }
10343
10344   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10345   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10346   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10347   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10348   if (Cond.getOpcode() == X86ISD::SETCC &&
10349       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10350       isZero(Cond.getOperand(1).getOperand(1))) {
10351     SDValue Cmp = Cond.getOperand(1);
10352
10353     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10354
10355     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10356         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10357       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10358
10359       SDValue CmpOp0 = Cmp.getOperand(0);
10360       // Apply further optimizations for special cases
10361       // (select (x != 0), -1, 0) -> neg & sbb
10362       // (select (x == 0), 0, -1) -> neg & sbb
10363       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10364         if (YC->isNullValue() &&
10365             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10366           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10367           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10368                                     DAG.getConstant(0, CmpOp0.getValueType()),
10369                                     CmpOp0);
10370           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10371                                     DAG.getConstant(X86::COND_B, MVT::i8),
10372                                     SDValue(Neg.getNode(), 1));
10373           return Res;
10374         }
10375
10376       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10377                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10378       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10379
10380       SDValue Res =   // Res = 0 or -1.
10381         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10382                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10383
10384       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10385         Res = DAG.getNOT(DL, Res, Res.getValueType());
10386
10387       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10388       if (N2C == 0 || !N2C->isNullValue())
10389         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10390       return Res;
10391     }
10392   }
10393
10394   // Look past (and (setcc_carry (cmp ...)), 1).
10395   if (Cond.getOpcode() == ISD::AND &&
10396       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10397     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10398     if (C && C->getAPIntValue() == 1)
10399       Cond = Cond.getOperand(0);
10400   }
10401
10402   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10403   // setting operand in place of the X86ISD::SETCC.
10404   unsigned CondOpcode = Cond.getOpcode();
10405   if (CondOpcode == X86ISD::SETCC ||
10406       CondOpcode == X86ISD::SETCC_CARRY) {
10407     CC = Cond.getOperand(0);
10408
10409     SDValue Cmp = Cond.getOperand(1);
10410     unsigned Opc = Cmp.getOpcode();
10411     MVT VT = Op.getSimpleValueType();
10412
10413     bool IllegalFPCMov = false;
10414     if (VT.isFloatingPoint() && !VT.isVector() &&
10415         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10416       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10417
10418     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10419         Opc == X86ISD::BT) { // FIXME
10420       Cond = Cmp;
10421       addTest = false;
10422     }
10423   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10424              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10425              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10426               Cond.getOperand(0).getValueType() != MVT::i8)) {
10427     SDValue LHS = Cond.getOperand(0);
10428     SDValue RHS = Cond.getOperand(1);
10429     unsigned X86Opcode;
10430     unsigned X86Cond;
10431     SDVTList VTs;
10432     switch (CondOpcode) {
10433     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10434     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10435     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10436     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10437     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10438     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10439     default: llvm_unreachable("unexpected overflowing operator");
10440     }
10441     if (CondOpcode == ISD::UMULO)
10442       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10443                           MVT::i32);
10444     else
10445       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10446
10447     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10448
10449     if (CondOpcode == ISD::UMULO)
10450       Cond = X86Op.getValue(2);
10451     else
10452       Cond = X86Op.getValue(1);
10453
10454     CC = DAG.getConstant(X86Cond, MVT::i8);
10455     addTest = false;
10456   }
10457
10458   if (addTest) {
10459     // Look pass the truncate if the high bits are known zero.
10460     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10461         Cond = Cond.getOperand(0);
10462
10463     // We know the result of AND is compared against zero. Try to match
10464     // it to BT.
10465     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10466       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10467       if (NewSetCC.getNode()) {
10468         CC = NewSetCC.getOperand(0);
10469         Cond = NewSetCC.getOperand(1);
10470         addTest = false;
10471       }
10472     }
10473   }
10474
10475   if (addTest) {
10476     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10477     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10478   }
10479
10480   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10481   // a <  b ?  0 : -1 -> RES = setcc_carry
10482   // a >= b ? -1 :  0 -> RES = setcc_carry
10483   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10484   if (Cond.getOpcode() == X86ISD::SUB) {
10485     Cond = ConvertCmpIfNecessary(Cond, DAG);
10486     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10487
10488     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10489         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10490       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10491                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10492       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10493         return DAG.getNOT(DL, Res, Res.getValueType());
10494       return Res;
10495     }
10496   }
10497
10498   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10499   // widen the cmov and push the truncate through. This avoids introducing a new
10500   // branch during isel and doesn't add any extensions.
10501   if (Op.getValueType() == MVT::i8 &&
10502       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10503     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10504     if (T1.getValueType() == T2.getValueType() &&
10505         // Blacklist CopyFromReg to avoid partial register stalls.
10506         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10507       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10508       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10509       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10510     }
10511   }
10512
10513   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10514   // condition is true.
10515   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10516   SDValue Ops[] = { Op2, Op1, CC, Cond };
10517   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10518 }
10519
10520 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10521   MVT VT = Op->getSimpleValueType(0);
10522   SDValue In = Op->getOperand(0);
10523   MVT InVT = In.getSimpleValueType();
10524   SDLoc dl(Op);
10525
10526   unsigned int NumElts = VT.getVectorNumElements();
10527   if (NumElts != 8 && NumElts != 16)
10528     return SDValue();
10529
10530   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10531     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10532
10533   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10534   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10535
10536   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10537   Constant *C = ConstantInt::get(*DAG.getContext(),
10538     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10539
10540   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10541   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10542   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10543                           MachinePointerInfo::getConstantPool(),
10544                           false, false, false, Alignment);
10545   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10546   if (VT.is512BitVector())
10547     return Brcst;
10548   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10549 }
10550
10551 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10552                                 SelectionDAG &DAG) {
10553   MVT VT = Op->getSimpleValueType(0);
10554   SDValue In = Op->getOperand(0);
10555   MVT InVT = In.getSimpleValueType();
10556   SDLoc dl(Op);
10557
10558   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10559     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10560
10561   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10562       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10563       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10564     return SDValue();
10565
10566   if (Subtarget->hasInt256())
10567     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10568
10569   // Optimize vectors in AVX mode
10570   // Sign extend  v8i16 to v8i32 and
10571   //              v4i32 to v4i64
10572   //
10573   // Divide input vector into two parts
10574   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10575   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10576   // concat the vectors to original VT
10577
10578   unsigned NumElems = InVT.getVectorNumElements();
10579   SDValue Undef = DAG.getUNDEF(InVT);
10580
10581   SmallVector<int,8> ShufMask1(NumElems, -1);
10582   for (unsigned i = 0; i != NumElems/2; ++i)
10583     ShufMask1[i] = i;
10584
10585   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10586
10587   SmallVector<int,8> ShufMask2(NumElems, -1);
10588   for (unsigned i = 0; i != NumElems/2; ++i)
10589     ShufMask2[i] = i + NumElems/2;
10590
10591   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10592
10593   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10594                                 VT.getVectorNumElements()/2);
10595
10596   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10597   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10598
10599   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10600 }
10601
10602 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10603 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10604 // from the AND / OR.
10605 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10606   Opc = Op.getOpcode();
10607   if (Opc != ISD::OR && Opc != ISD::AND)
10608     return false;
10609   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10610           Op.getOperand(0).hasOneUse() &&
10611           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10612           Op.getOperand(1).hasOneUse());
10613 }
10614
10615 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10616 // 1 and that the SETCC node has a single use.
10617 static bool isXor1OfSetCC(SDValue Op) {
10618   if (Op.getOpcode() != ISD::XOR)
10619     return false;
10620   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10621   if (N1C && N1C->getAPIntValue() == 1) {
10622     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10623       Op.getOperand(0).hasOneUse();
10624   }
10625   return false;
10626 }
10627
10628 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10629   bool addTest = true;
10630   SDValue Chain = Op.getOperand(0);
10631   SDValue Cond  = Op.getOperand(1);
10632   SDValue Dest  = Op.getOperand(2);
10633   SDLoc dl(Op);
10634   SDValue CC;
10635   bool Inverted = false;
10636
10637   if (Cond.getOpcode() == ISD::SETCC) {
10638     // Check for setcc([su]{add,sub,mul}o == 0).
10639     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10640         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10641         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10642         Cond.getOperand(0).getResNo() == 1 &&
10643         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10644          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10645          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10646          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10647          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10648          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10649       Inverted = true;
10650       Cond = Cond.getOperand(0);
10651     } else {
10652       SDValue NewCond = LowerSETCC(Cond, DAG);
10653       if (NewCond.getNode())
10654         Cond = NewCond;
10655     }
10656   }
10657 #if 0
10658   // FIXME: LowerXALUO doesn't handle these!!
10659   else if (Cond.getOpcode() == X86ISD::ADD  ||
10660            Cond.getOpcode() == X86ISD::SUB  ||
10661            Cond.getOpcode() == X86ISD::SMUL ||
10662            Cond.getOpcode() == X86ISD::UMUL)
10663     Cond = LowerXALUO(Cond, DAG);
10664 #endif
10665
10666   // Look pass (and (setcc_carry (cmp ...)), 1).
10667   if (Cond.getOpcode() == ISD::AND &&
10668       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10669     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10670     if (C && C->getAPIntValue() == 1)
10671       Cond = Cond.getOperand(0);
10672   }
10673
10674   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10675   // setting operand in place of the X86ISD::SETCC.
10676   unsigned CondOpcode = Cond.getOpcode();
10677   if (CondOpcode == X86ISD::SETCC ||
10678       CondOpcode == X86ISD::SETCC_CARRY) {
10679     CC = Cond.getOperand(0);
10680
10681     SDValue Cmp = Cond.getOperand(1);
10682     unsigned Opc = Cmp.getOpcode();
10683     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10684     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10685       Cond = Cmp;
10686       addTest = false;
10687     } else {
10688       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10689       default: break;
10690       case X86::COND_O:
10691       case X86::COND_B:
10692         // These can only come from an arithmetic instruction with overflow,
10693         // e.g. SADDO, UADDO.
10694         Cond = Cond.getNode()->getOperand(1);
10695         addTest = false;
10696         break;
10697       }
10698     }
10699   }
10700   CondOpcode = Cond.getOpcode();
10701   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10702       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10703       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10704        Cond.getOperand(0).getValueType() != MVT::i8)) {
10705     SDValue LHS = Cond.getOperand(0);
10706     SDValue RHS = Cond.getOperand(1);
10707     unsigned X86Opcode;
10708     unsigned X86Cond;
10709     SDVTList VTs;
10710     switch (CondOpcode) {
10711     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10712     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10713     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10714     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10715     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10716     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10717     default: llvm_unreachable("unexpected overflowing operator");
10718     }
10719     if (Inverted)
10720       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10721     if (CondOpcode == ISD::UMULO)
10722       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10723                           MVT::i32);
10724     else
10725       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10726
10727     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10728
10729     if (CondOpcode == ISD::UMULO)
10730       Cond = X86Op.getValue(2);
10731     else
10732       Cond = X86Op.getValue(1);
10733
10734     CC = DAG.getConstant(X86Cond, MVT::i8);
10735     addTest = false;
10736   } else {
10737     unsigned CondOpc;
10738     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10739       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10740       if (CondOpc == ISD::OR) {
10741         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10742         // two branches instead of an explicit OR instruction with a
10743         // separate test.
10744         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10745             isX86LogicalCmp(Cmp)) {
10746           CC = Cond.getOperand(0).getOperand(0);
10747           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10748                               Chain, Dest, CC, Cmp);
10749           CC = Cond.getOperand(1).getOperand(0);
10750           Cond = Cmp;
10751           addTest = false;
10752         }
10753       } else { // ISD::AND
10754         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10755         // two branches instead of an explicit AND instruction with a
10756         // separate test. However, we only do this if this block doesn't
10757         // have a fall-through edge, because this requires an explicit
10758         // jmp when the condition is false.
10759         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10760             isX86LogicalCmp(Cmp) &&
10761             Op.getNode()->hasOneUse()) {
10762           X86::CondCode CCode =
10763             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10764           CCode = X86::GetOppositeBranchCondition(CCode);
10765           CC = DAG.getConstant(CCode, MVT::i8);
10766           SDNode *User = *Op.getNode()->use_begin();
10767           // Look for an unconditional branch following this conditional branch.
10768           // We need this because we need to reverse the successors in order
10769           // to implement FCMP_OEQ.
10770           if (User->getOpcode() == ISD::BR) {
10771             SDValue FalseBB = User->getOperand(1);
10772             SDNode *NewBR =
10773               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10774             assert(NewBR == User);
10775             (void)NewBR;
10776             Dest = FalseBB;
10777
10778             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10779                                 Chain, Dest, CC, Cmp);
10780             X86::CondCode CCode =
10781               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10782             CCode = X86::GetOppositeBranchCondition(CCode);
10783             CC = DAG.getConstant(CCode, MVT::i8);
10784             Cond = Cmp;
10785             addTest = false;
10786           }
10787         }
10788       }
10789     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10790       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10791       // It should be transformed during dag combiner except when the condition
10792       // is set by a arithmetics with overflow node.
10793       X86::CondCode CCode =
10794         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10795       CCode = X86::GetOppositeBranchCondition(CCode);
10796       CC = DAG.getConstant(CCode, MVT::i8);
10797       Cond = Cond.getOperand(0).getOperand(1);
10798       addTest = false;
10799     } else if (Cond.getOpcode() == ISD::SETCC &&
10800                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10801       // For FCMP_OEQ, we can emit
10802       // two branches instead of an explicit AND instruction with a
10803       // separate test. However, we only do this if this block doesn't
10804       // have a fall-through edge, because this requires an explicit
10805       // jmp when the condition is false.
10806       if (Op.getNode()->hasOneUse()) {
10807         SDNode *User = *Op.getNode()->use_begin();
10808         // Look for an unconditional branch following this conditional branch.
10809         // We need this because we need to reverse the successors in order
10810         // to implement FCMP_OEQ.
10811         if (User->getOpcode() == ISD::BR) {
10812           SDValue FalseBB = User->getOperand(1);
10813           SDNode *NewBR =
10814             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10815           assert(NewBR == User);
10816           (void)NewBR;
10817           Dest = FalseBB;
10818
10819           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10820                                     Cond.getOperand(0), Cond.getOperand(1));
10821           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10822           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10823           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10824                               Chain, Dest, CC, Cmp);
10825           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10826           Cond = Cmp;
10827           addTest = false;
10828         }
10829       }
10830     } else if (Cond.getOpcode() == ISD::SETCC &&
10831                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10832       // For FCMP_UNE, we can emit
10833       // two branches instead of an explicit AND instruction with a
10834       // separate test. However, we only do this if this block doesn't
10835       // have a fall-through edge, because this requires an explicit
10836       // jmp when the condition is false.
10837       if (Op.getNode()->hasOneUse()) {
10838         SDNode *User = *Op.getNode()->use_begin();
10839         // Look for an unconditional branch following this conditional branch.
10840         // We need this because we need to reverse the successors in order
10841         // to implement FCMP_UNE.
10842         if (User->getOpcode() == ISD::BR) {
10843           SDValue FalseBB = User->getOperand(1);
10844           SDNode *NewBR =
10845             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10846           assert(NewBR == User);
10847           (void)NewBR;
10848
10849           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10850                                     Cond.getOperand(0), Cond.getOperand(1));
10851           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10852           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10853           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10854                               Chain, Dest, CC, Cmp);
10855           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10856           Cond = Cmp;
10857           addTest = false;
10858           Dest = FalseBB;
10859         }
10860       }
10861     }
10862   }
10863
10864   if (addTest) {
10865     // Look pass the truncate if the high bits are known zero.
10866     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10867         Cond = Cond.getOperand(0);
10868
10869     // We know the result of AND is compared against zero. Try to match
10870     // it to BT.
10871     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10872       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10873       if (NewSetCC.getNode()) {
10874         CC = NewSetCC.getOperand(0);
10875         Cond = NewSetCC.getOperand(1);
10876         addTest = false;
10877       }
10878     }
10879   }
10880
10881   if (addTest) {
10882     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10883     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10884   }
10885   Cond = ConvertCmpIfNecessary(Cond, DAG);
10886   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10887                      Chain, Dest, CC, Cond);
10888 }
10889
10890 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10891 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10892 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10893 // that the guard pages used by the OS virtual memory manager are allocated in
10894 // correct sequence.
10895 SDValue
10896 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10897                                            SelectionDAG &DAG) const {
10898   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10899           getTargetMachine().Options.EnableSegmentedStacks) &&
10900          "This should be used only on Windows targets or when segmented stacks "
10901          "are being used");
10902   assert(!Subtarget->isTargetMacho() && "Not implemented");
10903   SDLoc dl(Op);
10904
10905   // Get the inputs.
10906   SDValue Chain = Op.getOperand(0);
10907   SDValue Size  = Op.getOperand(1);
10908   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10909   EVT VT = Op.getNode()->getValueType(0);
10910
10911   bool Is64Bit = Subtarget->is64Bit();
10912   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10913
10914   if (getTargetMachine().Options.EnableSegmentedStacks) {
10915     MachineFunction &MF = DAG.getMachineFunction();
10916     MachineRegisterInfo &MRI = MF.getRegInfo();
10917
10918     if (Is64Bit) {
10919       // The 64 bit implementation of segmented stacks needs to clobber both r10
10920       // r11. This makes it impossible to use it along with nested parameters.
10921       const Function *F = MF.getFunction();
10922
10923       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10924            I != E; ++I)
10925         if (I->hasNestAttr())
10926           report_fatal_error("Cannot use segmented stacks with functions that "
10927                              "have nested arguments.");
10928     }
10929
10930     const TargetRegisterClass *AddrRegClass =
10931       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10932     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10933     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10934     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10935                                 DAG.getRegister(Vreg, SPTy));
10936     SDValue Ops1[2] = { Value, Chain };
10937     return DAG.getMergeValues(Ops1, 2, dl);
10938   } else {
10939     SDValue Flag;
10940     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10941
10942     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10943     Flag = Chain.getValue(1);
10944     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10945
10946     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10947
10948     const X86RegisterInfo *RegInfo =
10949       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10950     unsigned SPReg = RegInfo->getStackRegister();
10951     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
10952     Chain = SP.getValue(1);
10953
10954     if (Align) {
10955       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10956                        DAG.getConstant(-(uint64_t)Align, VT));
10957       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
10958     }
10959
10960     SDValue Ops1[2] = { SP, Chain };
10961     return DAG.getMergeValues(Ops1, 2, dl);
10962   }
10963 }
10964
10965 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10966   MachineFunction &MF = DAG.getMachineFunction();
10967   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10968
10969   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10970   SDLoc DL(Op);
10971
10972   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10973     // vastart just stores the address of the VarArgsFrameIndex slot into the
10974     // memory location argument.
10975     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10976                                    getPointerTy());
10977     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10978                         MachinePointerInfo(SV), false, false, 0);
10979   }
10980
10981   // __va_list_tag:
10982   //   gp_offset         (0 - 6 * 8)
10983   //   fp_offset         (48 - 48 + 8 * 16)
10984   //   overflow_arg_area (point to parameters coming in memory).
10985   //   reg_save_area
10986   SmallVector<SDValue, 8> MemOps;
10987   SDValue FIN = Op.getOperand(1);
10988   // Store gp_offset
10989   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10990                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10991                                                MVT::i32),
10992                                FIN, MachinePointerInfo(SV), false, false, 0);
10993   MemOps.push_back(Store);
10994
10995   // Store fp_offset
10996   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10997                     FIN, DAG.getIntPtrConstant(4));
10998   Store = DAG.getStore(Op.getOperand(0), DL,
10999                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11000                                        MVT::i32),
11001                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11002   MemOps.push_back(Store);
11003
11004   // Store ptr to overflow_arg_area
11005   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11006                     FIN, DAG.getIntPtrConstant(4));
11007   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11008                                     getPointerTy());
11009   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11010                        MachinePointerInfo(SV, 8),
11011                        false, false, 0);
11012   MemOps.push_back(Store);
11013
11014   // Store ptr to reg_save_area.
11015   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11016                     FIN, DAG.getIntPtrConstant(8));
11017   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11018                                     getPointerTy());
11019   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11020                        MachinePointerInfo(SV, 16), false, false, 0);
11021   MemOps.push_back(Store);
11022   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11023                      &MemOps[0], MemOps.size());
11024 }
11025
11026 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11027   assert(Subtarget->is64Bit() &&
11028          "LowerVAARG only handles 64-bit va_arg!");
11029   assert((Subtarget->isTargetLinux() ||
11030           Subtarget->isTargetDarwin()) &&
11031           "Unhandled target in LowerVAARG");
11032   assert(Op.getNode()->getNumOperands() == 4);
11033   SDValue Chain = Op.getOperand(0);
11034   SDValue SrcPtr = Op.getOperand(1);
11035   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11036   unsigned Align = Op.getConstantOperandVal(3);
11037   SDLoc dl(Op);
11038
11039   EVT ArgVT = Op.getNode()->getValueType(0);
11040   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11041   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11042   uint8_t ArgMode;
11043
11044   // Decide which area this value should be read from.
11045   // TODO: Implement the AMD64 ABI in its entirety. This simple
11046   // selection mechanism works only for the basic types.
11047   if (ArgVT == MVT::f80) {
11048     llvm_unreachable("va_arg for f80 not yet implemented");
11049   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11050     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11051   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11052     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11053   } else {
11054     llvm_unreachable("Unhandled argument type in LowerVAARG");
11055   }
11056
11057   if (ArgMode == 2) {
11058     // Sanity Check: Make sure using fp_offset makes sense.
11059     assert(!getTargetMachine().Options.UseSoftFloat &&
11060            !(DAG.getMachineFunction()
11061                 .getFunction()->getAttributes()
11062                 .hasAttribute(AttributeSet::FunctionIndex,
11063                               Attribute::NoImplicitFloat)) &&
11064            Subtarget->hasSSE1());
11065   }
11066
11067   // Insert VAARG_64 node into the DAG
11068   // VAARG_64 returns two values: Variable Argument Address, Chain
11069   SmallVector<SDValue, 11> InstOps;
11070   InstOps.push_back(Chain);
11071   InstOps.push_back(SrcPtr);
11072   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11073   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11074   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11075   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11076   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11077                                           VTs, &InstOps[0], InstOps.size(),
11078                                           MVT::i64,
11079                                           MachinePointerInfo(SV),
11080                                           /*Align=*/0,
11081                                           /*Volatile=*/false,
11082                                           /*ReadMem=*/true,
11083                                           /*WriteMem=*/true);
11084   Chain = VAARG.getValue(1);
11085
11086   // Load the next argument and return it
11087   return DAG.getLoad(ArgVT, dl,
11088                      Chain,
11089                      VAARG,
11090                      MachinePointerInfo(),
11091                      false, false, false, 0);
11092 }
11093
11094 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11095                            SelectionDAG &DAG) {
11096   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11097   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11098   SDValue Chain = Op.getOperand(0);
11099   SDValue DstPtr = Op.getOperand(1);
11100   SDValue SrcPtr = Op.getOperand(2);
11101   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11102   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11103   SDLoc DL(Op);
11104
11105   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11106                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11107                        false,
11108                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11109 }
11110
11111 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11112 // amount is a constant. Takes immediate version of shift as input.
11113 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11114                                           SDValue SrcOp, uint64_t ShiftAmt,
11115                                           SelectionDAG &DAG) {
11116   MVT ElementType = VT.getVectorElementType();
11117
11118   // Check for ShiftAmt >= element width
11119   if (ShiftAmt >= ElementType.getSizeInBits()) {
11120     if (Opc == X86ISD::VSRAI)
11121       ShiftAmt = ElementType.getSizeInBits() - 1;
11122     else
11123       return DAG.getConstant(0, VT);
11124   }
11125
11126   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11127          && "Unknown target vector shift-by-constant node");
11128
11129   // Fold this packed vector shift into a build vector if SrcOp is a
11130   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11131   if (VT == SrcOp.getSimpleValueType() &&
11132       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11133     SmallVector<SDValue, 8> Elts;
11134     unsigned NumElts = SrcOp->getNumOperands();
11135     ConstantSDNode *ND;
11136
11137     switch(Opc) {
11138     default: llvm_unreachable(0);
11139     case X86ISD::VSHLI:
11140       for (unsigned i=0; i!=NumElts; ++i) {
11141         SDValue CurrentOp = SrcOp->getOperand(i);
11142         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11143           Elts.push_back(CurrentOp);
11144           continue;
11145         }
11146         ND = cast<ConstantSDNode>(CurrentOp);
11147         const APInt &C = ND->getAPIntValue();
11148         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11149       }
11150       break;
11151     case X86ISD::VSRLI:
11152       for (unsigned i=0; i!=NumElts; ++i) {
11153         SDValue CurrentOp = SrcOp->getOperand(i);
11154         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11155           Elts.push_back(CurrentOp);
11156           continue;
11157         }
11158         ND = cast<ConstantSDNode>(CurrentOp);
11159         const APInt &C = ND->getAPIntValue();
11160         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11161       }
11162       break;
11163     case X86ISD::VSRAI:
11164       for (unsigned i=0; i!=NumElts; ++i) {
11165         SDValue CurrentOp = SrcOp->getOperand(i);
11166         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11167           Elts.push_back(CurrentOp);
11168           continue;
11169         }
11170         ND = cast<ConstantSDNode>(CurrentOp);
11171         const APInt &C = ND->getAPIntValue();
11172         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11173       }
11174       break;
11175     }
11176
11177     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11178   }
11179
11180   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11181 }
11182
11183 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11184 // may or may not be a constant. Takes immediate version of shift as input.
11185 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11186                                    SDValue SrcOp, SDValue ShAmt,
11187                                    SelectionDAG &DAG) {
11188   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11189
11190   // Catch shift-by-constant.
11191   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11192     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11193                                       CShAmt->getZExtValue(), DAG);
11194
11195   // Change opcode to non-immediate version
11196   switch (Opc) {
11197     default: llvm_unreachable("Unknown target vector shift node");
11198     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11199     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11200     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11201   }
11202
11203   // Need to build a vector containing shift amount
11204   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11205   SDValue ShOps[4];
11206   ShOps[0] = ShAmt;
11207   ShOps[1] = DAG.getConstant(0, MVT::i32);
11208   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11209   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11210
11211   // The return type has to be a 128-bit type with the same element
11212   // type as the input type.
11213   MVT EltVT = VT.getVectorElementType();
11214   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11215
11216   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11217   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11218 }
11219
11220 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11221   SDLoc dl(Op);
11222   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11223   switch (IntNo) {
11224   default: return SDValue();    // Don't custom lower most intrinsics.
11225   // Comparison intrinsics.
11226   case Intrinsic::x86_sse_comieq_ss:
11227   case Intrinsic::x86_sse_comilt_ss:
11228   case Intrinsic::x86_sse_comile_ss:
11229   case Intrinsic::x86_sse_comigt_ss:
11230   case Intrinsic::x86_sse_comige_ss:
11231   case Intrinsic::x86_sse_comineq_ss:
11232   case Intrinsic::x86_sse_ucomieq_ss:
11233   case Intrinsic::x86_sse_ucomilt_ss:
11234   case Intrinsic::x86_sse_ucomile_ss:
11235   case Intrinsic::x86_sse_ucomigt_ss:
11236   case Intrinsic::x86_sse_ucomige_ss:
11237   case Intrinsic::x86_sse_ucomineq_ss:
11238   case Intrinsic::x86_sse2_comieq_sd:
11239   case Intrinsic::x86_sse2_comilt_sd:
11240   case Intrinsic::x86_sse2_comile_sd:
11241   case Intrinsic::x86_sse2_comigt_sd:
11242   case Intrinsic::x86_sse2_comige_sd:
11243   case Intrinsic::x86_sse2_comineq_sd:
11244   case Intrinsic::x86_sse2_ucomieq_sd:
11245   case Intrinsic::x86_sse2_ucomilt_sd:
11246   case Intrinsic::x86_sse2_ucomile_sd:
11247   case Intrinsic::x86_sse2_ucomigt_sd:
11248   case Intrinsic::x86_sse2_ucomige_sd:
11249   case Intrinsic::x86_sse2_ucomineq_sd: {
11250     unsigned Opc;
11251     ISD::CondCode CC;
11252     switch (IntNo) {
11253     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11254     case Intrinsic::x86_sse_comieq_ss:
11255     case Intrinsic::x86_sse2_comieq_sd:
11256       Opc = X86ISD::COMI;
11257       CC = ISD::SETEQ;
11258       break;
11259     case Intrinsic::x86_sse_comilt_ss:
11260     case Intrinsic::x86_sse2_comilt_sd:
11261       Opc = X86ISD::COMI;
11262       CC = ISD::SETLT;
11263       break;
11264     case Intrinsic::x86_sse_comile_ss:
11265     case Intrinsic::x86_sse2_comile_sd:
11266       Opc = X86ISD::COMI;
11267       CC = ISD::SETLE;
11268       break;
11269     case Intrinsic::x86_sse_comigt_ss:
11270     case Intrinsic::x86_sse2_comigt_sd:
11271       Opc = X86ISD::COMI;
11272       CC = ISD::SETGT;
11273       break;
11274     case Intrinsic::x86_sse_comige_ss:
11275     case Intrinsic::x86_sse2_comige_sd:
11276       Opc = X86ISD::COMI;
11277       CC = ISD::SETGE;
11278       break;
11279     case Intrinsic::x86_sse_comineq_ss:
11280     case Intrinsic::x86_sse2_comineq_sd:
11281       Opc = X86ISD::COMI;
11282       CC = ISD::SETNE;
11283       break;
11284     case Intrinsic::x86_sse_ucomieq_ss:
11285     case Intrinsic::x86_sse2_ucomieq_sd:
11286       Opc = X86ISD::UCOMI;
11287       CC = ISD::SETEQ;
11288       break;
11289     case Intrinsic::x86_sse_ucomilt_ss:
11290     case Intrinsic::x86_sse2_ucomilt_sd:
11291       Opc = X86ISD::UCOMI;
11292       CC = ISD::SETLT;
11293       break;
11294     case Intrinsic::x86_sse_ucomile_ss:
11295     case Intrinsic::x86_sse2_ucomile_sd:
11296       Opc = X86ISD::UCOMI;
11297       CC = ISD::SETLE;
11298       break;
11299     case Intrinsic::x86_sse_ucomigt_ss:
11300     case Intrinsic::x86_sse2_ucomigt_sd:
11301       Opc = X86ISD::UCOMI;
11302       CC = ISD::SETGT;
11303       break;
11304     case Intrinsic::x86_sse_ucomige_ss:
11305     case Intrinsic::x86_sse2_ucomige_sd:
11306       Opc = X86ISD::UCOMI;
11307       CC = ISD::SETGE;
11308       break;
11309     case Intrinsic::x86_sse_ucomineq_ss:
11310     case Intrinsic::x86_sse2_ucomineq_sd:
11311       Opc = X86ISD::UCOMI;
11312       CC = ISD::SETNE;
11313       break;
11314     }
11315
11316     SDValue LHS = Op.getOperand(1);
11317     SDValue RHS = Op.getOperand(2);
11318     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11319     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11320     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11321     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11322                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11323     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11324   }
11325
11326   // Arithmetic intrinsics.
11327   case Intrinsic::x86_sse2_pmulu_dq:
11328   case Intrinsic::x86_avx2_pmulu_dq:
11329     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11330                        Op.getOperand(1), Op.getOperand(2));
11331
11332   // SSE2/AVX2 sub with unsigned saturation intrinsics
11333   case Intrinsic::x86_sse2_psubus_b:
11334   case Intrinsic::x86_sse2_psubus_w:
11335   case Intrinsic::x86_avx2_psubus_b:
11336   case Intrinsic::x86_avx2_psubus_w:
11337     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11338                        Op.getOperand(1), Op.getOperand(2));
11339
11340   // SSE3/AVX horizontal add/sub intrinsics
11341   case Intrinsic::x86_sse3_hadd_ps:
11342   case Intrinsic::x86_sse3_hadd_pd:
11343   case Intrinsic::x86_avx_hadd_ps_256:
11344   case Intrinsic::x86_avx_hadd_pd_256:
11345   case Intrinsic::x86_sse3_hsub_ps:
11346   case Intrinsic::x86_sse3_hsub_pd:
11347   case Intrinsic::x86_avx_hsub_ps_256:
11348   case Intrinsic::x86_avx_hsub_pd_256:
11349   case Intrinsic::x86_ssse3_phadd_w_128:
11350   case Intrinsic::x86_ssse3_phadd_d_128:
11351   case Intrinsic::x86_avx2_phadd_w:
11352   case Intrinsic::x86_avx2_phadd_d:
11353   case Intrinsic::x86_ssse3_phsub_w_128:
11354   case Intrinsic::x86_ssse3_phsub_d_128:
11355   case Intrinsic::x86_avx2_phsub_w:
11356   case Intrinsic::x86_avx2_phsub_d: {
11357     unsigned Opcode;
11358     switch (IntNo) {
11359     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11360     case Intrinsic::x86_sse3_hadd_ps:
11361     case Intrinsic::x86_sse3_hadd_pd:
11362     case Intrinsic::x86_avx_hadd_ps_256:
11363     case Intrinsic::x86_avx_hadd_pd_256:
11364       Opcode = X86ISD::FHADD;
11365       break;
11366     case Intrinsic::x86_sse3_hsub_ps:
11367     case Intrinsic::x86_sse3_hsub_pd:
11368     case Intrinsic::x86_avx_hsub_ps_256:
11369     case Intrinsic::x86_avx_hsub_pd_256:
11370       Opcode = X86ISD::FHSUB;
11371       break;
11372     case Intrinsic::x86_ssse3_phadd_w_128:
11373     case Intrinsic::x86_ssse3_phadd_d_128:
11374     case Intrinsic::x86_avx2_phadd_w:
11375     case Intrinsic::x86_avx2_phadd_d:
11376       Opcode = X86ISD::HADD;
11377       break;
11378     case Intrinsic::x86_ssse3_phsub_w_128:
11379     case Intrinsic::x86_ssse3_phsub_d_128:
11380     case Intrinsic::x86_avx2_phsub_w:
11381     case Intrinsic::x86_avx2_phsub_d:
11382       Opcode = X86ISD::HSUB;
11383       break;
11384     }
11385     return DAG.getNode(Opcode, dl, Op.getValueType(),
11386                        Op.getOperand(1), Op.getOperand(2));
11387   }
11388
11389   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11390   case Intrinsic::x86_sse2_pmaxu_b:
11391   case Intrinsic::x86_sse41_pmaxuw:
11392   case Intrinsic::x86_sse41_pmaxud:
11393   case Intrinsic::x86_avx2_pmaxu_b:
11394   case Intrinsic::x86_avx2_pmaxu_w:
11395   case Intrinsic::x86_avx2_pmaxu_d:
11396   case Intrinsic::x86_sse2_pminu_b:
11397   case Intrinsic::x86_sse41_pminuw:
11398   case Intrinsic::x86_sse41_pminud:
11399   case Intrinsic::x86_avx2_pminu_b:
11400   case Intrinsic::x86_avx2_pminu_w:
11401   case Intrinsic::x86_avx2_pminu_d:
11402   case Intrinsic::x86_sse41_pmaxsb:
11403   case Intrinsic::x86_sse2_pmaxs_w:
11404   case Intrinsic::x86_sse41_pmaxsd:
11405   case Intrinsic::x86_avx2_pmaxs_b:
11406   case Intrinsic::x86_avx2_pmaxs_w:
11407   case Intrinsic::x86_avx2_pmaxs_d:
11408   case Intrinsic::x86_sse41_pminsb:
11409   case Intrinsic::x86_sse2_pmins_w:
11410   case Intrinsic::x86_sse41_pminsd:
11411   case Intrinsic::x86_avx2_pmins_b:
11412   case Intrinsic::x86_avx2_pmins_w:
11413   case Intrinsic::x86_avx2_pmins_d: {
11414     unsigned Opcode;
11415     switch (IntNo) {
11416     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11417     case Intrinsic::x86_sse2_pmaxu_b:
11418     case Intrinsic::x86_sse41_pmaxuw:
11419     case Intrinsic::x86_sse41_pmaxud:
11420     case Intrinsic::x86_avx2_pmaxu_b:
11421     case Intrinsic::x86_avx2_pmaxu_w:
11422     case Intrinsic::x86_avx2_pmaxu_d:
11423       Opcode = X86ISD::UMAX;
11424       break;
11425     case Intrinsic::x86_sse2_pminu_b:
11426     case Intrinsic::x86_sse41_pminuw:
11427     case Intrinsic::x86_sse41_pminud:
11428     case Intrinsic::x86_avx2_pminu_b:
11429     case Intrinsic::x86_avx2_pminu_w:
11430     case Intrinsic::x86_avx2_pminu_d:
11431       Opcode = X86ISD::UMIN;
11432       break;
11433     case Intrinsic::x86_sse41_pmaxsb:
11434     case Intrinsic::x86_sse2_pmaxs_w:
11435     case Intrinsic::x86_sse41_pmaxsd:
11436     case Intrinsic::x86_avx2_pmaxs_b:
11437     case Intrinsic::x86_avx2_pmaxs_w:
11438     case Intrinsic::x86_avx2_pmaxs_d:
11439       Opcode = X86ISD::SMAX;
11440       break;
11441     case Intrinsic::x86_sse41_pminsb:
11442     case Intrinsic::x86_sse2_pmins_w:
11443     case Intrinsic::x86_sse41_pminsd:
11444     case Intrinsic::x86_avx2_pmins_b:
11445     case Intrinsic::x86_avx2_pmins_w:
11446     case Intrinsic::x86_avx2_pmins_d:
11447       Opcode = X86ISD::SMIN;
11448       break;
11449     }
11450     return DAG.getNode(Opcode, dl, Op.getValueType(),
11451                        Op.getOperand(1), Op.getOperand(2));
11452   }
11453
11454   // SSE/SSE2/AVX floating point max/min intrinsics.
11455   case Intrinsic::x86_sse_max_ps:
11456   case Intrinsic::x86_sse2_max_pd:
11457   case Intrinsic::x86_avx_max_ps_256:
11458   case Intrinsic::x86_avx_max_pd_256:
11459   case Intrinsic::x86_sse_min_ps:
11460   case Intrinsic::x86_sse2_min_pd:
11461   case Intrinsic::x86_avx_min_ps_256:
11462   case Intrinsic::x86_avx_min_pd_256: {
11463     unsigned Opcode;
11464     switch (IntNo) {
11465     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11466     case Intrinsic::x86_sse_max_ps:
11467     case Intrinsic::x86_sse2_max_pd:
11468     case Intrinsic::x86_avx_max_ps_256:
11469     case Intrinsic::x86_avx_max_pd_256:
11470       Opcode = X86ISD::FMAX;
11471       break;
11472     case Intrinsic::x86_sse_min_ps:
11473     case Intrinsic::x86_sse2_min_pd:
11474     case Intrinsic::x86_avx_min_ps_256:
11475     case Intrinsic::x86_avx_min_pd_256:
11476       Opcode = X86ISD::FMIN;
11477       break;
11478     }
11479     return DAG.getNode(Opcode, dl, Op.getValueType(),
11480                        Op.getOperand(1), Op.getOperand(2));
11481   }
11482
11483   // AVX2 variable shift intrinsics
11484   case Intrinsic::x86_avx2_psllv_d:
11485   case Intrinsic::x86_avx2_psllv_q:
11486   case Intrinsic::x86_avx2_psllv_d_256:
11487   case Intrinsic::x86_avx2_psllv_q_256:
11488   case Intrinsic::x86_avx2_psrlv_d:
11489   case Intrinsic::x86_avx2_psrlv_q:
11490   case Intrinsic::x86_avx2_psrlv_d_256:
11491   case Intrinsic::x86_avx2_psrlv_q_256:
11492   case Intrinsic::x86_avx2_psrav_d:
11493   case Intrinsic::x86_avx2_psrav_d_256: {
11494     unsigned Opcode;
11495     switch (IntNo) {
11496     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11497     case Intrinsic::x86_avx2_psllv_d:
11498     case Intrinsic::x86_avx2_psllv_q:
11499     case Intrinsic::x86_avx2_psllv_d_256:
11500     case Intrinsic::x86_avx2_psllv_q_256:
11501       Opcode = ISD::SHL;
11502       break;
11503     case Intrinsic::x86_avx2_psrlv_d:
11504     case Intrinsic::x86_avx2_psrlv_q:
11505     case Intrinsic::x86_avx2_psrlv_d_256:
11506     case Intrinsic::x86_avx2_psrlv_q_256:
11507       Opcode = ISD::SRL;
11508       break;
11509     case Intrinsic::x86_avx2_psrav_d:
11510     case Intrinsic::x86_avx2_psrav_d_256:
11511       Opcode = ISD::SRA;
11512       break;
11513     }
11514     return DAG.getNode(Opcode, dl, Op.getValueType(),
11515                        Op.getOperand(1), Op.getOperand(2));
11516   }
11517
11518   case Intrinsic::x86_ssse3_pshuf_b_128:
11519   case Intrinsic::x86_avx2_pshuf_b:
11520     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11521                        Op.getOperand(1), Op.getOperand(2));
11522
11523   case Intrinsic::x86_ssse3_psign_b_128:
11524   case Intrinsic::x86_ssse3_psign_w_128:
11525   case Intrinsic::x86_ssse3_psign_d_128:
11526   case Intrinsic::x86_avx2_psign_b:
11527   case Intrinsic::x86_avx2_psign_w:
11528   case Intrinsic::x86_avx2_psign_d:
11529     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11530                        Op.getOperand(1), Op.getOperand(2));
11531
11532   case Intrinsic::x86_sse41_insertps:
11533     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11534                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11535
11536   case Intrinsic::x86_avx_vperm2f128_ps_256:
11537   case Intrinsic::x86_avx_vperm2f128_pd_256:
11538   case Intrinsic::x86_avx_vperm2f128_si_256:
11539   case Intrinsic::x86_avx2_vperm2i128:
11540     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11541                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11542
11543   case Intrinsic::x86_avx2_permd:
11544   case Intrinsic::x86_avx2_permps:
11545     // Operands intentionally swapped. Mask is last operand to intrinsic,
11546     // but second operand for node/instruction.
11547     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11548                        Op.getOperand(2), Op.getOperand(1));
11549
11550   case Intrinsic::x86_sse_sqrt_ps:
11551   case Intrinsic::x86_sse2_sqrt_pd:
11552   case Intrinsic::x86_avx_sqrt_ps_256:
11553   case Intrinsic::x86_avx_sqrt_pd_256:
11554     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11555
11556   // ptest and testp intrinsics. The intrinsic these come from are designed to
11557   // return an integer value, not just an instruction so lower it to the ptest
11558   // or testp pattern and a setcc for the result.
11559   case Intrinsic::x86_sse41_ptestz:
11560   case Intrinsic::x86_sse41_ptestc:
11561   case Intrinsic::x86_sse41_ptestnzc:
11562   case Intrinsic::x86_avx_ptestz_256:
11563   case Intrinsic::x86_avx_ptestc_256:
11564   case Intrinsic::x86_avx_ptestnzc_256:
11565   case Intrinsic::x86_avx_vtestz_ps:
11566   case Intrinsic::x86_avx_vtestc_ps:
11567   case Intrinsic::x86_avx_vtestnzc_ps:
11568   case Intrinsic::x86_avx_vtestz_pd:
11569   case Intrinsic::x86_avx_vtestc_pd:
11570   case Intrinsic::x86_avx_vtestnzc_pd:
11571   case Intrinsic::x86_avx_vtestz_ps_256:
11572   case Intrinsic::x86_avx_vtestc_ps_256:
11573   case Intrinsic::x86_avx_vtestnzc_ps_256:
11574   case Intrinsic::x86_avx_vtestz_pd_256:
11575   case Intrinsic::x86_avx_vtestc_pd_256:
11576   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11577     bool IsTestPacked = false;
11578     unsigned X86CC;
11579     switch (IntNo) {
11580     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11581     case Intrinsic::x86_avx_vtestz_ps:
11582     case Intrinsic::x86_avx_vtestz_pd:
11583     case Intrinsic::x86_avx_vtestz_ps_256:
11584     case Intrinsic::x86_avx_vtestz_pd_256:
11585       IsTestPacked = true; // Fallthrough
11586     case Intrinsic::x86_sse41_ptestz:
11587     case Intrinsic::x86_avx_ptestz_256:
11588       // ZF = 1
11589       X86CC = X86::COND_E;
11590       break;
11591     case Intrinsic::x86_avx_vtestc_ps:
11592     case Intrinsic::x86_avx_vtestc_pd:
11593     case Intrinsic::x86_avx_vtestc_ps_256:
11594     case Intrinsic::x86_avx_vtestc_pd_256:
11595       IsTestPacked = true; // Fallthrough
11596     case Intrinsic::x86_sse41_ptestc:
11597     case Intrinsic::x86_avx_ptestc_256:
11598       // CF = 1
11599       X86CC = X86::COND_B;
11600       break;
11601     case Intrinsic::x86_avx_vtestnzc_ps:
11602     case Intrinsic::x86_avx_vtestnzc_pd:
11603     case Intrinsic::x86_avx_vtestnzc_ps_256:
11604     case Intrinsic::x86_avx_vtestnzc_pd_256:
11605       IsTestPacked = true; // Fallthrough
11606     case Intrinsic::x86_sse41_ptestnzc:
11607     case Intrinsic::x86_avx_ptestnzc_256:
11608       // ZF and CF = 0
11609       X86CC = X86::COND_A;
11610       break;
11611     }
11612
11613     SDValue LHS = Op.getOperand(1);
11614     SDValue RHS = Op.getOperand(2);
11615     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11616     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11617     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11618     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11619     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11620   }
11621   case Intrinsic::x86_avx512_kortestz_w:
11622   case Intrinsic::x86_avx512_kortestc_w: {
11623     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11624     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11625     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11626     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11627     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11628     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11629     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11630   }
11631
11632   // SSE/AVX shift intrinsics
11633   case Intrinsic::x86_sse2_psll_w:
11634   case Intrinsic::x86_sse2_psll_d:
11635   case Intrinsic::x86_sse2_psll_q:
11636   case Intrinsic::x86_avx2_psll_w:
11637   case Intrinsic::x86_avx2_psll_d:
11638   case Intrinsic::x86_avx2_psll_q:
11639   case Intrinsic::x86_sse2_psrl_w:
11640   case Intrinsic::x86_sse2_psrl_d:
11641   case Intrinsic::x86_sse2_psrl_q:
11642   case Intrinsic::x86_avx2_psrl_w:
11643   case Intrinsic::x86_avx2_psrl_d:
11644   case Intrinsic::x86_avx2_psrl_q:
11645   case Intrinsic::x86_sse2_psra_w:
11646   case Intrinsic::x86_sse2_psra_d:
11647   case Intrinsic::x86_avx2_psra_w:
11648   case Intrinsic::x86_avx2_psra_d: {
11649     unsigned Opcode;
11650     switch (IntNo) {
11651     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11652     case Intrinsic::x86_sse2_psll_w:
11653     case Intrinsic::x86_sse2_psll_d:
11654     case Intrinsic::x86_sse2_psll_q:
11655     case Intrinsic::x86_avx2_psll_w:
11656     case Intrinsic::x86_avx2_psll_d:
11657     case Intrinsic::x86_avx2_psll_q:
11658       Opcode = X86ISD::VSHL;
11659       break;
11660     case Intrinsic::x86_sse2_psrl_w:
11661     case Intrinsic::x86_sse2_psrl_d:
11662     case Intrinsic::x86_sse2_psrl_q:
11663     case Intrinsic::x86_avx2_psrl_w:
11664     case Intrinsic::x86_avx2_psrl_d:
11665     case Intrinsic::x86_avx2_psrl_q:
11666       Opcode = X86ISD::VSRL;
11667       break;
11668     case Intrinsic::x86_sse2_psra_w:
11669     case Intrinsic::x86_sse2_psra_d:
11670     case Intrinsic::x86_avx2_psra_w:
11671     case Intrinsic::x86_avx2_psra_d:
11672       Opcode = X86ISD::VSRA;
11673       break;
11674     }
11675     return DAG.getNode(Opcode, dl, Op.getValueType(),
11676                        Op.getOperand(1), Op.getOperand(2));
11677   }
11678
11679   // SSE/AVX immediate shift intrinsics
11680   case Intrinsic::x86_sse2_pslli_w:
11681   case Intrinsic::x86_sse2_pslli_d:
11682   case Intrinsic::x86_sse2_pslli_q:
11683   case Intrinsic::x86_avx2_pslli_w:
11684   case Intrinsic::x86_avx2_pslli_d:
11685   case Intrinsic::x86_avx2_pslli_q:
11686   case Intrinsic::x86_sse2_psrli_w:
11687   case Intrinsic::x86_sse2_psrli_d:
11688   case Intrinsic::x86_sse2_psrli_q:
11689   case Intrinsic::x86_avx2_psrli_w:
11690   case Intrinsic::x86_avx2_psrli_d:
11691   case Intrinsic::x86_avx2_psrli_q:
11692   case Intrinsic::x86_sse2_psrai_w:
11693   case Intrinsic::x86_sse2_psrai_d:
11694   case Intrinsic::x86_avx2_psrai_w:
11695   case Intrinsic::x86_avx2_psrai_d: {
11696     unsigned Opcode;
11697     switch (IntNo) {
11698     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11699     case Intrinsic::x86_sse2_pslli_w:
11700     case Intrinsic::x86_sse2_pslli_d:
11701     case Intrinsic::x86_sse2_pslli_q:
11702     case Intrinsic::x86_avx2_pslli_w:
11703     case Intrinsic::x86_avx2_pslli_d:
11704     case Intrinsic::x86_avx2_pslli_q:
11705       Opcode = X86ISD::VSHLI;
11706       break;
11707     case Intrinsic::x86_sse2_psrli_w:
11708     case Intrinsic::x86_sse2_psrli_d:
11709     case Intrinsic::x86_sse2_psrli_q:
11710     case Intrinsic::x86_avx2_psrli_w:
11711     case Intrinsic::x86_avx2_psrli_d:
11712     case Intrinsic::x86_avx2_psrli_q:
11713       Opcode = X86ISD::VSRLI;
11714       break;
11715     case Intrinsic::x86_sse2_psrai_w:
11716     case Intrinsic::x86_sse2_psrai_d:
11717     case Intrinsic::x86_avx2_psrai_w:
11718     case Intrinsic::x86_avx2_psrai_d:
11719       Opcode = X86ISD::VSRAI;
11720       break;
11721     }
11722     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11723                                Op.getOperand(1), Op.getOperand(2), DAG);
11724   }
11725
11726   case Intrinsic::x86_sse42_pcmpistria128:
11727   case Intrinsic::x86_sse42_pcmpestria128:
11728   case Intrinsic::x86_sse42_pcmpistric128:
11729   case Intrinsic::x86_sse42_pcmpestric128:
11730   case Intrinsic::x86_sse42_pcmpistrio128:
11731   case Intrinsic::x86_sse42_pcmpestrio128:
11732   case Intrinsic::x86_sse42_pcmpistris128:
11733   case Intrinsic::x86_sse42_pcmpestris128:
11734   case Intrinsic::x86_sse42_pcmpistriz128:
11735   case Intrinsic::x86_sse42_pcmpestriz128: {
11736     unsigned Opcode;
11737     unsigned X86CC;
11738     switch (IntNo) {
11739     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11740     case Intrinsic::x86_sse42_pcmpistria128:
11741       Opcode = X86ISD::PCMPISTRI;
11742       X86CC = X86::COND_A;
11743       break;
11744     case Intrinsic::x86_sse42_pcmpestria128:
11745       Opcode = X86ISD::PCMPESTRI;
11746       X86CC = X86::COND_A;
11747       break;
11748     case Intrinsic::x86_sse42_pcmpistric128:
11749       Opcode = X86ISD::PCMPISTRI;
11750       X86CC = X86::COND_B;
11751       break;
11752     case Intrinsic::x86_sse42_pcmpestric128:
11753       Opcode = X86ISD::PCMPESTRI;
11754       X86CC = X86::COND_B;
11755       break;
11756     case Intrinsic::x86_sse42_pcmpistrio128:
11757       Opcode = X86ISD::PCMPISTRI;
11758       X86CC = X86::COND_O;
11759       break;
11760     case Intrinsic::x86_sse42_pcmpestrio128:
11761       Opcode = X86ISD::PCMPESTRI;
11762       X86CC = X86::COND_O;
11763       break;
11764     case Intrinsic::x86_sse42_pcmpistris128:
11765       Opcode = X86ISD::PCMPISTRI;
11766       X86CC = X86::COND_S;
11767       break;
11768     case Intrinsic::x86_sse42_pcmpestris128:
11769       Opcode = X86ISD::PCMPESTRI;
11770       X86CC = X86::COND_S;
11771       break;
11772     case Intrinsic::x86_sse42_pcmpistriz128:
11773       Opcode = X86ISD::PCMPISTRI;
11774       X86CC = X86::COND_E;
11775       break;
11776     case Intrinsic::x86_sse42_pcmpestriz128:
11777       Opcode = X86ISD::PCMPESTRI;
11778       X86CC = X86::COND_E;
11779       break;
11780     }
11781     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11782     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11783     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11784     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11785                                 DAG.getConstant(X86CC, MVT::i8),
11786                                 SDValue(PCMP.getNode(), 1));
11787     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11788   }
11789
11790   case Intrinsic::x86_sse42_pcmpistri128:
11791   case Intrinsic::x86_sse42_pcmpestri128: {
11792     unsigned Opcode;
11793     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11794       Opcode = X86ISD::PCMPISTRI;
11795     else
11796       Opcode = X86ISD::PCMPESTRI;
11797
11798     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11799     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11800     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11801   }
11802   case Intrinsic::x86_fma_vfmadd_ps:
11803   case Intrinsic::x86_fma_vfmadd_pd:
11804   case Intrinsic::x86_fma_vfmsub_ps:
11805   case Intrinsic::x86_fma_vfmsub_pd:
11806   case Intrinsic::x86_fma_vfnmadd_ps:
11807   case Intrinsic::x86_fma_vfnmadd_pd:
11808   case Intrinsic::x86_fma_vfnmsub_ps:
11809   case Intrinsic::x86_fma_vfnmsub_pd:
11810   case Intrinsic::x86_fma_vfmaddsub_ps:
11811   case Intrinsic::x86_fma_vfmaddsub_pd:
11812   case Intrinsic::x86_fma_vfmsubadd_ps:
11813   case Intrinsic::x86_fma_vfmsubadd_pd:
11814   case Intrinsic::x86_fma_vfmadd_ps_256:
11815   case Intrinsic::x86_fma_vfmadd_pd_256:
11816   case Intrinsic::x86_fma_vfmsub_ps_256:
11817   case Intrinsic::x86_fma_vfmsub_pd_256:
11818   case Intrinsic::x86_fma_vfnmadd_ps_256:
11819   case Intrinsic::x86_fma_vfnmadd_pd_256:
11820   case Intrinsic::x86_fma_vfnmsub_ps_256:
11821   case Intrinsic::x86_fma_vfnmsub_pd_256:
11822   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11823   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11824   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11825   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11826   case Intrinsic::x86_fma_vfmadd_ps_512:
11827   case Intrinsic::x86_fma_vfmadd_pd_512:
11828   case Intrinsic::x86_fma_vfmsub_ps_512:
11829   case Intrinsic::x86_fma_vfmsub_pd_512:
11830   case Intrinsic::x86_fma_vfnmadd_ps_512:
11831   case Intrinsic::x86_fma_vfnmadd_pd_512:
11832   case Intrinsic::x86_fma_vfnmsub_ps_512:
11833   case Intrinsic::x86_fma_vfnmsub_pd_512:
11834   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11835   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11836   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11837   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11838     unsigned Opc;
11839     switch (IntNo) {
11840     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11841     case Intrinsic::x86_fma_vfmadd_ps:
11842     case Intrinsic::x86_fma_vfmadd_pd:
11843     case Intrinsic::x86_fma_vfmadd_ps_256:
11844     case Intrinsic::x86_fma_vfmadd_pd_256:
11845     case Intrinsic::x86_fma_vfmadd_ps_512:
11846     case Intrinsic::x86_fma_vfmadd_pd_512:
11847       Opc = X86ISD::FMADD;
11848       break;
11849     case Intrinsic::x86_fma_vfmsub_ps:
11850     case Intrinsic::x86_fma_vfmsub_pd:
11851     case Intrinsic::x86_fma_vfmsub_ps_256:
11852     case Intrinsic::x86_fma_vfmsub_pd_256:
11853     case Intrinsic::x86_fma_vfmsub_ps_512:
11854     case Intrinsic::x86_fma_vfmsub_pd_512:
11855       Opc = X86ISD::FMSUB;
11856       break;
11857     case Intrinsic::x86_fma_vfnmadd_ps:
11858     case Intrinsic::x86_fma_vfnmadd_pd:
11859     case Intrinsic::x86_fma_vfnmadd_ps_256:
11860     case Intrinsic::x86_fma_vfnmadd_pd_256:
11861     case Intrinsic::x86_fma_vfnmadd_ps_512:
11862     case Intrinsic::x86_fma_vfnmadd_pd_512:
11863       Opc = X86ISD::FNMADD;
11864       break;
11865     case Intrinsic::x86_fma_vfnmsub_ps:
11866     case Intrinsic::x86_fma_vfnmsub_pd:
11867     case Intrinsic::x86_fma_vfnmsub_ps_256:
11868     case Intrinsic::x86_fma_vfnmsub_pd_256:
11869     case Intrinsic::x86_fma_vfnmsub_ps_512:
11870     case Intrinsic::x86_fma_vfnmsub_pd_512:
11871       Opc = X86ISD::FNMSUB;
11872       break;
11873     case Intrinsic::x86_fma_vfmaddsub_ps:
11874     case Intrinsic::x86_fma_vfmaddsub_pd:
11875     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11876     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11877     case Intrinsic::x86_fma_vfmaddsub_ps_512:
11878     case Intrinsic::x86_fma_vfmaddsub_pd_512:
11879       Opc = X86ISD::FMADDSUB;
11880       break;
11881     case Intrinsic::x86_fma_vfmsubadd_ps:
11882     case Intrinsic::x86_fma_vfmsubadd_pd:
11883     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11884     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11885     case Intrinsic::x86_fma_vfmsubadd_ps_512:
11886     case Intrinsic::x86_fma_vfmsubadd_pd_512:
11887       Opc = X86ISD::FMSUBADD;
11888       break;
11889     }
11890
11891     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11892                        Op.getOperand(2), Op.getOperand(3));
11893   }
11894   }
11895 }
11896
11897 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11898                              SDValue Base, SDValue Index,
11899                              SDValue ScaleOp, SDValue Chain,
11900                              const X86Subtarget * Subtarget) {
11901   SDLoc dl(Op);
11902   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11903   assert(C && "Invalid scale type");
11904   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11905   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11906   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11907                              Index.getSimpleValueType().getVectorNumElements());
11908   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11909   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11910   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11911   SDValue Segment = DAG.getRegister(0, MVT::i32);
11912   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11913   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11914   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11915   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11916 }
11917
11918 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11919                               SDValue Src, SDValue Mask, SDValue Base,
11920                               SDValue Index, SDValue ScaleOp, SDValue Chain,
11921                               const X86Subtarget * Subtarget) {
11922   SDLoc dl(Op);
11923   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11924   assert(C && "Invalid scale type");
11925   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11926   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11927                              Index.getSimpleValueType().getVectorNumElements());
11928   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11929   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11930   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11931   SDValue Segment = DAG.getRegister(0, MVT::i32);
11932   if (Src.getOpcode() == ISD::UNDEF)
11933     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11934   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11935   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11936   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11937   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11938 }
11939
11940 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11941                               SDValue Src, SDValue Base, SDValue Index,
11942                               SDValue ScaleOp, SDValue Chain) {
11943   SDLoc dl(Op);
11944   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11945   assert(C && "Invalid scale type");
11946   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11947   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11948   SDValue Segment = DAG.getRegister(0, MVT::i32);
11949   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11950                              Index.getSimpleValueType().getVectorNumElements());
11951   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11952   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11953   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11954   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11955   return SDValue(Res, 1);
11956 }
11957
11958 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11959                                SDValue Src, SDValue Mask, SDValue Base,
11960                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
11961   SDLoc dl(Op);
11962   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11963   assert(C && "Invalid scale type");
11964   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11965   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11966   SDValue Segment = DAG.getRegister(0, MVT::i32);
11967   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11968                              Index.getSimpleValueType().getVectorNumElements());
11969   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11970   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11971   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11972   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11973   return SDValue(Res, 1);
11974 }
11975
11976 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
11977                                       SelectionDAG &DAG) {
11978   SDLoc dl(Op);
11979   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11980   switch (IntNo) {
11981   default: return SDValue();    // Don't custom lower most intrinsics.
11982
11983   // RDRAND/RDSEED intrinsics.
11984   case Intrinsic::x86_rdrand_16:
11985   case Intrinsic::x86_rdrand_32:
11986   case Intrinsic::x86_rdrand_64:
11987   case Intrinsic::x86_rdseed_16:
11988   case Intrinsic::x86_rdseed_32:
11989   case Intrinsic::x86_rdseed_64: {
11990     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11991                        IntNo == Intrinsic::x86_rdseed_32 ||
11992                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11993                                                             X86ISD::RDRAND;
11994     // Emit the node with the right value type.
11995     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11996     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11997
11998     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11999     // Otherwise return the value from Rand, which is always 0, casted to i32.
12000     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12001                       DAG.getConstant(1, Op->getValueType(1)),
12002                       DAG.getConstant(X86::COND_B, MVT::i32),
12003                       SDValue(Result.getNode(), 1) };
12004     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12005                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12006                                   Ops, array_lengthof(Ops));
12007
12008     // Return { result, isValid, chain }.
12009     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12010                        SDValue(Result.getNode(), 2));
12011   }
12012   //int_gather(index, base, scale);
12013   case Intrinsic::x86_avx512_gather_qpd_512:
12014   case Intrinsic::x86_avx512_gather_qps_512:
12015   case Intrinsic::x86_avx512_gather_dpd_512:
12016   case Intrinsic::x86_avx512_gather_qpi_512:
12017   case Intrinsic::x86_avx512_gather_qpq_512:
12018   case Intrinsic::x86_avx512_gather_dpq_512:
12019   case Intrinsic::x86_avx512_gather_dps_512:
12020   case Intrinsic::x86_avx512_gather_dpi_512: {
12021     unsigned Opc;
12022     switch (IntNo) {
12023     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12024     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12025     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12026     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12027     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12028     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12029     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12030     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12031     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12032     }
12033     SDValue Chain = Op.getOperand(0);
12034     SDValue Index = Op.getOperand(2);
12035     SDValue Base  = Op.getOperand(3);
12036     SDValue Scale = Op.getOperand(4);
12037     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12038   }
12039   //int_gather_mask(v1, mask, index, base, scale);
12040   case Intrinsic::x86_avx512_gather_qps_mask_512:
12041   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12042   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12043   case Intrinsic::x86_avx512_gather_dps_mask_512:
12044   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12045   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12046   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12047   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12048     unsigned Opc;
12049     switch (IntNo) {
12050     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12051     case Intrinsic::x86_avx512_gather_qps_mask_512:
12052       Opc = X86::VGATHERQPSZrm; break;
12053     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12054       Opc = X86::VGATHERQPDZrm; break;
12055     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12056       Opc = X86::VGATHERDPDZrm; break;
12057     case Intrinsic::x86_avx512_gather_dps_mask_512:
12058       Opc = X86::VGATHERDPSZrm; break;
12059     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12060       Opc = X86::VPGATHERQDZrm; break;
12061     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12062       Opc = X86::VPGATHERQQZrm; break;
12063     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12064       Opc = X86::VPGATHERDDZrm; break;
12065     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12066       Opc = X86::VPGATHERDQZrm; break;
12067     }
12068     SDValue Chain = Op.getOperand(0);
12069     SDValue Src   = Op.getOperand(2);
12070     SDValue Mask  = Op.getOperand(3);
12071     SDValue Index = Op.getOperand(4);
12072     SDValue Base  = Op.getOperand(5);
12073     SDValue Scale = Op.getOperand(6);
12074     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12075                           Subtarget);
12076   }
12077   //int_scatter(base, index, v1, scale);
12078   case Intrinsic::x86_avx512_scatter_qpd_512:
12079   case Intrinsic::x86_avx512_scatter_qps_512:
12080   case Intrinsic::x86_avx512_scatter_dpd_512:
12081   case Intrinsic::x86_avx512_scatter_qpi_512:
12082   case Intrinsic::x86_avx512_scatter_qpq_512:
12083   case Intrinsic::x86_avx512_scatter_dpq_512:
12084   case Intrinsic::x86_avx512_scatter_dps_512:
12085   case Intrinsic::x86_avx512_scatter_dpi_512: {
12086     unsigned Opc;
12087     switch (IntNo) {
12088     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12089     case Intrinsic::x86_avx512_scatter_qpd_512:
12090       Opc = X86::VSCATTERQPDZmr; break;
12091     case Intrinsic::x86_avx512_scatter_qps_512:
12092       Opc = X86::VSCATTERQPSZmr; break;
12093     case Intrinsic::x86_avx512_scatter_dpd_512:
12094       Opc = X86::VSCATTERDPDZmr; break;
12095     case Intrinsic::x86_avx512_scatter_dps_512:
12096       Opc = X86::VSCATTERDPSZmr; break;
12097     case Intrinsic::x86_avx512_scatter_qpi_512:
12098       Opc = X86::VPSCATTERQDZmr; break;
12099     case Intrinsic::x86_avx512_scatter_qpq_512:
12100       Opc = X86::VPSCATTERQQZmr; break;
12101     case Intrinsic::x86_avx512_scatter_dpq_512:
12102       Opc = X86::VPSCATTERDQZmr; break;
12103     case Intrinsic::x86_avx512_scatter_dpi_512:
12104       Opc = X86::VPSCATTERDDZmr; break;
12105     }
12106     SDValue Chain = Op.getOperand(0);
12107     SDValue Base  = Op.getOperand(2);
12108     SDValue Index = Op.getOperand(3);
12109     SDValue Src   = Op.getOperand(4);
12110     SDValue Scale = Op.getOperand(5);
12111     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12112   }
12113   //int_scatter_mask(base, mask, index, v1, scale);
12114   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12115   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12116   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12117   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12118   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12119   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12120   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12121   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12122     unsigned Opc;
12123     switch (IntNo) {
12124     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12125     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12126       Opc = X86::VSCATTERQPDZmr; break;
12127     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12128       Opc = X86::VSCATTERQPSZmr; break;
12129     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12130       Opc = X86::VSCATTERDPDZmr; break;
12131     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12132       Opc = X86::VSCATTERDPSZmr; break;
12133     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12134       Opc = X86::VPSCATTERQDZmr; break;
12135     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12136       Opc = X86::VPSCATTERQQZmr; break;
12137     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12138       Opc = X86::VPSCATTERDQZmr; break;
12139     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12140       Opc = X86::VPSCATTERDDZmr; break;
12141     }
12142     SDValue Chain = Op.getOperand(0);
12143     SDValue Base  = Op.getOperand(2);
12144     SDValue Mask  = Op.getOperand(3);
12145     SDValue Index = Op.getOperand(4);
12146     SDValue Src   = Op.getOperand(5);
12147     SDValue Scale = Op.getOperand(6);
12148     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12149   }
12150   // XTEST intrinsics.
12151   case Intrinsic::x86_xtest: {
12152     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12153     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12154     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12155                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12156                                 InTrans);
12157     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12158     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12159                        Ret, SDValue(InTrans.getNode(), 1));
12160   }
12161   }
12162 }
12163
12164 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12165                                            SelectionDAG &DAG) const {
12166   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12167   MFI->setReturnAddressIsTaken(true);
12168
12169   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12170     return SDValue();
12171
12172   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12173   SDLoc dl(Op);
12174   EVT PtrVT = getPointerTy();
12175
12176   if (Depth > 0) {
12177     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12178     const X86RegisterInfo *RegInfo =
12179       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12180     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12181     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12182                        DAG.getNode(ISD::ADD, dl, PtrVT,
12183                                    FrameAddr, Offset),
12184                        MachinePointerInfo(), false, false, false, 0);
12185   }
12186
12187   // Just load the return address.
12188   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12189   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12190                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12191 }
12192
12193 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12194   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12195   MFI->setFrameAddressIsTaken(true);
12196
12197   EVT VT = Op.getValueType();
12198   SDLoc dl(Op);  // FIXME probably not meaningful
12199   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12200   const X86RegisterInfo *RegInfo =
12201     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12202   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12203   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12204           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12205          "Invalid Frame Register!");
12206   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12207   while (Depth--)
12208     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12209                             MachinePointerInfo(),
12210                             false, false, false, 0);
12211   return FrameAddr;
12212 }
12213
12214 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12215                                                      SelectionDAG &DAG) const {
12216   const X86RegisterInfo *RegInfo =
12217     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12218   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12219 }
12220
12221 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12222   SDValue Chain     = Op.getOperand(0);
12223   SDValue Offset    = Op.getOperand(1);
12224   SDValue Handler   = Op.getOperand(2);
12225   SDLoc dl      (Op);
12226
12227   EVT PtrVT = getPointerTy();
12228   const X86RegisterInfo *RegInfo =
12229     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12230   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12231   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12232           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12233          "Invalid Frame Register!");
12234   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12235   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12236
12237   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12238                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12239   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12240   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12241                        false, false, 0);
12242   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12243
12244   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12245                      DAG.getRegister(StoreAddrReg, PtrVT));
12246 }
12247
12248 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12249                                                SelectionDAG &DAG) const {
12250   SDLoc DL(Op);
12251   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12252                      DAG.getVTList(MVT::i32, MVT::Other),
12253                      Op.getOperand(0), Op.getOperand(1));
12254 }
12255
12256 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12257                                                 SelectionDAG &DAG) const {
12258   SDLoc DL(Op);
12259   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12260                      Op.getOperand(0), Op.getOperand(1));
12261 }
12262
12263 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12264   return Op.getOperand(0);
12265 }
12266
12267 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12268                                                 SelectionDAG &DAG) const {
12269   SDValue Root = Op.getOperand(0);
12270   SDValue Trmp = Op.getOperand(1); // trampoline
12271   SDValue FPtr = Op.getOperand(2); // nested function
12272   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12273   SDLoc dl (Op);
12274
12275   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12276   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12277
12278   if (Subtarget->is64Bit()) {
12279     SDValue OutChains[6];
12280
12281     // Large code-model.
12282     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12283     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12284
12285     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12286     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12287
12288     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12289
12290     // Load the pointer to the nested function into R11.
12291     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12292     SDValue Addr = Trmp;
12293     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12294                                 Addr, MachinePointerInfo(TrmpAddr),
12295                                 false, false, 0);
12296
12297     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12298                        DAG.getConstant(2, MVT::i64));
12299     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12300                                 MachinePointerInfo(TrmpAddr, 2),
12301                                 false, false, 2);
12302
12303     // Load the 'nest' parameter value into R10.
12304     // R10 is specified in X86CallingConv.td
12305     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12306     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12307                        DAG.getConstant(10, MVT::i64));
12308     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12309                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12310                                 false, false, 0);
12311
12312     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12313                        DAG.getConstant(12, MVT::i64));
12314     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12315                                 MachinePointerInfo(TrmpAddr, 12),
12316                                 false, false, 2);
12317
12318     // Jump to the nested function.
12319     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12320     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12321                        DAG.getConstant(20, MVT::i64));
12322     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12323                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12324                                 false, false, 0);
12325
12326     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12327     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12328                        DAG.getConstant(22, MVT::i64));
12329     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12330                                 MachinePointerInfo(TrmpAddr, 22),
12331                                 false, false, 0);
12332
12333     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12334   } else {
12335     const Function *Func =
12336       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12337     CallingConv::ID CC = Func->getCallingConv();
12338     unsigned NestReg;
12339
12340     switch (CC) {
12341     default:
12342       llvm_unreachable("Unsupported calling convention");
12343     case CallingConv::C:
12344     case CallingConv::X86_StdCall: {
12345       // Pass 'nest' parameter in ECX.
12346       // Must be kept in sync with X86CallingConv.td
12347       NestReg = X86::ECX;
12348
12349       // Check that ECX wasn't needed by an 'inreg' parameter.
12350       FunctionType *FTy = Func->getFunctionType();
12351       const AttributeSet &Attrs = Func->getAttributes();
12352
12353       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12354         unsigned InRegCount = 0;
12355         unsigned Idx = 1;
12356
12357         for (FunctionType::param_iterator I = FTy->param_begin(),
12358              E = FTy->param_end(); I != E; ++I, ++Idx)
12359           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12360             // FIXME: should only count parameters that are lowered to integers.
12361             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12362
12363         if (InRegCount > 2) {
12364           report_fatal_error("Nest register in use - reduce number of inreg"
12365                              " parameters!");
12366         }
12367       }
12368       break;
12369     }
12370     case CallingConv::X86_FastCall:
12371     case CallingConv::X86_ThisCall:
12372     case CallingConv::Fast:
12373       // Pass 'nest' parameter in EAX.
12374       // Must be kept in sync with X86CallingConv.td
12375       NestReg = X86::EAX;
12376       break;
12377     }
12378
12379     SDValue OutChains[4];
12380     SDValue Addr, Disp;
12381
12382     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12383                        DAG.getConstant(10, MVT::i32));
12384     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12385
12386     // This is storing the opcode for MOV32ri.
12387     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12388     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12389     OutChains[0] = DAG.getStore(Root, dl,
12390                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12391                                 Trmp, MachinePointerInfo(TrmpAddr),
12392                                 false, false, 0);
12393
12394     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12395                        DAG.getConstant(1, MVT::i32));
12396     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12397                                 MachinePointerInfo(TrmpAddr, 1),
12398                                 false, false, 1);
12399
12400     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12401     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12402                        DAG.getConstant(5, MVT::i32));
12403     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12404                                 MachinePointerInfo(TrmpAddr, 5),
12405                                 false, false, 1);
12406
12407     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12408                        DAG.getConstant(6, MVT::i32));
12409     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12410                                 MachinePointerInfo(TrmpAddr, 6),
12411                                 false, false, 1);
12412
12413     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12414   }
12415 }
12416
12417 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12418                                             SelectionDAG &DAG) const {
12419   /*
12420    The rounding mode is in bits 11:10 of FPSR, and has the following
12421    settings:
12422      00 Round to nearest
12423      01 Round to -inf
12424      10 Round to +inf
12425      11 Round to 0
12426
12427   FLT_ROUNDS, on the other hand, expects the following:
12428     -1 Undefined
12429      0 Round to 0
12430      1 Round to nearest
12431      2 Round to +inf
12432      3 Round to -inf
12433
12434   To perform the conversion, we do:
12435     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12436   */
12437
12438   MachineFunction &MF = DAG.getMachineFunction();
12439   const TargetMachine &TM = MF.getTarget();
12440   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12441   unsigned StackAlignment = TFI.getStackAlignment();
12442   MVT VT = Op.getSimpleValueType();
12443   SDLoc DL(Op);
12444
12445   // Save FP Control Word to stack slot
12446   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12447   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12448
12449   MachineMemOperand *MMO =
12450    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12451                            MachineMemOperand::MOStore, 2, 2);
12452
12453   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12454   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12455                                           DAG.getVTList(MVT::Other),
12456                                           Ops, array_lengthof(Ops), MVT::i16,
12457                                           MMO);
12458
12459   // Load FP Control Word from stack slot
12460   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12461                             MachinePointerInfo(), false, false, false, 0);
12462
12463   // Transform as necessary
12464   SDValue CWD1 =
12465     DAG.getNode(ISD::SRL, DL, MVT::i16,
12466                 DAG.getNode(ISD::AND, DL, MVT::i16,
12467                             CWD, DAG.getConstant(0x800, MVT::i16)),
12468                 DAG.getConstant(11, MVT::i8));
12469   SDValue CWD2 =
12470     DAG.getNode(ISD::SRL, DL, MVT::i16,
12471                 DAG.getNode(ISD::AND, DL, MVT::i16,
12472                             CWD, DAG.getConstant(0x400, MVT::i16)),
12473                 DAG.getConstant(9, MVT::i8));
12474
12475   SDValue RetVal =
12476     DAG.getNode(ISD::AND, DL, MVT::i16,
12477                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12478                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12479                             DAG.getConstant(1, MVT::i16)),
12480                 DAG.getConstant(3, MVT::i16));
12481
12482   return DAG.getNode((VT.getSizeInBits() < 16 ?
12483                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12484 }
12485
12486 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12487   MVT VT = Op.getSimpleValueType();
12488   EVT OpVT = VT;
12489   unsigned NumBits = VT.getSizeInBits();
12490   SDLoc dl(Op);
12491
12492   Op = Op.getOperand(0);
12493   if (VT == MVT::i8) {
12494     // Zero extend to i32 since there is not an i8 bsr.
12495     OpVT = MVT::i32;
12496     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12497   }
12498
12499   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12500   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12501   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12502
12503   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12504   SDValue Ops[] = {
12505     Op,
12506     DAG.getConstant(NumBits+NumBits-1, OpVT),
12507     DAG.getConstant(X86::COND_E, MVT::i8),
12508     Op.getValue(1)
12509   };
12510   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12511
12512   // Finally xor with NumBits-1.
12513   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12514
12515   if (VT == MVT::i8)
12516     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12517   return Op;
12518 }
12519
12520 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12521   MVT VT = Op.getSimpleValueType();
12522   EVT OpVT = VT;
12523   unsigned NumBits = VT.getSizeInBits();
12524   SDLoc dl(Op);
12525
12526   Op = Op.getOperand(0);
12527   if (VT == MVT::i8) {
12528     // Zero extend to i32 since there is not an i8 bsr.
12529     OpVT = MVT::i32;
12530     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12531   }
12532
12533   // Issue a bsr (scan bits in reverse).
12534   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12535   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12536
12537   // And xor with NumBits-1.
12538   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12539
12540   if (VT == MVT::i8)
12541     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12542   return Op;
12543 }
12544
12545 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12546   MVT VT = Op.getSimpleValueType();
12547   unsigned NumBits = VT.getSizeInBits();
12548   SDLoc dl(Op);
12549   Op = Op.getOperand(0);
12550
12551   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12552   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12553   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12554
12555   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12556   SDValue Ops[] = {
12557     Op,
12558     DAG.getConstant(NumBits, VT),
12559     DAG.getConstant(X86::COND_E, MVT::i8),
12560     Op.getValue(1)
12561   };
12562   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12563 }
12564
12565 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12566 // ones, and then concatenate the result back.
12567 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12568   MVT VT = Op.getSimpleValueType();
12569
12570   assert(VT.is256BitVector() && VT.isInteger() &&
12571          "Unsupported value type for operation");
12572
12573   unsigned NumElems = VT.getVectorNumElements();
12574   SDLoc dl(Op);
12575
12576   // Extract the LHS vectors
12577   SDValue LHS = Op.getOperand(0);
12578   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12579   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12580
12581   // Extract the RHS vectors
12582   SDValue RHS = Op.getOperand(1);
12583   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12584   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12585
12586   MVT EltVT = VT.getVectorElementType();
12587   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12588
12589   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12590                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12591                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12592 }
12593
12594 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12595   assert(Op.getSimpleValueType().is256BitVector() &&
12596          Op.getSimpleValueType().isInteger() &&
12597          "Only handle AVX 256-bit vector integer operation");
12598   return Lower256IntArith(Op, DAG);
12599 }
12600
12601 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12602   assert(Op.getSimpleValueType().is256BitVector() &&
12603          Op.getSimpleValueType().isInteger() &&
12604          "Only handle AVX 256-bit vector integer operation");
12605   return Lower256IntArith(Op, DAG);
12606 }
12607
12608 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12609                         SelectionDAG &DAG) {
12610   SDLoc dl(Op);
12611   MVT VT = Op.getSimpleValueType();
12612
12613   // Decompose 256-bit ops into smaller 128-bit ops.
12614   if (VT.is256BitVector() && !Subtarget->hasInt256())
12615     return Lower256IntArith(Op, DAG);
12616
12617   SDValue A = Op.getOperand(0);
12618   SDValue B = Op.getOperand(1);
12619
12620   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12621   if (VT == MVT::v4i32) {
12622     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12623            "Should not custom lower when pmuldq is available!");
12624
12625     // Extract the odd parts.
12626     static const int UnpackMask[] = { 1, -1, 3, -1 };
12627     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12628     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12629
12630     // Multiply the even parts.
12631     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12632     // Now multiply odd parts.
12633     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12634
12635     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12636     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12637
12638     // Merge the two vectors back together with a shuffle. This expands into 2
12639     // shuffles.
12640     static const int ShufMask[] = { 0, 4, 2, 6 };
12641     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12642   }
12643
12644   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12645          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12646
12647   //  Ahi = psrlqi(a, 32);
12648   //  Bhi = psrlqi(b, 32);
12649   //
12650   //  AloBlo = pmuludq(a, b);
12651   //  AloBhi = pmuludq(a, Bhi);
12652   //  AhiBlo = pmuludq(Ahi, b);
12653
12654   //  AloBhi = psllqi(AloBhi, 32);
12655   //  AhiBlo = psllqi(AhiBlo, 32);
12656   //  return AloBlo + AloBhi + AhiBlo;
12657
12658   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12659   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12660
12661   // Bit cast to 32-bit vectors for MULUDQ
12662   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12663                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12664   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12665   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12666   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12667   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12668
12669   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12670   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12671   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12672
12673   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12674   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12675
12676   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12677   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12678 }
12679
12680 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12681   MVT VT = Op.getSimpleValueType();
12682   MVT EltTy = VT.getVectorElementType();
12683   unsigned NumElts = VT.getVectorNumElements();
12684   SDValue N0 = Op.getOperand(0);
12685   SDLoc dl(Op);
12686
12687   // Lower sdiv X, pow2-const.
12688   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12689   if (!C)
12690     return SDValue();
12691
12692   APInt SplatValue, SplatUndef;
12693   unsigned SplatBitSize;
12694   bool HasAnyUndefs;
12695   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12696                           HasAnyUndefs) ||
12697       EltTy.getSizeInBits() < SplatBitSize)
12698     return SDValue();
12699
12700   if ((SplatValue != 0) &&
12701       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12702     unsigned Lg2 = SplatValue.countTrailingZeros();
12703     // Splat the sign bit.
12704     SmallVector<SDValue, 16> Sz(NumElts,
12705                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12706                                                 EltTy));
12707     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12708                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12709                                           NumElts));
12710     // Add (N0 < 0) ? abs2 - 1 : 0;
12711     SmallVector<SDValue, 16> Amt(NumElts,
12712                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12713                                                  EltTy));
12714     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12715                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12716                                           NumElts));
12717     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12718     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12719     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12720                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12721                                           NumElts));
12722
12723     // If we're dividing by a positive value, we're done.  Otherwise, we must
12724     // negate the result.
12725     if (SplatValue.isNonNegative())
12726       return SRA;
12727
12728     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12729     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12730     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12731   }
12732   return SDValue();
12733 }
12734
12735 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12736                                          const X86Subtarget *Subtarget) {
12737   MVT VT = Op.getSimpleValueType();
12738   SDLoc dl(Op);
12739   SDValue R = Op.getOperand(0);
12740   SDValue Amt = Op.getOperand(1);
12741
12742   // Optimize shl/srl/sra with constant shift amount.
12743   if (isSplatVector(Amt.getNode())) {
12744     SDValue SclrAmt = Amt->getOperand(0);
12745     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12746       uint64_t ShiftAmt = C->getZExtValue();
12747
12748       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12749           (Subtarget->hasInt256() &&
12750            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12751           (Subtarget->hasAVX512() &&
12752            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12753         if (Op.getOpcode() == ISD::SHL)
12754           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12755                                             DAG);
12756         if (Op.getOpcode() == ISD::SRL)
12757           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12758                                             DAG);
12759         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12760           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12761                                             DAG);
12762       }
12763
12764       if (VT == MVT::v16i8) {
12765         if (Op.getOpcode() == ISD::SHL) {
12766           // Make a large shift.
12767           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12768                                                    MVT::v8i16, R, ShiftAmt,
12769                                                    DAG);
12770           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12771           // Zero out the rightmost bits.
12772           SmallVector<SDValue, 16> V(16,
12773                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12774                                                      MVT::i8));
12775           return DAG.getNode(ISD::AND, dl, VT, SHL,
12776                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12777         }
12778         if (Op.getOpcode() == ISD::SRL) {
12779           // Make a large shift.
12780           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12781                                                    MVT::v8i16, R, ShiftAmt,
12782                                                    DAG);
12783           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12784           // Zero out the leftmost bits.
12785           SmallVector<SDValue, 16> V(16,
12786                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12787                                                      MVT::i8));
12788           return DAG.getNode(ISD::AND, dl, VT, SRL,
12789                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12790         }
12791         if (Op.getOpcode() == ISD::SRA) {
12792           if (ShiftAmt == 7) {
12793             // R s>> 7  ===  R s< 0
12794             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12795             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12796           }
12797
12798           // R s>> a === ((R u>> a) ^ m) - m
12799           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12800           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12801                                                          MVT::i8));
12802           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12803           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12804           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12805           return Res;
12806         }
12807         llvm_unreachable("Unknown shift opcode.");
12808       }
12809
12810       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12811         if (Op.getOpcode() == ISD::SHL) {
12812           // Make a large shift.
12813           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12814                                                    MVT::v16i16, R, ShiftAmt,
12815                                                    DAG);
12816           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12817           // Zero out the rightmost bits.
12818           SmallVector<SDValue, 32> V(32,
12819                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12820                                                      MVT::i8));
12821           return DAG.getNode(ISD::AND, dl, VT, SHL,
12822                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12823         }
12824         if (Op.getOpcode() == ISD::SRL) {
12825           // Make a large shift.
12826           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12827                                                    MVT::v16i16, R, ShiftAmt,
12828                                                    DAG);
12829           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12830           // Zero out the leftmost bits.
12831           SmallVector<SDValue, 32> V(32,
12832                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12833                                                      MVT::i8));
12834           return DAG.getNode(ISD::AND, dl, VT, SRL,
12835                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12836         }
12837         if (Op.getOpcode() == ISD::SRA) {
12838           if (ShiftAmt == 7) {
12839             // R s>> 7  ===  R s< 0
12840             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12841             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12842           }
12843
12844           // R s>> a === ((R u>> a) ^ m) - m
12845           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12846           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12847                                                          MVT::i8));
12848           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12849           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12850           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12851           return Res;
12852         }
12853         llvm_unreachable("Unknown shift opcode.");
12854       }
12855     }
12856   }
12857
12858   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12859   if (!Subtarget->is64Bit() &&
12860       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12861       Amt.getOpcode() == ISD::BITCAST &&
12862       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12863     Amt = Amt.getOperand(0);
12864     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
12865                      VT.getVectorNumElements();
12866     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12867     uint64_t ShiftAmt = 0;
12868     for (unsigned i = 0; i != Ratio; ++i) {
12869       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12870       if (C == 0)
12871         return SDValue();
12872       // 6 == Log2(64)
12873       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12874     }
12875     // Check remaining shift amounts.
12876     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12877       uint64_t ShAmt = 0;
12878       for (unsigned j = 0; j != Ratio; ++j) {
12879         ConstantSDNode *C =
12880           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12881         if (C == 0)
12882           return SDValue();
12883         // 6 == Log2(64)
12884         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12885       }
12886       if (ShAmt != ShiftAmt)
12887         return SDValue();
12888     }
12889     switch (Op.getOpcode()) {
12890     default:
12891       llvm_unreachable("Unknown shift opcode!");
12892     case ISD::SHL:
12893       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12894                                         DAG);
12895     case ISD::SRL:
12896       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12897                                         DAG);
12898     case ISD::SRA:
12899       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12900                                         DAG);
12901     }
12902   }
12903
12904   return SDValue();
12905 }
12906
12907 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12908                                         const X86Subtarget* Subtarget) {
12909   MVT VT = Op.getSimpleValueType();
12910   SDLoc dl(Op);
12911   SDValue R = Op.getOperand(0);
12912   SDValue Amt = Op.getOperand(1);
12913
12914   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12915       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12916       (Subtarget->hasInt256() &&
12917        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12918         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12919        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12920     SDValue BaseShAmt;
12921     EVT EltVT = VT.getVectorElementType();
12922
12923     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12924       unsigned NumElts = VT.getVectorNumElements();
12925       unsigned i, j;
12926       for (i = 0; i != NumElts; ++i) {
12927         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12928           continue;
12929         break;
12930       }
12931       for (j = i; j != NumElts; ++j) {
12932         SDValue Arg = Amt.getOperand(j);
12933         if (Arg.getOpcode() == ISD::UNDEF) continue;
12934         if (Arg != Amt.getOperand(i))
12935           break;
12936       }
12937       if (i != NumElts && j == NumElts)
12938         BaseShAmt = Amt.getOperand(i);
12939     } else {
12940       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12941         Amt = Amt.getOperand(0);
12942       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12943                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12944         SDValue InVec = Amt.getOperand(0);
12945         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12946           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12947           unsigned i = 0;
12948           for (; i != NumElts; ++i) {
12949             SDValue Arg = InVec.getOperand(i);
12950             if (Arg.getOpcode() == ISD::UNDEF) continue;
12951             BaseShAmt = Arg;
12952             break;
12953           }
12954         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12955            if (ConstantSDNode *C =
12956                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12957              unsigned SplatIdx =
12958                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12959              if (C->getZExtValue() == SplatIdx)
12960                BaseShAmt = InVec.getOperand(1);
12961            }
12962         }
12963         if (BaseShAmt.getNode() == 0)
12964           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12965                                   DAG.getIntPtrConstant(0));
12966       }
12967     }
12968
12969     if (BaseShAmt.getNode()) {
12970       if (EltVT.bitsGT(MVT::i32))
12971         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12972       else if (EltVT.bitsLT(MVT::i32))
12973         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12974
12975       switch (Op.getOpcode()) {
12976       default:
12977         llvm_unreachable("Unknown shift opcode!");
12978       case ISD::SHL:
12979         switch (VT.SimpleTy) {
12980         default: return SDValue();
12981         case MVT::v2i64:
12982         case MVT::v4i32:
12983         case MVT::v8i16:
12984         case MVT::v4i64:
12985         case MVT::v8i32:
12986         case MVT::v16i16:
12987         case MVT::v16i32:
12988         case MVT::v8i64:
12989           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12990         }
12991       case ISD::SRA:
12992         switch (VT.SimpleTy) {
12993         default: return SDValue();
12994         case MVT::v4i32:
12995         case MVT::v8i16:
12996         case MVT::v8i32:
12997         case MVT::v16i16:
12998         case MVT::v16i32:
12999         case MVT::v8i64:
13000           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13001         }
13002       case ISD::SRL:
13003         switch (VT.SimpleTy) {
13004         default: return SDValue();
13005         case MVT::v2i64:
13006         case MVT::v4i32:
13007         case MVT::v8i16:
13008         case MVT::v4i64:
13009         case MVT::v8i32:
13010         case MVT::v16i16:
13011         case MVT::v16i32:
13012         case MVT::v8i64:
13013           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13014         }
13015       }
13016     }
13017   }
13018
13019   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13020   if (!Subtarget->is64Bit() &&
13021       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13022       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13023       Amt.getOpcode() == ISD::BITCAST &&
13024       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13025     Amt = Amt.getOperand(0);
13026     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13027                      VT.getVectorNumElements();
13028     std::vector<SDValue> Vals(Ratio);
13029     for (unsigned i = 0; i != Ratio; ++i)
13030       Vals[i] = Amt.getOperand(i);
13031     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13032       for (unsigned j = 0; j != Ratio; ++j)
13033         if (Vals[j] != Amt.getOperand(i + j))
13034           return SDValue();
13035     }
13036     switch (Op.getOpcode()) {
13037     default:
13038       llvm_unreachable("Unknown shift opcode!");
13039     case ISD::SHL:
13040       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13041     case ISD::SRL:
13042       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13043     case ISD::SRA:
13044       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13045     }
13046   }
13047
13048   return SDValue();
13049 }
13050
13051 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13052                           SelectionDAG &DAG) {
13053
13054   MVT VT = Op.getSimpleValueType();
13055   SDLoc dl(Op);
13056   SDValue R = Op.getOperand(0);
13057   SDValue Amt = Op.getOperand(1);
13058   SDValue V;
13059
13060   if (!Subtarget->hasSSE2())
13061     return SDValue();
13062
13063   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13064   if (V.getNode())
13065     return V;
13066
13067   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13068   if (V.getNode())
13069       return V;
13070
13071   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13072     return Op;
13073   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13074   if (Subtarget->hasInt256()) {
13075     if (Op.getOpcode() == ISD::SRL &&
13076         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13077          VT == MVT::v4i64 || VT == MVT::v8i32))
13078       return Op;
13079     if (Op.getOpcode() == ISD::SHL &&
13080         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13081          VT == MVT::v4i64 || VT == MVT::v8i32))
13082       return Op;
13083     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13084       return Op;
13085   }
13086
13087   // Lower SHL with variable shift amount.
13088   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13089     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13090
13091     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13092     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13093     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13094     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13095   }
13096   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13097     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13098
13099     // a = a << 5;
13100     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13101     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13102
13103     // Turn 'a' into a mask suitable for VSELECT
13104     SDValue VSelM = DAG.getConstant(0x80, VT);
13105     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13106     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13107
13108     SDValue CM1 = DAG.getConstant(0x0f, VT);
13109     SDValue CM2 = DAG.getConstant(0x3f, VT);
13110
13111     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13112     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13113     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13114     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13115     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13116
13117     // a += a
13118     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13119     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13120     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13121
13122     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13123     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13124     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13125     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13126     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13127
13128     // a += a
13129     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13130     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13131     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13132
13133     // return VSELECT(r, r+r, a);
13134     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13135                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13136     return R;
13137   }
13138
13139   // Decompose 256-bit shifts into smaller 128-bit shifts.
13140   if (VT.is256BitVector()) {
13141     unsigned NumElems = VT.getVectorNumElements();
13142     MVT EltVT = VT.getVectorElementType();
13143     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13144
13145     // Extract the two vectors
13146     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13147     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13148
13149     // Recreate the shift amount vectors
13150     SDValue Amt1, Amt2;
13151     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13152       // Constant shift amount
13153       SmallVector<SDValue, 4> Amt1Csts;
13154       SmallVector<SDValue, 4> Amt2Csts;
13155       for (unsigned i = 0; i != NumElems/2; ++i)
13156         Amt1Csts.push_back(Amt->getOperand(i));
13157       for (unsigned i = NumElems/2; i != NumElems; ++i)
13158         Amt2Csts.push_back(Amt->getOperand(i));
13159
13160       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13161                                  &Amt1Csts[0], NumElems/2);
13162       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13163                                  &Amt2Csts[0], NumElems/2);
13164     } else {
13165       // Variable shift amount
13166       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13167       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13168     }
13169
13170     // Issue new vector shifts for the smaller types
13171     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13172     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13173
13174     // Concatenate the result back
13175     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13176   }
13177
13178   return SDValue();
13179 }
13180
13181 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13182   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13183   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13184   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13185   // has only one use.
13186   SDNode *N = Op.getNode();
13187   SDValue LHS = N->getOperand(0);
13188   SDValue RHS = N->getOperand(1);
13189   unsigned BaseOp = 0;
13190   unsigned Cond = 0;
13191   SDLoc DL(Op);
13192   switch (Op.getOpcode()) {
13193   default: llvm_unreachable("Unknown ovf instruction!");
13194   case ISD::SADDO:
13195     // A subtract of one will be selected as a INC. Note that INC doesn't
13196     // set CF, so we can't do this for UADDO.
13197     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13198       if (C->isOne()) {
13199         BaseOp = X86ISD::INC;
13200         Cond = X86::COND_O;
13201         break;
13202       }
13203     BaseOp = X86ISD::ADD;
13204     Cond = X86::COND_O;
13205     break;
13206   case ISD::UADDO:
13207     BaseOp = X86ISD::ADD;
13208     Cond = X86::COND_B;
13209     break;
13210   case ISD::SSUBO:
13211     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13212     // set CF, so we can't do this for USUBO.
13213     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13214       if (C->isOne()) {
13215         BaseOp = X86ISD::DEC;
13216         Cond = X86::COND_O;
13217         break;
13218       }
13219     BaseOp = X86ISD::SUB;
13220     Cond = X86::COND_O;
13221     break;
13222   case ISD::USUBO:
13223     BaseOp = X86ISD::SUB;
13224     Cond = X86::COND_B;
13225     break;
13226   case ISD::SMULO:
13227     BaseOp = X86ISD::SMUL;
13228     Cond = X86::COND_O;
13229     break;
13230   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13231     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13232                                  MVT::i32);
13233     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13234
13235     SDValue SetCC =
13236       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13237                   DAG.getConstant(X86::COND_O, MVT::i32),
13238                   SDValue(Sum.getNode(), 2));
13239
13240     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13241   }
13242   }
13243
13244   // Also sets EFLAGS.
13245   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13246   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13247
13248   SDValue SetCC =
13249     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13250                 DAG.getConstant(Cond, MVT::i32),
13251                 SDValue(Sum.getNode(), 1));
13252
13253   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13254 }
13255
13256 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13257                                                   SelectionDAG &DAG) const {
13258   SDLoc dl(Op);
13259   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13260   MVT VT = Op.getSimpleValueType();
13261
13262   if (!Subtarget->hasSSE2() || !VT.isVector())
13263     return SDValue();
13264
13265   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13266                       ExtraVT.getScalarType().getSizeInBits();
13267
13268   switch (VT.SimpleTy) {
13269     default: return SDValue();
13270     case MVT::v8i32:
13271     case MVT::v16i16:
13272       if (!Subtarget->hasFp256())
13273         return SDValue();
13274       if (!Subtarget->hasInt256()) {
13275         // needs to be split
13276         unsigned NumElems = VT.getVectorNumElements();
13277
13278         // Extract the LHS vectors
13279         SDValue LHS = Op.getOperand(0);
13280         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13281         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13282
13283         MVT EltVT = VT.getVectorElementType();
13284         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13285
13286         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13287         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13288         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13289                                    ExtraNumElems/2);
13290         SDValue Extra = DAG.getValueType(ExtraVT);
13291
13292         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13293         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13294
13295         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13296       }
13297       // fall through
13298     case MVT::v4i32:
13299     case MVT::v8i16: {
13300       SDValue Op0 = Op.getOperand(0);
13301       SDValue Op00 = Op0.getOperand(0);
13302       SDValue Tmp1;
13303       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13304       if (Op0.getOpcode() == ISD::BITCAST &&
13305           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13306         // (sext (vzext x)) -> (vsext x)
13307         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13308         if (Tmp1.getNode()) {
13309           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13310           // This folding is only valid when the in-reg type is a vector of i8,
13311           // i16, or i32.
13312           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13313               ExtraEltVT == MVT::i32) {
13314             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13315             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13316                    "This optimization is invalid without a VZEXT.");
13317             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13318           }
13319           Op0 = Tmp1;
13320         }
13321       }
13322
13323       // If the above didn't work, then just use Shift-Left + Shift-Right.
13324       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13325                                         DAG);
13326       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13327                                         DAG);
13328     }
13329   }
13330 }
13331
13332 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13333                                  SelectionDAG &DAG) {
13334   SDLoc dl(Op);
13335   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13336     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13337   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13338     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13339
13340   // The only fence that needs an instruction is a sequentially-consistent
13341   // cross-thread fence.
13342   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13343     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13344     // no-sse2). There isn't any reason to disable it if the target processor
13345     // supports it.
13346     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13347       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13348
13349     SDValue Chain = Op.getOperand(0);
13350     SDValue Zero = DAG.getConstant(0, MVT::i32);
13351     SDValue Ops[] = {
13352       DAG.getRegister(X86::ESP, MVT::i32), // Base
13353       DAG.getTargetConstant(1, MVT::i8),   // Scale
13354       DAG.getRegister(0, MVT::i32),        // Index
13355       DAG.getTargetConstant(0, MVT::i32),  // Disp
13356       DAG.getRegister(0, MVT::i32),        // Segment.
13357       Zero,
13358       Chain
13359     };
13360     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13361     return SDValue(Res, 0);
13362   }
13363
13364   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13365   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13366 }
13367
13368 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13369                              SelectionDAG &DAG) {
13370   MVT T = Op.getSimpleValueType();
13371   SDLoc DL(Op);
13372   unsigned Reg = 0;
13373   unsigned size = 0;
13374   switch(T.SimpleTy) {
13375   default: llvm_unreachable("Invalid value type!");
13376   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13377   case MVT::i16: Reg = X86::AX;  size = 2; break;
13378   case MVT::i32: Reg = X86::EAX; size = 4; break;
13379   case MVT::i64:
13380     assert(Subtarget->is64Bit() && "Node not type legal!");
13381     Reg = X86::RAX; size = 8;
13382     break;
13383   }
13384   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13385                                     Op.getOperand(2), SDValue());
13386   SDValue Ops[] = { cpIn.getValue(0),
13387                     Op.getOperand(1),
13388                     Op.getOperand(3),
13389                     DAG.getTargetConstant(size, MVT::i8),
13390                     cpIn.getValue(1) };
13391   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13392   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13393   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13394                                            Ops, array_lengthof(Ops), T, MMO);
13395   SDValue cpOut =
13396     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13397   return cpOut;
13398 }
13399
13400 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13401                                      SelectionDAG &DAG) {
13402   assert(Subtarget->is64Bit() && "Result not type legalized?");
13403   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13404   SDValue TheChain = Op.getOperand(0);
13405   SDLoc dl(Op);
13406   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13407   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13408   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13409                                    rax.getValue(2));
13410   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13411                             DAG.getConstant(32, MVT::i8));
13412   SDValue Ops[] = {
13413     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13414     rdx.getValue(1)
13415   };
13416   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13417 }
13418
13419 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13420                             SelectionDAG &DAG) {
13421   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13422   MVT DstVT = Op.getSimpleValueType();
13423   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13424          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13425   assert((DstVT == MVT::i64 ||
13426           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13427          "Unexpected custom BITCAST");
13428   // i64 <=> MMX conversions are Legal.
13429   if (SrcVT==MVT::i64 && DstVT.isVector())
13430     return Op;
13431   if (DstVT==MVT::i64 && SrcVT.isVector())
13432     return Op;
13433   // MMX <=> MMX conversions are Legal.
13434   if (SrcVT.isVector() && DstVT.isVector())
13435     return Op;
13436   // All other conversions need to be expanded.
13437   return SDValue();
13438 }
13439
13440 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13441   SDNode *Node = Op.getNode();
13442   SDLoc dl(Node);
13443   EVT T = Node->getValueType(0);
13444   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13445                               DAG.getConstant(0, T), Node->getOperand(2));
13446   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13447                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13448                        Node->getOperand(0),
13449                        Node->getOperand(1), negOp,
13450                        cast<AtomicSDNode>(Node)->getSrcValue(),
13451                        cast<AtomicSDNode>(Node)->getAlignment(),
13452                        cast<AtomicSDNode>(Node)->getOrdering(),
13453                        cast<AtomicSDNode>(Node)->getSynchScope());
13454 }
13455
13456 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13457   SDNode *Node = Op.getNode();
13458   SDLoc dl(Node);
13459   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13460
13461   // Convert seq_cst store -> xchg
13462   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13463   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13464   //        (The only way to get a 16-byte store is cmpxchg16b)
13465   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13466   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13467       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13468     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13469                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13470                                  Node->getOperand(0),
13471                                  Node->getOperand(1), Node->getOperand(2),
13472                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13473                                  cast<AtomicSDNode>(Node)->getOrdering(),
13474                                  cast<AtomicSDNode>(Node)->getSynchScope());
13475     return Swap.getValue(1);
13476   }
13477   // Other atomic stores have a simple pattern.
13478   return Op;
13479 }
13480
13481 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13482   EVT VT = Op.getNode()->getSimpleValueType(0);
13483
13484   // Let legalize expand this if it isn't a legal type yet.
13485   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13486     return SDValue();
13487
13488   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13489
13490   unsigned Opc;
13491   bool ExtraOp = false;
13492   switch (Op.getOpcode()) {
13493   default: llvm_unreachable("Invalid code");
13494   case ISD::ADDC: Opc = X86ISD::ADD; break;
13495   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13496   case ISD::SUBC: Opc = X86ISD::SUB; break;
13497   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13498   }
13499
13500   if (!ExtraOp)
13501     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13502                        Op.getOperand(1));
13503   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13504                      Op.getOperand(1), Op.getOperand(2));
13505 }
13506
13507 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13508                             SelectionDAG &DAG) {
13509   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13510
13511   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13512   // which returns the values as { float, float } (in XMM0) or
13513   // { double, double } (which is returned in XMM0, XMM1).
13514   SDLoc dl(Op);
13515   SDValue Arg = Op.getOperand(0);
13516   EVT ArgVT = Arg.getValueType();
13517   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13518
13519   TargetLowering::ArgListTy Args;
13520   TargetLowering::ArgListEntry Entry;
13521
13522   Entry.Node = Arg;
13523   Entry.Ty = ArgTy;
13524   Entry.isSExt = false;
13525   Entry.isZExt = false;
13526   Args.push_back(Entry);
13527
13528   bool isF64 = ArgVT == MVT::f64;
13529   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13530   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13531   // the results are returned via SRet in memory.
13532   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13533   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13534   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13535
13536   Type *RetTy = isF64
13537     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13538     : (Type*)VectorType::get(ArgTy, 4);
13539   TargetLowering::
13540     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13541                          false, false, false, false, 0,
13542                          CallingConv::C, /*isTaillCall=*/false,
13543                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13544                          Callee, Args, DAG, dl);
13545   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13546
13547   if (isF64)
13548     // Returned in xmm0 and xmm1.
13549     return CallResult.first;
13550
13551   // Returned in bits 0:31 and 32:64 xmm0.
13552   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13553                                CallResult.first, DAG.getIntPtrConstant(0));
13554   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13555                                CallResult.first, DAG.getIntPtrConstant(1));
13556   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13557   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13558 }
13559
13560 /// LowerOperation - Provide custom lowering hooks for some operations.
13561 ///
13562 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13563   switch (Op.getOpcode()) {
13564   default: llvm_unreachable("Should not custom lower this!");
13565   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13566   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13567   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13568   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13569   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13570   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13571   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13572   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13573   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13574   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13575   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13576   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13577   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13578   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13579   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13580   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13581   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13582   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13583   case ISD::SHL_PARTS:
13584   case ISD::SRA_PARTS:
13585   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13586   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13587   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13588   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13589   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13590   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13591   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13592   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13593   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13594   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13595   case ISD::FABS:               return LowerFABS(Op, DAG);
13596   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13597   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13598   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13599   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13600   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13601   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13602   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13603   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13604   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13605   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13606   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13607   case ISD::INTRINSIC_VOID:
13608   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13609   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13610   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13611   case ISD::FRAME_TO_ARGS_OFFSET:
13612                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13613   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13614   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13615   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13616   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13617   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13618   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13619   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13620   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13621   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13622   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13623   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13624   case ISD::SRA:
13625   case ISD::SRL:
13626   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13627   case ISD::SADDO:
13628   case ISD::UADDO:
13629   case ISD::SSUBO:
13630   case ISD::USUBO:
13631   case ISD::SMULO:
13632   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13633   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13634   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13635   case ISD::ADDC:
13636   case ISD::ADDE:
13637   case ISD::SUBC:
13638   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13639   case ISD::ADD:                return LowerADD(Op, DAG);
13640   case ISD::SUB:                return LowerSUB(Op, DAG);
13641   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13642   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13643   }
13644 }
13645
13646 static void ReplaceATOMIC_LOAD(SDNode *Node,
13647                                   SmallVectorImpl<SDValue> &Results,
13648                                   SelectionDAG &DAG) {
13649   SDLoc dl(Node);
13650   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13651
13652   // Convert wide load -> cmpxchg8b/cmpxchg16b
13653   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13654   //        (The only way to get a 16-byte load is cmpxchg16b)
13655   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13656   SDValue Zero = DAG.getConstant(0, VT);
13657   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13658                                Node->getOperand(0),
13659                                Node->getOperand(1), Zero, Zero,
13660                                cast<AtomicSDNode>(Node)->getMemOperand(),
13661                                cast<AtomicSDNode>(Node)->getOrdering(),
13662                                cast<AtomicSDNode>(Node)->getSynchScope());
13663   Results.push_back(Swap.getValue(0));
13664   Results.push_back(Swap.getValue(1));
13665 }
13666
13667 static void
13668 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13669                         SelectionDAG &DAG, unsigned NewOp) {
13670   SDLoc dl(Node);
13671   assert (Node->getValueType(0) == MVT::i64 &&
13672           "Only know how to expand i64 atomics");
13673
13674   SDValue Chain = Node->getOperand(0);
13675   SDValue In1 = Node->getOperand(1);
13676   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13677                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13678   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13679                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13680   SDValue Ops[] = { Chain, In1, In2L, In2H };
13681   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13682   SDValue Result =
13683     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13684                             cast<MemSDNode>(Node)->getMemOperand());
13685   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13686   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13687   Results.push_back(Result.getValue(2));
13688 }
13689
13690 /// ReplaceNodeResults - Replace a node with an illegal result type
13691 /// with a new node built out of custom code.
13692 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13693                                            SmallVectorImpl<SDValue>&Results,
13694                                            SelectionDAG &DAG) const {
13695   SDLoc dl(N);
13696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13697   switch (N->getOpcode()) {
13698   default:
13699     llvm_unreachable("Do not know how to custom type legalize this operation!");
13700   case ISD::SIGN_EXTEND_INREG:
13701   case ISD::ADDC:
13702   case ISD::ADDE:
13703   case ISD::SUBC:
13704   case ISD::SUBE:
13705     // We don't want to expand or promote these.
13706     return;
13707   case ISD::FP_TO_SINT:
13708   case ISD::FP_TO_UINT: {
13709     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13710
13711     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13712       return;
13713
13714     std::pair<SDValue,SDValue> Vals =
13715         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13716     SDValue FIST = Vals.first, StackSlot = Vals.second;
13717     if (FIST.getNode() != 0) {
13718       EVT VT = N->getValueType(0);
13719       // Return a load from the stack slot.
13720       if (StackSlot.getNode() != 0)
13721         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13722                                       MachinePointerInfo(),
13723                                       false, false, false, 0));
13724       else
13725         Results.push_back(FIST);
13726     }
13727     return;
13728   }
13729   case ISD::UINT_TO_FP: {
13730     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13731     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13732         N->getValueType(0) != MVT::v2f32)
13733       return;
13734     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13735                                  N->getOperand(0));
13736     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13737                                      MVT::f64);
13738     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13739     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13740                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13741     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13742     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13743     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13744     return;
13745   }
13746   case ISD::FP_ROUND: {
13747     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13748         return;
13749     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13750     Results.push_back(V);
13751     return;
13752   }
13753   case ISD::READCYCLECOUNTER: {
13754     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13755     SDValue TheChain = N->getOperand(0);
13756     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13757     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13758                                      rd.getValue(1));
13759     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13760                                      eax.getValue(2));
13761     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13762     SDValue Ops[] = { eax, edx };
13763     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13764                                   array_lengthof(Ops)));
13765     Results.push_back(edx.getValue(1));
13766     return;
13767   }
13768   case ISD::ATOMIC_CMP_SWAP: {
13769     EVT T = N->getValueType(0);
13770     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13771     bool Regs64bit = T == MVT::i128;
13772     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13773     SDValue cpInL, cpInH;
13774     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13775                         DAG.getConstant(0, HalfT));
13776     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13777                         DAG.getConstant(1, HalfT));
13778     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13779                              Regs64bit ? X86::RAX : X86::EAX,
13780                              cpInL, SDValue());
13781     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13782                              Regs64bit ? X86::RDX : X86::EDX,
13783                              cpInH, cpInL.getValue(1));
13784     SDValue swapInL, swapInH;
13785     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13786                           DAG.getConstant(0, HalfT));
13787     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13788                           DAG.getConstant(1, HalfT));
13789     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13790                                Regs64bit ? X86::RBX : X86::EBX,
13791                                swapInL, cpInH.getValue(1));
13792     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13793                                Regs64bit ? X86::RCX : X86::ECX,
13794                                swapInH, swapInL.getValue(1));
13795     SDValue Ops[] = { swapInH.getValue(0),
13796                       N->getOperand(1),
13797                       swapInH.getValue(1) };
13798     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13799     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13800     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13801                                   X86ISD::LCMPXCHG8_DAG;
13802     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13803                                              Ops, array_lengthof(Ops), T, MMO);
13804     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13805                                         Regs64bit ? X86::RAX : X86::EAX,
13806                                         HalfT, Result.getValue(1));
13807     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13808                                         Regs64bit ? X86::RDX : X86::EDX,
13809                                         HalfT, cpOutL.getValue(2));
13810     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13811     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13812     Results.push_back(cpOutH.getValue(1));
13813     return;
13814   }
13815   case ISD::ATOMIC_LOAD_ADD:
13816   case ISD::ATOMIC_LOAD_AND:
13817   case ISD::ATOMIC_LOAD_NAND:
13818   case ISD::ATOMIC_LOAD_OR:
13819   case ISD::ATOMIC_LOAD_SUB:
13820   case ISD::ATOMIC_LOAD_XOR:
13821   case ISD::ATOMIC_LOAD_MAX:
13822   case ISD::ATOMIC_LOAD_MIN:
13823   case ISD::ATOMIC_LOAD_UMAX:
13824   case ISD::ATOMIC_LOAD_UMIN:
13825   case ISD::ATOMIC_SWAP: {
13826     unsigned Opc;
13827     switch (N->getOpcode()) {
13828     default: llvm_unreachable("Unexpected opcode");
13829     case ISD::ATOMIC_LOAD_ADD:
13830       Opc = X86ISD::ATOMADD64_DAG;
13831       break;
13832     case ISD::ATOMIC_LOAD_AND:
13833       Opc = X86ISD::ATOMAND64_DAG;
13834       break;
13835     case ISD::ATOMIC_LOAD_NAND:
13836       Opc = X86ISD::ATOMNAND64_DAG;
13837       break;
13838     case ISD::ATOMIC_LOAD_OR:
13839       Opc = X86ISD::ATOMOR64_DAG;
13840       break;
13841     case ISD::ATOMIC_LOAD_SUB:
13842       Opc = X86ISD::ATOMSUB64_DAG;
13843       break;
13844     case ISD::ATOMIC_LOAD_XOR:
13845       Opc = X86ISD::ATOMXOR64_DAG;
13846       break;
13847     case ISD::ATOMIC_LOAD_MAX:
13848       Opc = X86ISD::ATOMMAX64_DAG;
13849       break;
13850     case ISD::ATOMIC_LOAD_MIN:
13851       Opc = X86ISD::ATOMMIN64_DAG;
13852       break;
13853     case ISD::ATOMIC_LOAD_UMAX:
13854       Opc = X86ISD::ATOMUMAX64_DAG;
13855       break;
13856     case ISD::ATOMIC_LOAD_UMIN:
13857       Opc = X86ISD::ATOMUMIN64_DAG;
13858       break;
13859     case ISD::ATOMIC_SWAP:
13860       Opc = X86ISD::ATOMSWAP64_DAG;
13861       break;
13862     }
13863     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13864     return;
13865   }
13866   case ISD::ATOMIC_LOAD:
13867     ReplaceATOMIC_LOAD(N, Results, DAG);
13868   }
13869 }
13870
13871 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13872   switch (Opcode) {
13873   default: return NULL;
13874   case X86ISD::BSF:                return "X86ISD::BSF";
13875   case X86ISD::BSR:                return "X86ISD::BSR";
13876   case X86ISD::SHLD:               return "X86ISD::SHLD";
13877   case X86ISD::SHRD:               return "X86ISD::SHRD";
13878   case X86ISD::FAND:               return "X86ISD::FAND";
13879   case X86ISD::FANDN:              return "X86ISD::FANDN";
13880   case X86ISD::FOR:                return "X86ISD::FOR";
13881   case X86ISD::FXOR:               return "X86ISD::FXOR";
13882   case X86ISD::FSRL:               return "X86ISD::FSRL";
13883   case X86ISD::FILD:               return "X86ISD::FILD";
13884   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13885   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13886   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13887   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13888   case X86ISD::FLD:                return "X86ISD::FLD";
13889   case X86ISD::FST:                return "X86ISD::FST";
13890   case X86ISD::CALL:               return "X86ISD::CALL";
13891   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13892   case X86ISD::BT:                 return "X86ISD::BT";
13893   case X86ISD::CMP:                return "X86ISD::CMP";
13894   case X86ISD::COMI:               return "X86ISD::COMI";
13895   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13896   case X86ISD::CMPM:               return "X86ISD::CMPM";
13897   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13898   case X86ISD::SETCC:              return "X86ISD::SETCC";
13899   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13900   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
13901   case X86ISD::CMOV:               return "X86ISD::CMOV";
13902   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13903   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13904   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13905   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13906   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13907   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13908   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13909   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13910   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13911   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13912   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13913   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13914   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13915   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13916   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13917   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13918   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13919   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13920   case X86ISD::HADD:               return "X86ISD::HADD";
13921   case X86ISD::HSUB:               return "X86ISD::HSUB";
13922   case X86ISD::FHADD:              return "X86ISD::FHADD";
13923   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13924   case X86ISD::UMAX:               return "X86ISD::UMAX";
13925   case X86ISD::UMIN:               return "X86ISD::UMIN";
13926   case X86ISD::SMAX:               return "X86ISD::SMAX";
13927   case X86ISD::SMIN:               return "X86ISD::SMIN";
13928   case X86ISD::FMAX:               return "X86ISD::FMAX";
13929   case X86ISD::FMIN:               return "X86ISD::FMIN";
13930   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13931   case X86ISD::FMINC:              return "X86ISD::FMINC";
13932   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13933   case X86ISD::FRCP:               return "X86ISD::FRCP";
13934   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13935   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13936   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13937   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13938   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13939   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13940   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13941   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13942   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13943   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13944   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13945   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13946   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13947   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13948   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13949   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13950   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13951   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13952   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13953   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13954   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13955   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13956   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
13957   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
13958   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
13959   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13960   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13961   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13962   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13963   case X86ISD::VSHL:               return "X86ISD::VSHL";
13964   case X86ISD::VSRL:               return "X86ISD::VSRL";
13965   case X86ISD::VSRA:               return "X86ISD::VSRA";
13966   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13967   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13968   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13969   case X86ISD::CMPP:               return "X86ISD::CMPP";
13970   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13971   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13972   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
13973   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
13974   case X86ISD::ADD:                return "X86ISD::ADD";
13975   case X86ISD::SUB:                return "X86ISD::SUB";
13976   case X86ISD::ADC:                return "X86ISD::ADC";
13977   case X86ISD::SBB:                return "X86ISD::SBB";
13978   case X86ISD::SMUL:               return "X86ISD::SMUL";
13979   case X86ISD::UMUL:               return "X86ISD::UMUL";
13980   case X86ISD::INC:                return "X86ISD::INC";
13981   case X86ISD::DEC:                return "X86ISD::DEC";
13982   case X86ISD::OR:                 return "X86ISD::OR";
13983   case X86ISD::XOR:                return "X86ISD::XOR";
13984   case X86ISD::AND:                return "X86ISD::AND";
13985   case X86ISD::BLSI:               return "X86ISD::BLSI";
13986   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13987   case X86ISD::BLSR:               return "X86ISD::BLSR";
13988   case X86ISD::BZHI:               return "X86ISD::BZHI";
13989   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
13990   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13991   case X86ISD::PTEST:              return "X86ISD::PTEST";
13992   case X86ISD::TESTP:              return "X86ISD::TESTP";
13993   case X86ISD::TESTM:              return "X86ISD::TESTM";
13994   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
13995   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13996   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13997   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13998   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13999   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14000   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14001   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14002   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14003   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14004   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14005   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14006   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14007   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14008   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14009   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14010   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14011   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14012   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14013   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14014   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14015   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14016   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14017   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14018   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14019   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14020   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14021   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14022   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14023   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14024   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14025   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14026   case X86ISD::SAHF:               return "X86ISD::SAHF";
14027   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14028   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14029   case X86ISD::FMADD:              return "X86ISD::FMADD";
14030   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14031   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14032   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14033   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14034   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14035   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14036   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14037   case X86ISD::XTEST:              return "X86ISD::XTEST";
14038   }
14039 }
14040
14041 // isLegalAddressingMode - Return true if the addressing mode represented
14042 // by AM is legal for this target, for a load/store of the specified type.
14043 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14044                                               Type *Ty) const {
14045   // X86 supports extremely general addressing modes.
14046   CodeModel::Model M = getTargetMachine().getCodeModel();
14047   Reloc::Model R = getTargetMachine().getRelocationModel();
14048
14049   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14050   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14051     return false;
14052
14053   if (AM.BaseGV) {
14054     unsigned GVFlags =
14055       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14056
14057     // If a reference to this global requires an extra load, we can't fold it.
14058     if (isGlobalStubReference(GVFlags))
14059       return false;
14060
14061     // If BaseGV requires a register for the PIC base, we cannot also have a
14062     // BaseReg specified.
14063     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14064       return false;
14065
14066     // If lower 4G is not available, then we must use rip-relative addressing.
14067     if ((M != CodeModel::Small || R != Reloc::Static) &&
14068         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14069       return false;
14070   }
14071
14072   switch (AM.Scale) {
14073   case 0:
14074   case 1:
14075   case 2:
14076   case 4:
14077   case 8:
14078     // These scales always work.
14079     break;
14080   case 3:
14081   case 5:
14082   case 9:
14083     // These scales are formed with basereg+scalereg.  Only accept if there is
14084     // no basereg yet.
14085     if (AM.HasBaseReg)
14086       return false;
14087     break;
14088   default:  // Other stuff never works.
14089     return false;
14090   }
14091
14092   return true;
14093 }
14094
14095 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14096   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14097     return false;
14098   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14099   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14100   return NumBits1 > NumBits2;
14101 }
14102
14103 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14104   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14105     return false;
14106
14107   if (!isTypeLegal(EVT::getEVT(Ty1)))
14108     return false;
14109
14110   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14111
14112   // Assuming the caller doesn't have a zeroext or signext return parameter,
14113   // truncation all the way down to i1 is valid.
14114   return true;
14115 }
14116
14117 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14118   return isInt<32>(Imm);
14119 }
14120
14121 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14122   // Can also use sub to handle negated immediates.
14123   return isInt<32>(Imm);
14124 }
14125
14126 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14127   if (!VT1.isInteger() || !VT2.isInteger())
14128     return false;
14129   unsigned NumBits1 = VT1.getSizeInBits();
14130   unsigned NumBits2 = VT2.getSizeInBits();
14131   return NumBits1 > NumBits2;
14132 }
14133
14134 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14135   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14136   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14137 }
14138
14139 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14140   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14141   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14142 }
14143
14144 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14145   EVT VT1 = Val.getValueType();
14146   if (isZExtFree(VT1, VT2))
14147     return true;
14148
14149   if (Val.getOpcode() != ISD::LOAD)
14150     return false;
14151
14152   if (!VT1.isSimple() || !VT1.isInteger() ||
14153       !VT2.isSimple() || !VT2.isInteger())
14154     return false;
14155
14156   switch (VT1.getSimpleVT().SimpleTy) {
14157   default: break;
14158   case MVT::i8:
14159   case MVT::i16:
14160   case MVT::i32:
14161     // X86 has 8, 16, and 32-bit zero-extending loads.
14162     return true;
14163   }
14164
14165   return false;
14166 }
14167
14168 bool
14169 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14170   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14171     return false;
14172
14173   VT = VT.getScalarType();
14174
14175   if (!VT.isSimple())
14176     return false;
14177
14178   switch (VT.getSimpleVT().SimpleTy) {
14179   case MVT::f32:
14180   case MVT::f64:
14181     return true;
14182   default:
14183     break;
14184   }
14185
14186   return false;
14187 }
14188
14189 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14190   // i16 instructions are longer (0x66 prefix) and potentially slower.
14191   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14192 }
14193
14194 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14195 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14196 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14197 /// are assumed to be legal.
14198 bool
14199 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14200                                       EVT VT) const {
14201   if (!VT.isSimple())
14202     return false;
14203
14204   MVT SVT = VT.getSimpleVT();
14205
14206   // Very little shuffling can be done for 64-bit vectors right now.
14207   if (VT.getSizeInBits() == 64)
14208     return false;
14209
14210   // FIXME: pshufb, blends, shifts.
14211   return (SVT.getVectorNumElements() == 2 ||
14212           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14213           isMOVLMask(M, SVT) ||
14214           isSHUFPMask(M, SVT) ||
14215           isPSHUFDMask(M, SVT) ||
14216           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14217           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14218           isPALIGNRMask(M, SVT, Subtarget) ||
14219           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14220           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14221           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14222           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14223 }
14224
14225 bool
14226 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14227                                           EVT VT) const {
14228   if (!VT.isSimple())
14229     return false;
14230
14231   MVT SVT = VT.getSimpleVT();
14232   unsigned NumElts = SVT.getVectorNumElements();
14233   // FIXME: This collection of masks seems suspect.
14234   if (NumElts == 2)
14235     return true;
14236   if (NumElts == 4 && SVT.is128BitVector()) {
14237     return (isMOVLMask(Mask, SVT)  ||
14238             isCommutedMOVLMask(Mask, SVT, true) ||
14239             isSHUFPMask(Mask, SVT) ||
14240             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14241   }
14242   return false;
14243 }
14244
14245 //===----------------------------------------------------------------------===//
14246 //                           X86 Scheduler Hooks
14247 //===----------------------------------------------------------------------===//
14248
14249 /// Utility function to emit xbegin specifying the start of an RTM region.
14250 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14251                                      const TargetInstrInfo *TII) {
14252   DebugLoc DL = MI->getDebugLoc();
14253
14254   const BasicBlock *BB = MBB->getBasicBlock();
14255   MachineFunction::iterator I = MBB;
14256   ++I;
14257
14258   // For the v = xbegin(), we generate
14259   //
14260   // thisMBB:
14261   //  xbegin sinkMBB
14262   //
14263   // mainMBB:
14264   //  eax = -1
14265   //
14266   // sinkMBB:
14267   //  v = eax
14268
14269   MachineBasicBlock *thisMBB = MBB;
14270   MachineFunction *MF = MBB->getParent();
14271   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14272   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14273   MF->insert(I, mainMBB);
14274   MF->insert(I, sinkMBB);
14275
14276   // Transfer the remainder of BB and its successor edges to sinkMBB.
14277   sinkMBB->splice(sinkMBB->begin(), MBB,
14278                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14279   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14280
14281   // thisMBB:
14282   //  xbegin sinkMBB
14283   //  # fallthrough to mainMBB
14284   //  # abortion to sinkMBB
14285   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14286   thisMBB->addSuccessor(mainMBB);
14287   thisMBB->addSuccessor(sinkMBB);
14288
14289   // mainMBB:
14290   //  EAX = -1
14291   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14292   mainMBB->addSuccessor(sinkMBB);
14293
14294   // sinkMBB:
14295   // EAX is live into the sinkMBB
14296   sinkMBB->addLiveIn(X86::EAX);
14297   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14298           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14299     .addReg(X86::EAX);
14300
14301   MI->eraseFromParent();
14302   return sinkMBB;
14303 }
14304
14305 // Get CMPXCHG opcode for the specified data type.
14306 static unsigned getCmpXChgOpcode(EVT VT) {
14307   switch (VT.getSimpleVT().SimpleTy) {
14308   case MVT::i8:  return X86::LCMPXCHG8;
14309   case MVT::i16: return X86::LCMPXCHG16;
14310   case MVT::i32: return X86::LCMPXCHG32;
14311   case MVT::i64: return X86::LCMPXCHG64;
14312   default:
14313     break;
14314   }
14315   llvm_unreachable("Invalid operand size!");
14316 }
14317
14318 // Get LOAD opcode for the specified data type.
14319 static unsigned getLoadOpcode(EVT VT) {
14320   switch (VT.getSimpleVT().SimpleTy) {
14321   case MVT::i8:  return X86::MOV8rm;
14322   case MVT::i16: return X86::MOV16rm;
14323   case MVT::i32: return X86::MOV32rm;
14324   case MVT::i64: return X86::MOV64rm;
14325   default:
14326     break;
14327   }
14328   llvm_unreachable("Invalid operand size!");
14329 }
14330
14331 // Get opcode of the non-atomic one from the specified atomic instruction.
14332 static unsigned getNonAtomicOpcode(unsigned Opc) {
14333   switch (Opc) {
14334   case X86::ATOMAND8:  return X86::AND8rr;
14335   case X86::ATOMAND16: return X86::AND16rr;
14336   case X86::ATOMAND32: return X86::AND32rr;
14337   case X86::ATOMAND64: return X86::AND64rr;
14338   case X86::ATOMOR8:   return X86::OR8rr;
14339   case X86::ATOMOR16:  return X86::OR16rr;
14340   case X86::ATOMOR32:  return X86::OR32rr;
14341   case X86::ATOMOR64:  return X86::OR64rr;
14342   case X86::ATOMXOR8:  return X86::XOR8rr;
14343   case X86::ATOMXOR16: return X86::XOR16rr;
14344   case X86::ATOMXOR32: return X86::XOR32rr;
14345   case X86::ATOMXOR64: return X86::XOR64rr;
14346   }
14347   llvm_unreachable("Unhandled atomic-load-op opcode!");
14348 }
14349
14350 // Get opcode of the non-atomic one from the specified atomic instruction with
14351 // extra opcode.
14352 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14353                                                unsigned &ExtraOpc) {
14354   switch (Opc) {
14355   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14356   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14357   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14358   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14359   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14360   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14361   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14362   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14363   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14364   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14365   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14366   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14367   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14368   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14369   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14370   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14371   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14372   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14373   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14374   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14375   }
14376   llvm_unreachable("Unhandled atomic-load-op opcode!");
14377 }
14378
14379 // Get opcode of the non-atomic one from the specified atomic instruction for
14380 // 64-bit data type on 32-bit target.
14381 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14382   switch (Opc) {
14383   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14384   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14385   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14386   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14387   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14388   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14389   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14390   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14391   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14392   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14393   }
14394   llvm_unreachable("Unhandled atomic-load-op opcode!");
14395 }
14396
14397 // Get opcode of the non-atomic one from the specified atomic instruction for
14398 // 64-bit data type on 32-bit target with extra opcode.
14399 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14400                                                    unsigned &HiOpc,
14401                                                    unsigned &ExtraOpc) {
14402   switch (Opc) {
14403   case X86::ATOMNAND6432:
14404     ExtraOpc = X86::NOT32r;
14405     HiOpc = X86::AND32rr;
14406     return X86::AND32rr;
14407   }
14408   llvm_unreachable("Unhandled atomic-load-op opcode!");
14409 }
14410
14411 // Get pseudo CMOV opcode from the specified data type.
14412 static unsigned getPseudoCMOVOpc(EVT VT) {
14413   switch (VT.getSimpleVT().SimpleTy) {
14414   case MVT::i8:  return X86::CMOV_GR8;
14415   case MVT::i16: return X86::CMOV_GR16;
14416   case MVT::i32: return X86::CMOV_GR32;
14417   default:
14418     break;
14419   }
14420   llvm_unreachable("Unknown CMOV opcode!");
14421 }
14422
14423 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14424 // They will be translated into a spin-loop or compare-exchange loop from
14425 //
14426 //    ...
14427 //    dst = atomic-fetch-op MI.addr, MI.val
14428 //    ...
14429 //
14430 // to
14431 //
14432 //    ...
14433 //    t1 = LOAD MI.addr
14434 // loop:
14435 //    t4 = phi(t1, t3 / loop)
14436 //    t2 = OP MI.val, t4
14437 //    EAX = t4
14438 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14439 //    t3 = EAX
14440 //    JNE loop
14441 // sink:
14442 //    dst = t3
14443 //    ...
14444 MachineBasicBlock *
14445 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14446                                        MachineBasicBlock *MBB) const {
14447   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14448   DebugLoc DL = MI->getDebugLoc();
14449
14450   MachineFunction *MF = MBB->getParent();
14451   MachineRegisterInfo &MRI = MF->getRegInfo();
14452
14453   const BasicBlock *BB = MBB->getBasicBlock();
14454   MachineFunction::iterator I = MBB;
14455   ++I;
14456
14457   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14458          "Unexpected number of operands");
14459
14460   assert(MI->hasOneMemOperand() &&
14461          "Expected atomic-load-op to have one memoperand");
14462
14463   // Memory Reference
14464   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14465   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14466
14467   unsigned DstReg, SrcReg;
14468   unsigned MemOpndSlot;
14469
14470   unsigned CurOp = 0;
14471
14472   DstReg = MI->getOperand(CurOp++).getReg();
14473   MemOpndSlot = CurOp;
14474   CurOp += X86::AddrNumOperands;
14475   SrcReg = MI->getOperand(CurOp++).getReg();
14476
14477   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14478   MVT::SimpleValueType VT = *RC->vt_begin();
14479   unsigned t1 = MRI.createVirtualRegister(RC);
14480   unsigned t2 = MRI.createVirtualRegister(RC);
14481   unsigned t3 = MRI.createVirtualRegister(RC);
14482   unsigned t4 = MRI.createVirtualRegister(RC);
14483   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14484
14485   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14486   unsigned LOADOpc = getLoadOpcode(VT);
14487
14488   // For the atomic load-arith operator, we generate
14489   //
14490   //  thisMBB:
14491   //    t1 = LOAD [MI.addr]
14492   //  mainMBB:
14493   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14494   //    t1 = OP MI.val, EAX
14495   //    EAX = t4
14496   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14497   //    t3 = EAX
14498   //    JNE mainMBB
14499   //  sinkMBB:
14500   //    dst = t3
14501
14502   MachineBasicBlock *thisMBB = MBB;
14503   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14504   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14505   MF->insert(I, mainMBB);
14506   MF->insert(I, sinkMBB);
14507
14508   MachineInstrBuilder MIB;
14509
14510   // Transfer the remainder of BB and its successor edges to sinkMBB.
14511   sinkMBB->splice(sinkMBB->begin(), MBB,
14512                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14513   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14514
14515   // thisMBB:
14516   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14517   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14518     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14519     if (NewMO.isReg())
14520       NewMO.setIsKill(false);
14521     MIB.addOperand(NewMO);
14522   }
14523   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14524     unsigned flags = (*MMOI)->getFlags();
14525     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14526     MachineMemOperand *MMO =
14527       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14528                                (*MMOI)->getSize(),
14529                                (*MMOI)->getBaseAlignment(),
14530                                (*MMOI)->getTBAAInfo(),
14531                                (*MMOI)->getRanges());
14532     MIB.addMemOperand(MMO);
14533   }
14534
14535   thisMBB->addSuccessor(mainMBB);
14536
14537   // mainMBB:
14538   MachineBasicBlock *origMainMBB = mainMBB;
14539
14540   // Add a PHI.
14541   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14542                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14543
14544   unsigned Opc = MI->getOpcode();
14545   switch (Opc) {
14546   default:
14547     llvm_unreachable("Unhandled atomic-load-op opcode!");
14548   case X86::ATOMAND8:
14549   case X86::ATOMAND16:
14550   case X86::ATOMAND32:
14551   case X86::ATOMAND64:
14552   case X86::ATOMOR8:
14553   case X86::ATOMOR16:
14554   case X86::ATOMOR32:
14555   case X86::ATOMOR64:
14556   case X86::ATOMXOR8:
14557   case X86::ATOMXOR16:
14558   case X86::ATOMXOR32:
14559   case X86::ATOMXOR64: {
14560     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14561     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14562       .addReg(t4);
14563     break;
14564   }
14565   case X86::ATOMNAND8:
14566   case X86::ATOMNAND16:
14567   case X86::ATOMNAND32:
14568   case X86::ATOMNAND64: {
14569     unsigned Tmp = MRI.createVirtualRegister(RC);
14570     unsigned NOTOpc;
14571     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14572     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14573       .addReg(t4);
14574     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14575     break;
14576   }
14577   case X86::ATOMMAX8:
14578   case X86::ATOMMAX16:
14579   case X86::ATOMMAX32:
14580   case X86::ATOMMAX64:
14581   case X86::ATOMMIN8:
14582   case X86::ATOMMIN16:
14583   case X86::ATOMMIN32:
14584   case X86::ATOMMIN64:
14585   case X86::ATOMUMAX8:
14586   case X86::ATOMUMAX16:
14587   case X86::ATOMUMAX32:
14588   case X86::ATOMUMAX64:
14589   case X86::ATOMUMIN8:
14590   case X86::ATOMUMIN16:
14591   case X86::ATOMUMIN32:
14592   case X86::ATOMUMIN64: {
14593     unsigned CMPOpc;
14594     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14595
14596     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14597       .addReg(SrcReg)
14598       .addReg(t4);
14599
14600     if (Subtarget->hasCMov()) {
14601       if (VT != MVT::i8) {
14602         // Native support
14603         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14604           .addReg(SrcReg)
14605           .addReg(t4);
14606       } else {
14607         // Promote i8 to i32 to use CMOV32
14608         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14609         const TargetRegisterClass *RC32 =
14610           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14611         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14612         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14613         unsigned Tmp = MRI.createVirtualRegister(RC32);
14614
14615         unsigned Undef = MRI.createVirtualRegister(RC32);
14616         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14617
14618         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14619           .addReg(Undef)
14620           .addReg(SrcReg)
14621           .addImm(X86::sub_8bit);
14622         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14623           .addReg(Undef)
14624           .addReg(t4)
14625           .addImm(X86::sub_8bit);
14626
14627         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14628           .addReg(SrcReg32)
14629           .addReg(AccReg32);
14630
14631         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14632           .addReg(Tmp, 0, X86::sub_8bit);
14633       }
14634     } else {
14635       // Use pseudo select and lower them.
14636       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14637              "Invalid atomic-load-op transformation!");
14638       unsigned SelOpc = getPseudoCMOVOpc(VT);
14639       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14640       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14641       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14642               .addReg(SrcReg).addReg(t4)
14643               .addImm(CC);
14644       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14645       // Replace the original PHI node as mainMBB is changed after CMOV
14646       // lowering.
14647       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14648         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14649       Phi->eraseFromParent();
14650     }
14651     break;
14652   }
14653   }
14654
14655   // Copy PhyReg back from virtual register.
14656   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14657     .addReg(t4);
14658
14659   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14660   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14661     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14662     if (NewMO.isReg())
14663       NewMO.setIsKill(false);
14664     MIB.addOperand(NewMO);
14665   }
14666   MIB.addReg(t2);
14667   MIB.setMemRefs(MMOBegin, MMOEnd);
14668
14669   // Copy PhyReg back to virtual register.
14670   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14671     .addReg(PhyReg);
14672
14673   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14674
14675   mainMBB->addSuccessor(origMainMBB);
14676   mainMBB->addSuccessor(sinkMBB);
14677
14678   // sinkMBB:
14679   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14680           TII->get(TargetOpcode::COPY), DstReg)
14681     .addReg(t3);
14682
14683   MI->eraseFromParent();
14684   return sinkMBB;
14685 }
14686
14687 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14688 // instructions. They will be translated into a spin-loop or compare-exchange
14689 // loop from
14690 //
14691 //    ...
14692 //    dst = atomic-fetch-op MI.addr, MI.val
14693 //    ...
14694 //
14695 // to
14696 //
14697 //    ...
14698 //    t1L = LOAD [MI.addr + 0]
14699 //    t1H = LOAD [MI.addr + 4]
14700 // loop:
14701 //    t4L = phi(t1L, t3L / loop)
14702 //    t4H = phi(t1H, t3H / loop)
14703 //    t2L = OP MI.val.lo, t4L
14704 //    t2H = OP MI.val.hi, t4H
14705 //    EAX = t4L
14706 //    EDX = t4H
14707 //    EBX = t2L
14708 //    ECX = t2H
14709 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14710 //    t3L = EAX
14711 //    t3H = EDX
14712 //    JNE loop
14713 // sink:
14714 //    dstL = t3L
14715 //    dstH = t3H
14716 //    ...
14717 MachineBasicBlock *
14718 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14719                                            MachineBasicBlock *MBB) const {
14720   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14721   DebugLoc DL = MI->getDebugLoc();
14722
14723   MachineFunction *MF = MBB->getParent();
14724   MachineRegisterInfo &MRI = MF->getRegInfo();
14725
14726   const BasicBlock *BB = MBB->getBasicBlock();
14727   MachineFunction::iterator I = MBB;
14728   ++I;
14729
14730   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14731          "Unexpected number of operands");
14732
14733   assert(MI->hasOneMemOperand() &&
14734          "Expected atomic-load-op32 to have one memoperand");
14735
14736   // Memory Reference
14737   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14738   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14739
14740   unsigned DstLoReg, DstHiReg;
14741   unsigned SrcLoReg, SrcHiReg;
14742   unsigned MemOpndSlot;
14743
14744   unsigned CurOp = 0;
14745
14746   DstLoReg = MI->getOperand(CurOp++).getReg();
14747   DstHiReg = MI->getOperand(CurOp++).getReg();
14748   MemOpndSlot = CurOp;
14749   CurOp += X86::AddrNumOperands;
14750   SrcLoReg = MI->getOperand(CurOp++).getReg();
14751   SrcHiReg = MI->getOperand(CurOp++).getReg();
14752
14753   const TargetRegisterClass *RC = &X86::GR32RegClass;
14754   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14755
14756   unsigned t1L = MRI.createVirtualRegister(RC);
14757   unsigned t1H = MRI.createVirtualRegister(RC);
14758   unsigned t2L = MRI.createVirtualRegister(RC);
14759   unsigned t2H = MRI.createVirtualRegister(RC);
14760   unsigned t3L = MRI.createVirtualRegister(RC);
14761   unsigned t3H = MRI.createVirtualRegister(RC);
14762   unsigned t4L = MRI.createVirtualRegister(RC);
14763   unsigned t4H = MRI.createVirtualRegister(RC);
14764
14765   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14766   unsigned LOADOpc = X86::MOV32rm;
14767
14768   // For the atomic load-arith operator, we generate
14769   //
14770   //  thisMBB:
14771   //    t1L = LOAD [MI.addr + 0]
14772   //    t1H = LOAD [MI.addr + 4]
14773   //  mainMBB:
14774   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14775   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14776   //    t2L = OP MI.val.lo, t4L
14777   //    t2H = OP MI.val.hi, t4H
14778   //    EBX = t2L
14779   //    ECX = t2H
14780   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14781   //    t3L = EAX
14782   //    t3H = EDX
14783   //    JNE loop
14784   //  sinkMBB:
14785   //    dstL = t3L
14786   //    dstH = t3H
14787
14788   MachineBasicBlock *thisMBB = MBB;
14789   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14790   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14791   MF->insert(I, mainMBB);
14792   MF->insert(I, sinkMBB);
14793
14794   MachineInstrBuilder MIB;
14795
14796   // Transfer the remainder of BB and its successor edges to sinkMBB.
14797   sinkMBB->splice(sinkMBB->begin(), MBB,
14798                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14799   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14800
14801   // thisMBB:
14802   // Lo
14803   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14804   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14805     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14806     if (NewMO.isReg())
14807       NewMO.setIsKill(false);
14808     MIB.addOperand(NewMO);
14809   }
14810   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14811     unsigned flags = (*MMOI)->getFlags();
14812     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14813     MachineMemOperand *MMO =
14814       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14815                                (*MMOI)->getSize(),
14816                                (*MMOI)->getBaseAlignment(),
14817                                (*MMOI)->getTBAAInfo(),
14818                                (*MMOI)->getRanges());
14819     MIB.addMemOperand(MMO);
14820   };
14821   MachineInstr *LowMI = MIB;
14822
14823   // Hi
14824   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14825   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14826     if (i == X86::AddrDisp) {
14827       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14828     } else {
14829       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14830       if (NewMO.isReg())
14831         NewMO.setIsKill(false);
14832       MIB.addOperand(NewMO);
14833     }
14834   }
14835   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14836
14837   thisMBB->addSuccessor(mainMBB);
14838
14839   // mainMBB:
14840   MachineBasicBlock *origMainMBB = mainMBB;
14841
14842   // Add PHIs.
14843   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14844                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14845   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14846                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14847
14848   unsigned Opc = MI->getOpcode();
14849   switch (Opc) {
14850   default:
14851     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14852   case X86::ATOMAND6432:
14853   case X86::ATOMOR6432:
14854   case X86::ATOMXOR6432:
14855   case X86::ATOMADD6432:
14856   case X86::ATOMSUB6432: {
14857     unsigned HiOpc;
14858     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14859     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14860       .addReg(SrcLoReg);
14861     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14862       .addReg(SrcHiReg);
14863     break;
14864   }
14865   case X86::ATOMNAND6432: {
14866     unsigned HiOpc, NOTOpc;
14867     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14868     unsigned TmpL = MRI.createVirtualRegister(RC);
14869     unsigned TmpH = MRI.createVirtualRegister(RC);
14870     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14871       .addReg(t4L);
14872     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14873       .addReg(t4H);
14874     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14875     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14876     break;
14877   }
14878   case X86::ATOMMAX6432:
14879   case X86::ATOMMIN6432:
14880   case X86::ATOMUMAX6432:
14881   case X86::ATOMUMIN6432: {
14882     unsigned HiOpc;
14883     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14884     unsigned cL = MRI.createVirtualRegister(RC8);
14885     unsigned cH = MRI.createVirtualRegister(RC8);
14886     unsigned cL32 = MRI.createVirtualRegister(RC);
14887     unsigned cH32 = MRI.createVirtualRegister(RC);
14888     unsigned cc = MRI.createVirtualRegister(RC);
14889     // cl := cmp src_lo, lo
14890     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14891       .addReg(SrcLoReg).addReg(t4L);
14892     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14893     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14894     // ch := cmp src_hi, hi
14895     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14896       .addReg(SrcHiReg).addReg(t4H);
14897     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14898     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14899     // cc := if (src_hi == hi) ? cl : ch;
14900     if (Subtarget->hasCMov()) {
14901       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14902         .addReg(cH32).addReg(cL32);
14903     } else {
14904       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14905               .addReg(cH32).addReg(cL32)
14906               .addImm(X86::COND_E);
14907       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14908     }
14909     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14910     if (Subtarget->hasCMov()) {
14911       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14912         .addReg(SrcLoReg).addReg(t4L);
14913       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14914         .addReg(SrcHiReg).addReg(t4H);
14915     } else {
14916       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14917               .addReg(SrcLoReg).addReg(t4L)
14918               .addImm(X86::COND_NE);
14919       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14920       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14921       // 2nd CMOV lowering.
14922       mainMBB->addLiveIn(X86::EFLAGS);
14923       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14924               .addReg(SrcHiReg).addReg(t4H)
14925               .addImm(X86::COND_NE);
14926       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14927       // Replace the original PHI node as mainMBB is changed after CMOV
14928       // lowering.
14929       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14930         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14931       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14932         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14933       PhiL->eraseFromParent();
14934       PhiH->eraseFromParent();
14935     }
14936     break;
14937   }
14938   case X86::ATOMSWAP6432: {
14939     unsigned HiOpc;
14940     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14941     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14942     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14943     break;
14944   }
14945   }
14946
14947   // Copy EDX:EAX back from HiReg:LoReg
14948   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14949   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14950   // Copy ECX:EBX from t1H:t1L
14951   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14952   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14953
14954   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14955   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14956     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14957     if (NewMO.isReg())
14958       NewMO.setIsKill(false);
14959     MIB.addOperand(NewMO);
14960   }
14961   MIB.setMemRefs(MMOBegin, MMOEnd);
14962
14963   // Copy EDX:EAX back to t3H:t3L
14964   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14965   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14966
14967   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14968
14969   mainMBB->addSuccessor(origMainMBB);
14970   mainMBB->addSuccessor(sinkMBB);
14971
14972   // sinkMBB:
14973   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14974           TII->get(TargetOpcode::COPY), DstLoReg)
14975     .addReg(t3L);
14976   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14977           TII->get(TargetOpcode::COPY), DstHiReg)
14978     .addReg(t3H);
14979
14980   MI->eraseFromParent();
14981   return sinkMBB;
14982 }
14983
14984 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14985 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14986 // in the .td file.
14987 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14988                                        const TargetInstrInfo *TII) {
14989   unsigned Opc;
14990   switch (MI->getOpcode()) {
14991   default: llvm_unreachable("illegal opcode!");
14992   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14993   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14994   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14995   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14996   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14997   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14998   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14999   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15000   }
15001
15002   DebugLoc dl = MI->getDebugLoc();
15003   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15004
15005   unsigned NumArgs = MI->getNumOperands();
15006   for (unsigned i = 1; i < NumArgs; ++i) {
15007     MachineOperand &Op = MI->getOperand(i);
15008     if (!(Op.isReg() && Op.isImplicit()))
15009       MIB.addOperand(Op);
15010   }
15011   if (MI->hasOneMemOperand())
15012     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15013
15014   BuildMI(*BB, MI, dl,
15015     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15016     .addReg(X86::XMM0);
15017
15018   MI->eraseFromParent();
15019   return BB;
15020 }
15021
15022 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15023 // defs in an instruction pattern
15024 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15025                                        const TargetInstrInfo *TII) {
15026   unsigned Opc;
15027   switch (MI->getOpcode()) {
15028   default: llvm_unreachable("illegal opcode!");
15029   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15030   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15031   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15032   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15033   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15034   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15035   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15036   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15037   }
15038
15039   DebugLoc dl = MI->getDebugLoc();
15040   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15041
15042   unsigned NumArgs = MI->getNumOperands(); // remove the results
15043   for (unsigned i = 1; i < NumArgs; ++i) {
15044     MachineOperand &Op = MI->getOperand(i);
15045     if (!(Op.isReg() && Op.isImplicit()))
15046       MIB.addOperand(Op);
15047   }
15048   if (MI->hasOneMemOperand())
15049     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15050
15051   BuildMI(*BB, MI, dl,
15052     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15053     .addReg(X86::ECX);
15054
15055   MI->eraseFromParent();
15056   return BB;
15057 }
15058
15059 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15060                                        const TargetInstrInfo *TII,
15061                                        const X86Subtarget* Subtarget) {
15062   DebugLoc dl = MI->getDebugLoc();
15063
15064   // Address into RAX/EAX, other two args into ECX, EDX.
15065   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15066   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15067   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15068   for (int i = 0; i < X86::AddrNumOperands; ++i)
15069     MIB.addOperand(MI->getOperand(i));
15070
15071   unsigned ValOps = X86::AddrNumOperands;
15072   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15073     .addReg(MI->getOperand(ValOps).getReg());
15074   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15075     .addReg(MI->getOperand(ValOps+1).getReg());
15076
15077   // The instruction doesn't actually take any operands though.
15078   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15079
15080   MI->eraseFromParent(); // The pseudo is gone now.
15081   return BB;
15082 }
15083
15084 MachineBasicBlock *
15085 X86TargetLowering::EmitVAARG64WithCustomInserter(
15086                    MachineInstr *MI,
15087                    MachineBasicBlock *MBB) const {
15088   // Emit va_arg instruction on X86-64.
15089
15090   // Operands to this pseudo-instruction:
15091   // 0  ) Output        : destination address (reg)
15092   // 1-5) Input         : va_list address (addr, i64mem)
15093   // 6  ) ArgSize       : Size (in bytes) of vararg type
15094   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15095   // 8  ) Align         : Alignment of type
15096   // 9  ) EFLAGS (implicit-def)
15097
15098   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15099   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15100
15101   unsigned DestReg = MI->getOperand(0).getReg();
15102   MachineOperand &Base = MI->getOperand(1);
15103   MachineOperand &Scale = MI->getOperand(2);
15104   MachineOperand &Index = MI->getOperand(3);
15105   MachineOperand &Disp = MI->getOperand(4);
15106   MachineOperand &Segment = MI->getOperand(5);
15107   unsigned ArgSize = MI->getOperand(6).getImm();
15108   unsigned ArgMode = MI->getOperand(7).getImm();
15109   unsigned Align = MI->getOperand(8).getImm();
15110
15111   // Memory Reference
15112   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15113   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15114   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15115
15116   // Machine Information
15117   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15118   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15119   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15120   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15121   DebugLoc DL = MI->getDebugLoc();
15122
15123   // struct va_list {
15124   //   i32   gp_offset
15125   //   i32   fp_offset
15126   //   i64   overflow_area (address)
15127   //   i64   reg_save_area (address)
15128   // }
15129   // sizeof(va_list) = 24
15130   // alignment(va_list) = 8
15131
15132   unsigned TotalNumIntRegs = 6;
15133   unsigned TotalNumXMMRegs = 8;
15134   bool UseGPOffset = (ArgMode == 1);
15135   bool UseFPOffset = (ArgMode == 2);
15136   unsigned MaxOffset = TotalNumIntRegs * 8 +
15137                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15138
15139   /* Align ArgSize to a multiple of 8 */
15140   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15141   bool NeedsAlign = (Align > 8);
15142
15143   MachineBasicBlock *thisMBB = MBB;
15144   MachineBasicBlock *overflowMBB;
15145   MachineBasicBlock *offsetMBB;
15146   MachineBasicBlock *endMBB;
15147
15148   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15149   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15150   unsigned OffsetReg = 0;
15151
15152   if (!UseGPOffset && !UseFPOffset) {
15153     // If we only pull from the overflow region, we don't create a branch.
15154     // We don't need to alter control flow.
15155     OffsetDestReg = 0; // unused
15156     OverflowDestReg = DestReg;
15157
15158     offsetMBB = NULL;
15159     overflowMBB = thisMBB;
15160     endMBB = thisMBB;
15161   } else {
15162     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15163     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15164     // If not, pull from overflow_area. (branch to overflowMBB)
15165     //
15166     //       thisMBB
15167     //         |     .
15168     //         |        .
15169     //     offsetMBB   overflowMBB
15170     //         |        .
15171     //         |     .
15172     //        endMBB
15173
15174     // Registers for the PHI in endMBB
15175     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15176     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15177
15178     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15179     MachineFunction *MF = MBB->getParent();
15180     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15181     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15182     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15183
15184     MachineFunction::iterator MBBIter = MBB;
15185     ++MBBIter;
15186
15187     // Insert the new basic blocks
15188     MF->insert(MBBIter, offsetMBB);
15189     MF->insert(MBBIter, overflowMBB);
15190     MF->insert(MBBIter, endMBB);
15191
15192     // Transfer the remainder of MBB and its successor edges to endMBB.
15193     endMBB->splice(endMBB->begin(), thisMBB,
15194                     llvm::next(MachineBasicBlock::iterator(MI)),
15195                     thisMBB->end());
15196     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15197
15198     // Make offsetMBB and overflowMBB successors of thisMBB
15199     thisMBB->addSuccessor(offsetMBB);
15200     thisMBB->addSuccessor(overflowMBB);
15201
15202     // endMBB is a successor of both offsetMBB and overflowMBB
15203     offsetMBB->addSuccessor(endMBB);
15204     overflowMBB->addSuccessor(endMBB);
15205
15206     // Load the offset value into a register
15207     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15208     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15209       .addOperand(Base)
15210       .addOperand(Scale)
15211       .addOperand(Index)
15212       .addDisp(Disp, UseFPOffset ? 4 : 0)
15213       .addOperand(Segment)
15214       .setMemRefs(MMOBegin, MMOEnd);
15215
15216     // Check if there is enough room left to pull this argument.
15217     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15218       .addReg(OffsetReg)
15219       .addImm(MaxOffset + 8 - ArgSizeA8);
15220
15221     // Branch to "overflowMBB" if offset >= max
15222     // Fall through to "offsetMBB" otherwise
15223     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15224       .addMBB(overflowMBB);
15225   }
15226
15227   // In offsetMBB, emit code to use the reg_save_area.
15228   if (offsetMBB) {
15229     assert(OffsetReg != 0);
15230
15231     // Read the reg_save_area address.
15232     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15233     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15234       .addOperand(Base)
15235       .addOperand(Scale)
15236       .addOperand(Index)
15237       .addDisp(Disp, 16)
15238       .addOperand(Segment)
15239       .setMemRefs(MMOBegin, MMOEnd);
15240
15241     // Zero-extend the offset
15242     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15243       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15244         .addImm(0)
15245         .addReg(OffsetReg)
15246         .addImm(X86::sub_32bit);
15247
15248     // Add the offset to the reg_save_area to get the final address.
15249     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15250       .addReg(OffsetReg64)
15251       .addReg(RegSaveReg);
15252
15253     // Compute the offset for the next argument
15254     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15255     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15256       .addReg(OffsetReg)
15257       .addImm(UseFPOffset ? 16 : 8);
15258
15259     // Store it back into the va_list.
15260     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15261       .addOperand(Base)
15262       .addOperand(Scale)
15263       .addOperand(Index)
15264       .addDisp(Disp, UseFPOffset ? 4 : 0)
15265       .addOperand(Segment)
15266       .addReg(NextOffsetReg)
15267       .setMemRefs(MMOBegin, MMOEnd);
15268
15269     // Jump to endMBB
15270     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15271       .addMBB(endMBB);
15272   }
15273
15274   //
15275   // Emit code to use overflow area
15276   //
15277
15278   // Load the overflow_area address into a register.
15279   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15280   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15281     .addOperand(Base)
15282     .addOperand(Scale)
15283     .addOperand(Index)
15284     .addDisp(Disp, 8)
15285     .addOperand(Segment)
15286     .setMemRefs(MMOBegin, MMOEnd);
15287
15288   // If we need to align it, do so. Otherwise, just copy the address
15289   // to OverflowDestReg.
15290   if (NeedsAlign) {
15291     // Align the overflow address
15292     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15293     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15294
15295     // aligned_addr = (addr + (align-1)) & ~(align-1)
15296     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15297       .addReg(OverflowAddrReg)
15298       .addImm(Align-1);
15299
15300     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15301       .addReg(TmpReg)
15302       .addImm(~(uint64_t)(Align-1));
15303   } else {
15304     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15305       .addReg(OverflowAddrReg);
15306   }
15307
15308   // Compute the next overflow address after this argument.
15309   // (the overflow address should be kept 8-byte aligned)
15310   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15311   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15312     .addReg(OverflowDestReg)
15313     .addImm(ArgSizeA8);
15314
15315   // Store the new overflow address.
15316   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15317     .addOperand(Base)
15318     .addOperand(Scale)
15319     .addOperand(Index)
15320     .addDisp(Disp, 8)
15321     .addOperand(Segment)
15322     .addReg(NextAddrReg)
15323     .setMemRefs(MMOBegin, MMOEnd);
15324
15325   // If we branched, emit the PHI to the front of endMBB.
15326   if (offsetMBB) {
15327     BuildMI(*endMBB, endMBB->begin(), DL,
15328             TII->get(X86::PHI), DestReg)
15329       .addReg(OffsetDestReg).addMBB(offsetMBB)
15330       .addReg(OverflowDestReg).addMBB(overflowMBB);
15331   }
15332
15333   // Erase the pseudo instruction
15334   MI->eraseFromParent();
15335
15336   return endMBB;
15337 }
15338
15339 MachineBasicBlock *
15340 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15341                                                  MachineInstr *MI,
15342                                                  MachineBasicBlock *MBB) const {
15343   // Emit code to save XMM registers to the stack. The ABI says that the
15344   // number of registers to save is given in %al, so it's theoretically
15345   // possible to do an indirect jump trick to avoid saving all of them,
15346   // however this code takes a simpler approach and just executes all
15347   // of the stores if %al is non-zero. It's less code, and it's probably
15348   // easier on the hardware branch predictor, and stores aren't all that
15349   // expensive anyway.
15350
15351   // Create the new basic blocks. One block contains all the XMM stores,
15352   // and one block is the final destination regardless of whether any
15353   // stores were performed.
15354   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15355   MachineFunction *F = MBB->getParent();
15356   MachineFunction::iterator MBBIter = MBB;
15357   ++MBBIter;
15358   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15359   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15360   F->insert(MBBIter, XMMSaveMBB);
15361   F->insert(MBBIter, EndMBB);
15362
15363   // Transfer the remainder of MBB and its successor edges to EndMBB.
15364   EndMBB->splice(EndMBB->begin(), MBB,
15365                  llvm::next(MachineBasicBlock::iterator(MI)),
15366                  MBB->end());
15367   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15368
15369   // The original block will now fall through to the XMM save block.
15370   MBB->addSuccessor(XMMSaveMBB);
15371   // The XMMSaveMBB will fall through to the end block.
15372   XMMSaveMBB->addSuccessor(EndMBB);
15373
15374   // Now add the instructions.
15375   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15376   DebugLoc DL = MI->getDebugLoc();
15377
15378   unsigned CountReg = MI->getOperand(0).getReg();
15379   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15380   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15381
15382   if (!Subtarget->isTargetWin64()) {
15383     // If %al is 0, branch around the XMM save block.
15384     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15385     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15386     MBB->addSuccessor(EndMBB);
15387   }
15388
15389   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15390   // that was just emitted, but clearly shouldn't be "saved".
15391   assert((MI->getNumOperands() <= 3 ||
15392           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15393           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15394          && "Expected last argument to be EFLAGS");
15395   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15396   // In the XMM save block, save all the XMM argument registers.
15397   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15398     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15399     MachineMemOperand *MMO =
15400       F->getMachineMemOperand(
15401           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15402         MachineMemOperand::MOStore,
15403         /*Size=*/16, /*Align=*/16);
15404     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15405       .addFrameIndex(RegSaveFrameIndex)
15406       .addImm(/*Scale=*/1)
15407       .addReg(/*IndexReg=*/0)
15408       .addImm(/*Disp=*/Offset)
15409       .addReg(/*Segment=*/0)
15410       .addReg(MI->getOperand(i).getReg())
15411       .addMemOperand(MMO);
15412   }
15413
15414   MI->eraseFromParent();   // The pseudo instruction is gone now.
15415
15416   return EndMBB;
15417 }
15418
15419 // The EFLAGS operand of SelectItr might be missing a kill marker
15420 // because there were multiple uses of EFLAGS, and ISel didn't know
15421 // which to mark. Figure out whether SelectItr should have had a
15422 // kill marker, and set it if it should. Returns the correct kill
15423 // marker value.
15424 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15425                                      MachineBasicBlock* BB,
15426                                      const TargetRegisterInfo* TRI) {
15427   // Scan forward through BB for a use/def of EFLAGS.
15428   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15429   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15430     const MachineInstr& mi = *miI;
15431     if (mi.readsRegister(X86::EFLAGS))
15432       return false;
15433     if (mi.definesRegister(X86::EFLAGS))
15434       break; // Should have kill-flag - update below.
15435   }
15436
15437   // If we hit the end of the block, check whether EFLAGS is live into a
15438   // successor.
15439   if (miI == BB->end()) {
15440     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15441                                           sEnd = BB->succ_end();
15442          sItr != sEnd; ++sItr) {
15443       MachineBasicBlock* succ = *sItr;
15444       if (succ->isLiveIn(X86::EFLAGS))
15445         return false;
15446     }
15447   }
15448
15449   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15450   // out. SelectMI should have a kill flag on EFLAGS.
15451   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15452   return true;
15453 }
15454
15455 MachineBasicBlock *
15456 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15457                                      MachineBasicBlock *BB) const {
15458   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15459   DebugLoc DL = MI->getDebugLoc();
15460
15461   // To "insert" a SELECT_CC instruction, we actually have to insert the
15462   // diamond control-flow pattern.  The incoming instruction knows the
15463   // destination vreg to set, the condition code register to branch on, the
15464   // true/false values to select between, and a branch opcode to use.
15465   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15466   MachineFunction::iterator It = BB;
15467   ++It;
15468
15469   //  thisMBB:
15470   //  ...
15471   //   TrueVal = ...
15472   //   cmpTY ccX, r1, r2
15473   //   bCC copy1MBB
15474   //   fallthrough --> copy0MBB
15475   MachineBasicBlock *thisMBB = BB;
15476   MachineFunction *F = BB->getParent();
15477   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15478   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15479   F->insert(It, copy0MBB);
15480   F->insert(It, sinkMBB);
15481
15482   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15483   // live into the sink and copy blocks.
15484   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15485   if (!MI->killsRegister(X86::EFLAGS) &&
15486       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15487     copy0MBB->addLiveIn(X86::EFLAGS);
15488     sinkMBB->addLiveIn(X86::EFLAGS);
15489   }
15490
15491   // Transfer the remainder of BB and its successor edges to sinkMBB.
15492   sinkMBB->splice(sinkMBB->begin(), BB,
15493                   llvm::next(MachineBasicBlock::iterator(MI)),
15494                   BB->end());
15495   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15496
15497   // Add the true and fallthrough blocks as its successors.
15498   BB->addSuccessor(copy0MBB);
15499   BB->addSuccessor(sinkMBB);
15500
15501   // Create the conditional branch instruction.
15502   unsigned Opc =
15503     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15504   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15505
15506   //  copy0MBB:
15507   //   %FalseValue = ...
15508   //   # fallthrough to sinkMBB
15509   copy0MBB->addSuccessor(sinkMBB);
15510
15511   //  sinkMBB:
15512   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15513   //  ...
15514   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15515           TII->get(X86::PHI), MI->getOperand(0).getReg())
15516     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15517     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15518
15519   MI->eraseFromParent();   // The pseudo instruction is gone now.
15520   return sinkMBB;
15521 }
15522
15523 MachineBasicBlock *
15524 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15525                                         bool Is64Bit) const {
15526   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15527   DebugLoc DL = MI->getDebugLoc();
15528   MachineFunction *MF = BB->getParent();
15529   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15530
15531   assert(getTargetMachine().Options.EnableSegmentedStacks);
15532
15533   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15534   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15535
15536   // BB:
15537   //  ... [Till the alloca]
15538   // If stacklet is not large enough, jump to mallocMBB
15539   //
15540   // bumpMBB:
15541   //  Allocate by subtracting from RSP
15542   //  Jump to continueMBB
15543   //
15544   // mallocMBB:
15545   //  Allocate by call to runtime
15546   //
15547   // continueMBB:
15548   //  ...
15549   //  [rest of original BB]
15550   //
15551
15552   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15553   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15554   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15555
15556   MachineRegisterInfo &MRI = MF->getRegInfo();
15557   const TargetRegisterClass *AddrRegClass =
15558     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15559
15560   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15561     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15562     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15563     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15564     sizeVReg = MI->getOperand(1).getReg(),
15565     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15566
15567   MachineFunction::iterator MBBIter = BB;
15568   ++MBBIter;
15569
15570   MF->insert(MBBIter, bumpMBB);
15571   MF->insert(MBBIter, mallocMBB);
15572   MF->insert(MBBIter, continueMBB);
15573
15574   continueMBB->splice(continueMBB->begin(), BB, llvm::next
15575                       (MachineBasicBlock::iterator(MI)), BB->end());
15576   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15577
15578   // Add code to the main basic block to check if the stack limit has been hit,
15579   // and if so, jump to mallocMBB otherwise to bumpMBB.
15580   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15581   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15582     .addReg(tmpSPVReg).addReg(sizeVReg);
15583   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15584     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15585     .addReg(SPLimitVReg);
15586   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15587
15588   // bumpMBB simply decreases the stack pointer, since we know the current
15589   // stacklet has enough space.
15590   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15591     .addReg(SPLimitVReg);
15592   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15593     .addReg(SPLimitVReg);
15594   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15595
15596   // Calls into a routine in libgcc to allocate more space from the heap.
15597   const uint32_t *RegMask =
15598     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15599   if (Is64Bit) {
15600     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15601       .addReg(sizeVReg);
15602     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15603       .addExternalSymbol("__morestack_allocate_stack_space")
15604       .addRegMask(RegMask)
15605       .addReg(X86::RDI, RegState::Implicit)
15606       .addReg(X86::RAX, RegState::ImplicitDefine);
15607   } else {
15608     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15609       .addImm(12);
15610     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15611     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15612       .addExternalSymbol("__morestack_allocate_stack_space")
15613       .addRegMask(RegMask)
15614       .addReg(X86::EAX, RegState::ImplicitDefine);
15615   }
15616
15617   if (!Is64Bit)
15618     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15619       .addImm(16);
15620
15621   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15622     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15623   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15624
15625   // Set up the CFG correctly.
15626   BB->addSuccessor(bumpMBB);
15627   BB->addSuccessor(mallocMBB);
15628   mallocMBB->addSuccessor(continueMBB);
15629   bumpMBB->addSuccessor(continueMBB);
15630
15631   // Take care of the PHI nodes.
15632   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15633           MI->getOperand(0).getReg())
15634     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15635     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15636
15637   // Delete the original pseudo instruction.
15638   MI->eraseFromParent();
15639
15640   // And we're done.
15641   return continueMBB;
15642 }
15643
15644 MachineBasicBlock *
15645 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15646                                           MachineBasicBlock *BB) const {
15647   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15648   DebugLoc DL = MI->getDebugLoc();
15649
15650   assert(!Subtarget->isTargetMacho());
15651
15652   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15653   // non-trivial part is impdef of ESP.
15654
15655   if (Subtarget->isTargetWin64()) {
15656     if (Subtarget->isTargetCygMing()) {
15657       // ___chkstk(Mingw64):
15658       // Clobbers R10, R11, RAX and EFLAGS.
15659       // Updates RSP.
15660       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15661         .addExternalSymbol("___chkstk")
15662         .addReg(X86::RAX, RegState::Implicit)
15663         .addReg(X86::RSP, RegState::Implicit)
15664         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15665         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15666         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15667     } else {
15668       // __chkstk(MSVCRT): does not update stack pointer.
15669       // Clobbers R10, R11 and EFLAGS.
15670       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15671         .addExternalSymbol("__chkstk")
15672         .addReg(X86::RAX, RegState::Implicit)
15673         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15674       // RAX has the offset to be subtracted from RSP.
15675       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15676         .addReg(X86::RSP)
15677         .addReg(X86::RAX);
15678     }
15679   } else {
15680     const char *StackProbeSymbol =
15681       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15682
15683     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15684       .addExternalSymbol(StackProbeSymbol)
15685       .addReg(X86::EAX, RegState::Implicit)
15686       .addReg(X86::ESP, RegState::Implicit)
15687       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15688       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15689       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15690   }
15691
15692   MI->eraseFromParent();   // The pseudo instruction is gone now.
15693   return BB;
15694 }
15695
15696 MachineBasicBlock *
15697 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15698                                       MachineBasicBlock *BB) const {
15699   // This is pretty easy.  We're taking the value that we received from
15700   // our load from the relocation, sticking it in either RDI (x86-64)
15701   // or EAX and doing an indirect call.  The return value will then
15702   // be in the normal return register.
15703   const X86InstrInfo *TII
15704     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15705   DebugLoc DL = MI->getDebugLoc();
15706   MachineFunction *F = BB->getParent();
15707
15708   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15709   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15710
15711   // Get a register mask for the lowered call.
15712   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15713   // proper register mask.
15714   const uint32_t *RegMask =
15715     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15716   if (Subtarget->is64Bit()) {
15717     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15718                                       TII->get(X86::MOV64rm), X86::RDI)
15719     .addReg(X86::RIP)
15720     .addImm(0).addReg(0)
15721     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15722                       MI->getOperand(3).getTargetFlags())
15723     .addReg(0);
15724     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15725     addDirectMem(MIB, X86::RDI);
15726     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15727   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15728     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15729                                       TII->get(X86::MOV32rm), X86::EAX)
15730     .addReg(0)
15731     .addImm(0).addReg(0)
15732     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15733                       MI->getOperand(3).getTargetFlags())
15734     .addReg(0);
15735     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15736     addDirectMem(MIB, X86::EAX);
15737     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15738   } else {
15739     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15740                                       TII->get(X86::MOV32rm), X86::EAX)
15741     .addReg(TII->getGlobalBaseReg(F))
15742     .addImm(0).addReg(0)
15743     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15744                       MI->getOperand(3).getTargetFlags())
15745     .addReg(0);
15746     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15747     addDirectMem(MIB, X86::EAX);
15748     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15749   }
15750
15751   MI->eraseFromParent(); // The pseudo instruction is gone now.
15752   return BB;
15753 }
15754
15755 MachineBasicBlock *
15756 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15757                                     MachineBasicBlock *MBB) const {
15758   DebugLoc DL = MI->getDebugLoc();
15759   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15760
15761   MachineFunction *MF = MBB->getParent();
15762   MachineRegisterInfo &MRI = MF->getRegInfo();
15763
15764   const BasicBlock *BB = MBB->getBasicBlock();
15765   MachineFunction::iterator I = MBB;
15766   ++I;
15767
15768   // Memory Reference
15769   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15770   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15771
15772   unsigned DstReg;
15773   unsigned MemOpndSlot = 0;
15774
15775   unsigned CurOp = 0;
15776
15777   DstReg = MI->getOperand(CurOp++).getReg();
15778   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15779   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15780   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15781   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15782
15783   MemOpndSlot = CurOp;
15784
15785   MVT PVT = getPointerTy();
15786   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15787          "Invalid Pointer Size!");
15788
15789   // For v = setjmp(buf), we generate
15790   //
15791   // thisMBB:
15792   //  buf[LabelOffset] = restoreMBB
15793   //  SjLjSetup restoreMBB
15794   //
15795   // mainMBB:
15796   //  v_main = 0
15797   //
15798   // sinkMBB:
15799   //  v = phi(main, restore)
15800   //
15801   // restoreMBB:
15802   //  v_restore = 1
15803
15804   MachineBasicBlock *thisMBB = MBB;
15805   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15806   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15807   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15808   MF->insert(I, mainMBB);
15809   MF->insert(I, sinkMBB);
15810   MF->push_back(restoreMBB);
15811
15812   MachineInstrBuilder MIB;
15813
15814   // Transfer the remainder of BB and its successor edges to sinkMBB.
15815   sinkMBB->splice(sinkMBB->begin(), MBB,
15816                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15817   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15818
15819   // thisMBB:
15820   unsigned PtrStoreOpc = 0;
15821   unsigned LabelReg = 0;
15822   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15823   Reloc::Model RM = getTargetMachine().getRelocationModel();
15824   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15825                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15826
15827   // Prepare IP either in reg or imm.
15828   if (!UseImmLabel) {
15829     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15830     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15831     LabelReg = MRI.createVirtualRegister(PtrRC);
15832     if (Subtarget->is64Bit()) {
15833       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15834               .addReg(X86::RIP)
15835               .addImm(0)
15836               .addReg(0)
15837               .addMBB(restoreMBB)
15838               .addReg(0);
15839     } else {
15840       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15841       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15842               .addReg(XII->getGlobalBaseReg(MF))
15843               .addImm(0)
15844               .addReg(0)
15845               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15846               .addReg(0);
15847     }
15848   } else
15849     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15850   // Store IP
15851   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15852   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15853     if (i == X86::AddrDisp)
15854       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15855     else
15856       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15857   }
15858   if (!UseImmLabel)
15859     MIB.addReg(LabelReg);
15860   else
15861     MIB.addMBB(restoreMBB);
15862   MIB.setMemRefs(MMOBegin, MMOEnd);
15863   // Setup
15864   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15865           .addMBB(restoreMBB);
15866
15867   const X86RegisterInfo *RegInfo =
15868     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15869   MIB.addRegMask(RegInfo->getNoPreservedMask());
15870   thisMBB->addSuccessor(mainMBB);
15871   thisMBB->addSuccessor(restoreMBB);
15872
15873   // mainMBB:
15874   //  EAX = 0
15875   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15876   mainMBB->addSuccessor(sinkMBB);
15877
15878   // sinkMBB:
15879   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15880           TII->get(X86::PHI), DstReg)
15881     .addReg(mainDstReg).addMBB(mainMBB)
15882     .addReg(restoreDstReg).addMBB(restoreMBB);
15883
15884   // restoreMBB:
15885   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15886   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15887   restoreMBB->addSuccessor(sinkMBB);
15888
15889   MI->eraseFromParent();
15890   return sinkMBB;
15891 }
15892
15893 MachineBasicBlock *
15894 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15895                                      MachineBasicBlock *MBB) const {
15896   DebugLoc DL = MI->getDebugLoc();
15897   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15898
15899   MachineFunction *MF = MBB->getParent();
15900   MachineRegisterInfo &MRI = MF->getRegInfo();
15901
15902   // Memory Reference
15903   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15904   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15905
15906   MVT PVT = getPointerTy();
15907   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15908          "Invalid Pointer Size!");
15909
15910   const TargetRegisterClass *RC =
15911     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15912   unsigned Tmp = MRI.createVirtualRegister(RC);
15913   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15914   const X86RegisterInfo *RegInfo =
15915     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15916   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15917   unsigned SP = RegInfo->getStackRegister();
15918
15919   MachineInstrBuilder MIB;
15920
15921   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15922   const int64_t SPOffset = 2 * PVT.getStoreSize();
15923
15924   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15925   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15926
15927   // Reload FP
15928   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15929   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15930     MIB.addOperand(MI->getOperand(i));
15931   MIB.setMemRefs(MMOBegin, MMOEnd);
15932   // Reload IP
15933   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15934   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15935     if (i == X86::AddrDisp)
15936       MIB.addDisp(MI->getOperand(i), LabelOffset);
15937     else
15938       MIB.addOperand(MI->getOperand(i));
15939   }
15940   MIB.setMemRefs(MMOBegin, MMOEnd);
15941   // Reload SP
15942   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15943   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15944     if (i == X86::AddrDisp)
15945       MIB.addDisp(MI->getOperand(i), SPOffset);
15946     else
15947       MIB.addOperand(MI->getOperand(i));
15948   }
15949   MIB.setMemRefs(MMOBegin, MMOEnd);
15950   // Jump
15951   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15952
15953   MI->eraseFromParent();
15954   return MBB;
15955 }
15956
15957 MachineBasicBlock *
15958 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15959                                                MachineBasicBlock *BB) const {
15960   switch (MI->getOpcode()) {
15961   default: llvm_unreachable("Unexpected instr type to insert");
15962   case X86::TAILJMPd64:
15963   case X86::TAILJMPr64:
15964   case X86::TAILJMPm64:
15965     llvm_unreachable("TAILJMP64 would not be touched here.");
15966   case X86::TCRETURNdi64:
15967   case X86::TCRETURNri64:
15968   case X86::TCRETURNmi64:
15969     return BB;
15970   case X86::WIN_ALLOCA:
15971     return EmitLoweredWinAlloca(MI, BB);
15972   case X86::SEG_ALLOCA_32:
15973     return EmitLoweredSegAlloca(MI, BB, false);
15974   case X86::SEG_ALLOCA_64:
15975     return EmitLoweredSegAlloca(MI, BB, true);
15976   case X86::TLSCall_32:
15977   case X86::TLSCall_64:
15978     return EmitLoweredTLSCall(MI, BB);
15979   case X86::CMOV_GR8:
15980   case X86::CMOV_FR32:
15981   case X86::CMOV_FR64:
15982   case X86::CMOV_V4F32:
15983   case X86::CMOV_V2F64:
15984   case X86::CMOV_V2I64:
15985   case X86::CMOV_V8F32:
15986   case X86::CMOV_V4F64:
15987   case X86::CMOV_V4I64:
15988   case X86::CMOV_V16F32:
15989   case X86::CMOV_V8F64:
15990   case X86::CMOV_V8I64:
15991   case X86::CMOV_GR16:
15992   case X86::CMOV_GR32:
15993   case X86::CMOV_RFP32:
15994   case X86::CMOV_RFP64:
15995   case X86::CMOV_RFP80:
15996     return EmitLoweredSelect(MI, BB);
15997
15998   case X86::FP32_TO_INT16_IN_MEM:
15999   case X86::FP32_TO_INT32_IN_MEM:
16000   case X86::FP32_TO_INT64_IN_MEM:
16001   case X86::FP64_TO_INT16_IN_MEM:
16002   case X86::FP64_TO_INT32_IN_MEM:
16003   case X86::FP64_TO_INT64_IN_MEM:
16004   case X86::FP80_TO_INT16_IN_MEM:
16005   case X86::FP80_TO_INT32_IN_MEM:
16006   case X86::FP80_TO_INT64_IN_MEM: {
16007     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16008     DebugLoc DL = MI->getDebugLoc();
16009
16010     // Change the floating point control register to use "round towards zero"
16011     // mode when truncating to an integer value.
16012     MachineFunction *F = BB->getParent();
16013     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16014     addFrameReference(BuildMI(*BB, MI, DL,
16015                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16016
16017     // Load the old value of the high byte of the control word...
16018     unsigned OldCW =
16019       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16020     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16021                       CWFrameIdx);
16022
16023     // Set the high part to be round to zero...
16024     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16025       .addImm(0xC7F);
16026
16027     // Reload the modified control word now...
16028     addFrameReference(BuildMI(*BB, MI, DL,
16029                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16030
16031     // Restore the memory image of control word to original value
16032     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16033       .addReg(OldCW);
16034
16035     // Get the X86 opcode to use.
16036     unsigned Opc;
16037     switch (MI->getOpcode()) {
16038     default: llvm_unreachable("illegal opcode!");
16039     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16040     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16041     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16042     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16043     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16044     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16045     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16046     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16047     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16048     }
16049
16050     X86AddressMode AM;
16051     MachineOperand &Op = MI->getOperand(0);
16052     if (Op.isReg()) {
16053       AM.BaseType = X86AddressMode::RegBase;
16054       AM.Base.Reg = Op.getReg();
16055     } else {
16056       AM.BaseType = X86AddressMode::FrameIndexBase;
16057       AM.Base.FrameIndex = Op.getIndex();
16058     }
16059     Op = MI->getOperand(1);
16060     if (Op.isImm())
16061       AM.Scale = Op.getImm();
16062     Op = MI->getOperand(2);
16063     if (Op.isImm())
16064       AM.IndexReg = Op.getImm();
16065     Op = MI->getOperand(3);
16066     if (Op.isGlobal()) {
16067       AM.GV = Op.getGlobal();
16068     } else {
16069       AM.Disp = Op.getImm();
16070     }
16071     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16072                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16073
16074     // Reload the original control word now.
16075     addFrameReference(BuildMI(*BB, MI, DL,
16076                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16077
16078     MI->eraseFromParent();   // The pseudo instruction is gone now.
16079     return BB;
16080   }
16081     // String/text processing lowering.
16082   case X86::PCMPISTRM128REG:
16083   case X86::VPCMPISTRM128REG:
16084   case X86::PCMPISTRM128MEM:
16085   case X86::VPCMPISTRM128MEM:
16086   case X86::PCMPESTRM128REG:
16087   case X86::VPCMPESTRM128REG:
16088   case X86::PCMPESTRM128MEM:
16089   case X86::VPCMPESTRM128MEM:
16090     assert(Subtarget->hasSSE42() &&
16091            "Target must have SSE4.2 or AVX features enabled");
16092     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16093
16094   // String/text processing lowering.
16095   case X86::PCMPISTRIREG:
16096   case X86::VPCMPISTRIREG:
16097   case X86::PCMPISTRIMEM:
16098   case X86::VPCMPISTRIMEM:
16099   case X86::PCMPESTRIREG:
16100   case X86::VPCMPESTRIREG:
16101   case X86::PCMPESTRIMEM:
16102   case X86::VPCMPESTRIMEM:
16103     assert(Subtarget->hasSSE42() &&
16104            "Target must have SSE4.2 or AVX features enabled");
16105     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16106
16107   // Thread synchronization.
16108   case X86::MONITOR:
16109     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16110
16111   // xbegin
16112   case X86::XBEGIN:
16113     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16114
16115   // Atomic Lowering.
16116   case X86::ATOMAND8:
16117   case X86::ATOMAND16:
16118   case X86::ATOMAND32:
16119   case X86::ATOMAND64:
16120     // Fall through
16121   case X86::ATOMOR8:
16122   case X86::ATOMOR16:
16123   case X86::ATOMOR32:
16124   case X86::ATOMOR64:
16125     // Fall through
16126   case X86::ATOMXOR16:
16127   case X86::ATOMXOR8:
16128   case X86::ATOMXOR32:
16129   case X86::ATOMXOR64:
16130     // Fall through
16131   case X86::ATOMNAND8:
16132   case X86::ATOMNAND16:
16133   case X86::ATOMNAND32:
16134   case X86::ATOMNAND64:
16135     // Fall through
16136   case X86::ATOMMAX8:
16137   case X86::ATOMMAX16:
16138   case X86::ATOMMAX32:
16139   case X86::ATOMMAX64:
16140     // Fall through
16141   case X86::ATOMMIN8:
16142   case X86::ATOMMIN16:
16143   case X86::ATOMMIN32:
16144   case X86::ATOMMIN64:
16145     // Fall through
16146   case X86::ATOMUMAX8:
16147   case X86::ATOMUMAX16:
16148   case X86::ATOMUMAX32:
16149   case X86::ATOMUMAX64:
16150     // Fall through
16151   case X86::ATOMUMIN8:
16152   case X86::ATOMUMIN16:
16153   case X86::ATOMUMIN32:
16154   case X86::ATOMUMIN64:
16155     return EmitAtomicLoadArith(MI, BB);
16156
16157   // This group does 64-bit operations on a 32-bit host.
16158   case X86::ATOMAND6432:
16159   case X86::ATOMOR6432:
16160   case X86::ATOMXOR6432:
16161   case X86::ATOMNAND6432:
16162   case X86::ATOMADD6432:
16163   case X86::ATOMSUB6432:
16164   case X86::ATOMMAX6432:
16165   case X86::ATOMMIN6432:
16166   case X86::ATOMUMAX6432:
16167   case X86::ATOMUMIN6432:
16168   case X86::ATOMSWAP6432:
16169     return EmitAtomicLoadArith6432(MI, BB);
16170
16171   case X86::VASTART_SAVE_XMM_REGS:
16172     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16173
16174   case X86::VAARG_64:
16175     return EmitVAARG64WithCustomInserter(MI, BB);
16176
16177   case X86::EH_SjLj_SetJmp32:
16178   case X86::EH_SjLj_SetJmp64:
16179     return emitEHSjLjSetJmp(MI, BB);
16180
16181   case X86::EH_SjLj_LongJmp32:
16182   case X86::EH_SjLj_LongJmp64:
16183     return emitEHSjLjLongJmp(MI, BB);
16184
16185   case TargetOpcode::STACKMAP:
16186   case TargetOpcode::PATCHPOINT:
16187     return emitPatchPoint(MI, BB);
16188   }
16189 }
16190
16191 //===----------------------------------------------------------------------===//
16192 //                           X86 Optimization Hooks
16193 //===----------------------------------------------------------------------===//
16194
16195 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16196                                                        APInt &KnownZero,
16197                                                        APInt &KnownOne,
16198                                                        const SelectionDAG &DAG,
16199                                                        unsigned Depth) const {
16200   unsigned BitWidth = KnownZero.getBitWidth();
16201   unsigned Opc = Op.getOpcode();
16202   assert((Opc >= ISD::BUILTIN_OP_END ||
16203           Opc == ISD::INTRINSIC_WO_CHAIN ||
16204           Opc == ISD::INTRINSIC_W_CHAIN ||
16205           Opc == ISD::INTRINSIC_VOID) &&
16206          "Should use MaskedValueIsZero if you don't know whether Op"
16207          " is a target node!");
16208
16209   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16210   switch (Opc) {
16211   default: break;
16212   case X86ISD::ADD:
16213   case X86ISD::SUB:
16214   case X86ISD::ADC:
16215   case X86ISD::SBB:
16216   case X86ISD::SMUL:
16217   case X86ISD::UMUL:
16218   case X86ISD::INC:
16219   case X86ISD::DEC:
16220   case X86ISD::OR:
16221   case X86ISD::XOR:
16222   case X86ISD::AND:
16223     // These nodes' second result is a boolean.
16224     if (Op.getResNo() == 0)
16225       break;
16226     // Fallthrough
16227   case X86ISD::SETCC:
16228     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16229     break;
16230   case ISD::INTRINSIC_WO_CHAIN: {
16231     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16232     unsigned NumLoBits = 0;
16233     switch (IntId) {
16234     default: break;
16235     case Intrinsic::x86_sse_movmsk_ps:
16236     case Intrinsic::x86_avx_movmsk_ps_256:
16237     case Intrinsic::x86_sse2_movmsk_pd:
16238     case Intrinsic::x86_avx_movmsk_pd_256:
16239     case Intrinsic::x86_mmx_pmovmskb:
16240     case Intrinsic::x86_sse2_pmovmskb_128:
16241     case Intrinsic::x86_avx2_pmovmskb: {
16242       // High bits of movmskp{s|d}, pmovmskb are known zero.
16243       switch (IntId) {
16244         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16245         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16246         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16247         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16248         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16249         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16250         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16251         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16252       }
16253       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16254       break;
16255     }
16256     }
16257     break;
16258   }
16259   }
16260 }
16261
16262 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16263                                                          unsigned Depth) const {
16264   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16265   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16266     return Op.getValueType().getScalarType().getSizeInBits();
16267
16268   // Fallback case.
16269   return 1;
16270 }
16271
16272 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16273 /// node is a GlobalAddress + offset.
16274 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16275                                        const GlobalValue* &GA,
16276                                        int64_t &Offset) const {
16277   if (N->getOpcode() == X86ISD::Wrapper) {
16278     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16279       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16280       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16281       return true;
16282     }
16283   }
16284   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16285 }
16286
16287 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16288 /// same as extracting the high 128-bit part of 256-bit vector and then
16289 /// inserting the result into the low part of a new 256-bit vector
16290 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16291   EVT VT = SVOp->getValueType(0);
16292   unsigned NumElems = VT.getVectorNumElements();
16293
16294   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16295   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16296     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16297         SVOp->getMaskElt(j) >= 0)
16298       return false;
16299
16300   return true;
16301 }
16302
16303 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16304 /// same as extracting the low 128-bit part of 256-bit vector and then
16305 /// inserting the result into the high part of a new 256-bit vector
16306 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16307   EVT VT = SVOp->getValueType(0);
16308   unsigned NumElems = VT.getVectorNumElements();
16309
16310   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16311   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16312     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16313         SVOp->getMaskElt(j) >= 0)
16314       return false;
16315
16316   return true;
16317 }
16318
16319 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16320 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16321                                         TargetLowering::DAGCombinerInfo &DCI,
16322                                         const X86Subtarget* Subtarget) {
16323   SDLoc dl(N);
16324   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16325   SDValue V1 = SVOp->getOperand(0);
16326   SDValue V2 = SVOp->getOperand(1);
16327   EVT VT = SVOp->getValueType(0);
16328   unsigned NumElems = VT.getVectorNumElements();
16329
16330   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16331       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16332     //
16333     //                   0,0,0,...
16334     //                      |
16335     //    V      UNDEF    BUILD_VECTOR    UNDEF
16336     //     \      /           \           /
16337     //  CONCAT_VECTOR         CONCAT_VECTOR
16338     //         \                  /
16339     //          \                /
16340     //          RESULT: V + zero extended
16341     //
16342     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16343         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16344         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16345       return SDValue();
16346
16347     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16348       return SDValue();
16349
16350     // To match the shuffle mask, the first half of the mask should
16351     // be exactly the first vector, and all the rest a splat with the
16352     // first element of the second one.
16353     for (unsigned i = 0; i != NumElems/2; ++i)
16354       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16355           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16356         return SDValue();
16357
16358     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16359     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16360       if (Ld->hasNUsesOfValue(1, 0)) {
16361         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16362         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16363         SDValue ResNode =
16364           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16365                                   array_lengthof(Ops),
16366                                   Ld->getMemoryVT(),
16367                                   Ld->getPointerInfo(),
16368                                   Ld->getAlignment(),
16369                                   false/*isVolatile*/, true/*ReadMem*/,
16370                                   false/*WriteMem*/);
16371
16372         // Make sure the newly-created LOAD is in the same position as Ld in
16373         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16374         // and update uses of Ld's output chain to use the TokenFactor.
16375         if (Ld->hasAnyUseOfValue(1)) {
16376           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16377                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16378           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16379           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16380                                  SDValue(ResNode.getNode(), 1));
16381         }
16382
16383         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16384       }
16385     }
16386
16387     // Emit a zeroed vector and insert the desired subvector on its
16388     // first half.
16389     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16390     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16391     return DCI.CombineTo(N, InsV);
16392   }
16393
16394   //===--------------------------------------------------------------------===//
16395   // Combine some shuffles into subvector extracts and inserts:
16396   //
16397
16398   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16399   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16400     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16401     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16402     return DCI.CombineTo(N, InsV);
16403   }
16404
16405   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16406   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16407     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16408     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16409     return DCI.CombineTo(N, InsV);
16410   }
16411
16412   return SDValue();
16413 }
16414
16415 /// PerformShuffleCombine - Performs several different shuffle combines.
16416 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16417                                      TargetLowering::DAGCombinerInfo &DCI,
16418                                      const X86Subtarget *Subtarget) {
16419   SDLoc dl(N);
16420   EVT VT = N->getValueType(0);
16421
16422   // Don't create instructions with illegal types after legalize types has run.
16423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16424   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16425     return SDValue();
16426
16427   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16428   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16429       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16430     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16431
16432   // Only handle 128 wide vector from here on.
16433   if (!VT.is128BitVector())
16434     return SDValue();
16435
16436   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16437   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16438   // consecutive, non-overlapping, and in the right order.
16439   SmallVector<SDValue, 16> Elts;
16440   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16441     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16442
16443   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16444 }
16445
16446 /// PerformTruncateCombine - Converts truncate operation to
16447 /// a sequence of vector shuffle operations.
16448 /// It is possible when we truncate 256-bit vector to 128-bit vector
16449 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16450                                       TargetLowering::DAGCombinerInfo &DCI,
16451                                       const X86Subtarget *Subtarget)  {
16452   return SDValue();
16453 }
16454
16455 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16456 /// specific shuffle of a load can be folded into a single element load.
16457 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16458 /// shuffles have been customed lowered so we need to handle those here.
16459 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16460                                          TargetLowering::DAGCombinerInfo &DCI) {
16461   if (DCI.isBeforeLegalizeOps())
16462     return SDValue();
16463
16464   SDValue InVec = N->getOperand(0);
16465   SDValue EltNo = N->getOperand(1);
16466
16467   if (!isa<ConstantSDNode>(EltNo))
16468     return SDValue();
16469
16470   EVT VT = InVec.getValueType();
16471
16472   bool HasShuffleIntoBitcast = false;
16473   if (InVec.getOpcode() == ISD::BITCAST) {
16474     // Don't duplicate a load with other uses.
16475     if (!InVec.hasOneUse())
16476       return SDValue();
16477     EVT BCVT = InVec.getOperand(0).getValueType();
16478     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16479       return SDValue();
16480     InVec = InVec.getOperand(0);
16481     HasShuffleIntoBitcast = true;
16482   }
16483
16484   if (!isTargetShuffle(InVec.getOpcode()))
16485     return SDValue();
16486
16487   // Don't duplicate a load with other uses.
16488   if (!InVec.hasOneUse())
16489     return SDValue();
16490
16491   SmallVector<int, 16> ShuffleMask;
16492   bool UnaryShuffle;
16493   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16494                             UnaryShuffle))
16495     return SDValue();
16496
16497   // Select the input vector, guarding against out of range extract vector.
16498   unsigned NumElems = VT.getVectorNumElements();
16499   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16500   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16501   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16502                                          : InVec.getOperand(1);
16503
16504   // If inputs to shuffle are the same for both ops, then allow 2 uses
16505   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16506
16507   if (LdNode.getOpcode() == ISD::BITCAST) {
16508     // Don't duplicate a load with other uses.
16509     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16510       return SDValue();
16511
16512     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16513     LdNode = LdNode.getOperand(0);
16514   }
16515
16516   if (!ISD::isNormalLoad(LdNode.getNode()))
16517     return SDValue();
16518
16519   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16520
16521   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16522     return SDValue();
16523
16524   if (HasShuffleIntoBitcast) {
16525     // If there's a bitcast before the shuffle, check if the load type and
16526     // alignment is valid.
16527     unsigned Align = LN0->getAlignment();
16528     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16529     unsigned NewAlign = TLI.getDataLayout()->
16530       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16531
16532     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16533       return SDValue();
16534   }
16535
16536   // All checks match so transform back to vector_shuffle so that DAG combiner
16537   // can finish the job
16538   SDLoc dl(N);
16539
16540   // Create shuffle node taking into account the case that its a unary shuffle
16541   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16542   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16543                                  InVec.getOperand(0), Shuffle,
16544                                  &ShuffleMask[0]);
16545   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16546   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16547                      EltNo);
16548 }
16549
16550 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16551 /// generation and convert it from being a bunch of shuffles and extracts
16552 /// to a simple store and scalar loads to extract the elements.
16553 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16554                                          TargetLowering::DAGCombinerInfo &DCI) {
16555   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16556   if (NewOp.getNode())
16557     return NewOp;
16558
16559   SDValue InputVector = N->getOperand(0);
16560
16561   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16562   // from mmx to v2i32 has a single usage.
16563   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16564       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16565       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16566     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16567                        N->getValueType(0),
16568                        InputVector.getNode()->getOperand(0));
16569
16570   // Only operate on vectors of 4 elements, where the alternative shuffling
16571   // gets to be more expensive.
16572   if (InputVector.getValueType() != MVT::v4i32)
16573     return SDValue();
16574
16575   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16576   // single use which is a sign-extend or zero-extend, and all elements are
16577   // used.
16578   SmallVector<SDNode *, 4> Uses;
16579   unsigned ExtractedElements = 0;
16580   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16581        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16582     if (UI.getUse().getResNo() != InputVector.getResNo())
16583       return SDValue();
16584
16585     SDNode *Extract = *UI;
16586     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16587       return SDValue();
16588
16589     if (Extract->getValueType(0) != MVT::i32)
16590       return SDValue();
16591     if (!Extract->hasOneUse())
16592       return SDValue();
16593     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16594         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16595       return SDValue();
16596     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16597       return SDValue();
16598
16599     // Record which element was extracted.
16600     ExtractedElements |=
16601       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16602
16603     Uses.push_back(Extract);
16604   }
16605
16606   // If not all the elements were used, this may not be worthwhile.
16607   if (ExtractedElements != 15)
16608     return SDValue();
16609
16610   // Ok, we've now decided to do the transformation.
16611   SDLoc dl(InputVector);
16612
16613   // Store the value to a temporary stack slot.
16614   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16615   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16616                             MachinePointerInfo(), false, false, 0);
16617
16618   // Replace each use (extract) with a load of the appropriate element.
16619   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16620        UE = Uses.end(); UI != UE; ++UI) {
16621     SDNode *Extract = *UI;
16622
16623     // cOMpute the element's address.
16624     SDValue Idx = Extract->getOperand(1);
16625     unsigned EltSize =
16626         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16627     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16628     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16629     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16630
16631     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16632                                      StackPtr, OffsetVal);
16633
16634     // Load the scalar.
16635     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16636                                      ScalarAddr, MachinePointerInfo(),
16637                                      false, false, false, 0);
16638
16639     // Replace the exact with the load.
16640     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16641   }
16642
16643   // The replacement was made in place; don't return anything.
16644   return SDValue();
16645 }
16646
16647 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16648 static std::pair<unsigned, bool>
16649 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16650                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16651   if (!VT.isVector())
16652     return std::make_pair(0, false);
16653
16654   bool NeedSplit = false;
16655   switch (VT.getSimpleVT().SimpleTy) {
16656   default: return std::make_pair(0, false);
16657   case MVT::v32i8:
16658   case MVT::v16i16:
16659   case MVT::v8i32:
16660     if (!Subtarget->hasAVX2())
16661       NeedSplit = true;
16662     if (!Subtarget->hasAVX())
16663       return std::make_pair(0, false);
16664     break;
16665   case MVT::v16i8:
16666   case MVT::v8i16:
16667   case MVT::v4i32:
16668     if (!Subtarget->hasSSE2())
16669       return std::make_pair(0, false);
16670   }
16671
16672   // SSE2 has only a small subset of the operations.
16673   bool hasUnsigned = Subtarget->hasSSE41() ||
16674                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16675   bool hasSigned = Subtarget->hasSSE41() ||
16676                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16677
16678   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16679
16680   unsigned Opc = 0;
16681   // Check for x CC y ? x : y.
16682   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16683       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16684     switch (CC) {
16685     default: break;
16686     case ISD::SETULT:
16687     case ISD::SETULE:
16688       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16689     case ISD::SETUGT:
16690     case ISD::SETUGE:
16691       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16692     case ISD::SETLT:
16693     case ISD::SETLE:
16694       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16695     case ISD::SETGT:
16696     case ISD::SETGE:
16697       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16698     }
16699   // Check for x CC y ? y : x -- a min/max with reversed arms.
16700   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16701              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16702     switch (CC) {
16703     default: break;
16704     case ISD::SETULT:
16705     case ISD::SETULE:
16706       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16707     case ISD::SETUGT:
16708     case ISD::SETUGE:
16709       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16710     case ISD::SETLT:
16711     case ISD::SETLE:
16712       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16713     case ISD::SETGT:
16714     case ISD::SETGE:
16715       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16716     }
16717   }
16718
16719   return std::make_pair(Opc, NeedSplit);
16720 }
16721
16722 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16723 /// nodes.
16724 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16725                                     TargetLowering::DAGCombinerInfo &DCI,
16726                                     const X86Subtarget *Subtarget) {
16727   SDLoc DL(N);
16728   SDValue Cond = N->getOperand(0);
16729   // Get the LHS/RHS of the select.
16730   SDValue LHS = N->getOperand(1);
16731   SDValue RHS = N->getOperand(2);
16732   EVT VT = LHS.getValueType();
16733   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16734
16735   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16736   // instructions match the semantics of the common C idiom x<y?x:y but not
16737   // x<=y?x:y, because of how they handle negative zero (which can be
16738   // ignored in unsafe-math mode).
16739   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16740       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16741       (Subtarget->hasSSE2() ||
16742        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16743     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16744
16745     unsigned Opcode = 0;
16746     // Check for x CC y ? x : y.
16747     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16748         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16749       switch (CC) {
16750       default: break;
16751       case ISD::SETULT:
16752         // Converting this to a min would handle NaNs incorrectly, and swapping
16753         // the operands would cause it to handle comparisons between positive
16754         // and negative zero incorrectly.
16755         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16756           if (!DAG.getTarget().Options.UnsafeFPMath &&
16757               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16758             break;
16759           std::swap(LHS, RHS);
16760         }
16761         Opcode = X86ISD::FMIN;
16762         break;
16763       case ISD::SETOLE:
16764         // Converting this to a min would handle comparisons between positive
16765         // and negative zero incorrectly.
16766         if (!DAG.getTarget().Options.UnsafeFPMath &&
16767             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16768           break;
16769         Opcode = X86ISD::FMIN;
16770         break;
16771       case ISD::SETULE:
16772         // Converting this to a min would handle both negative zeros and NaNs
16773         // incorrectly, but we can swap the operands to fix both.
16774         std::swap(LHS, RHS);
16775       case ISD::SETOLT:
16776       case ISD::SETLT:
16777       case ISD::SETLE:
16778         Opcode = X86ISD::FMIN;
16779         break;
16780
16781       case ISD::SETOGE:
16782         // Converting this to a max would handle comparisons between positive
16783         // and negative zero incorrectly.
16784         if (!DAG.getTarget().Options.UnsafeFPMath &&
16785             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16786           break;
16787         Opcode = X86ISD::FMAX;
16788         break;
16789       case ISD::SETUGT:
16790         // Converting this to a max would handle NaNs incorrectly, and swapping
16791         // the operands would cause it to handle comparisons between positive
16792         // and negative zero incorrectly.
16793         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16794           if (!DAG.getTarget().Options.UnsafeFPMath &&
16795               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16796             break;
16797           std::swap(LHS, RHS);
16798         }
16799         Opcode = X86ISD::FMAX;
16800         break;
16801       case ISD::SETUGE:
16802         // Converting this to a max would handle both negative zeros and NaNs
16803         // incorrectly, but we can swap the operands to fix both.
16804         std::swap(LHS, RHS);
16805       case ISD::SETOGT:
16806       case ISD::SETGT:
16807       case ISD::SETGE:
16808         Opcode = X86ISD::FMAX;
16809         break;
16810       }
16811     // Check for x CC y ? y : x -- a min/max with reversed arms.
16812     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16813                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16814       switch (CC) {
16815       default: break;
16816       case ISD::SETOGE:
16817         // Converting this to a min would handle comparisons between positive
16818         // and negative zero incorrectly, and swapping the operands would
16819         // cause it to handle NaNs incorrectly.
16820         if (!DAG.getTarget().Options.UnsafeFPMath &&
16821             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16822           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16823             break;
16824           std::swap(LHS, RHS);
16825         }
16826         Opcode = X86ISD::FMIN;
16827         break;
16828       case ISD::SETUGT:
16829         // Converting this to a min would handle NaNs incorrectly.
16830         if (!DAG.getTarget().Options.UnsafeFPMath &&
16831             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16832           break;
16833         Opcode = X86ISD::FMIN;
16834         break;
16835       case ISD::SETUGE:
16836         // Converting this to a min would handle both negative zeros and NaNs
16837         // incorrectly, but we can swap the operands to fix both.
16838         std::swap(LHS, RHS);
16839       case ISD::SETOGT:
16840       case ISD::SETGT:
16841       case ISD::SETGE:
16842         Opcode = X86ISD::FMIN;
16843         break;
16844
16845       case ISD::SETULT:
16846         // Converting this to a max would handle NaNs incorrectly.
16847         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16848           break;
16849         Opcode = X86ISD::FMAX;
16850         break;
16851       case ISD::SETOLE:
16852         // Converting this to a max would handle comparisons between positive
16853         // and negative zero incorrectly, and swapping the operands would
16854         // cause it to handle NaNs incorrectly.
16855         if (!DAG.getTarget().Options.UnsafeFPMath &&
16856             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16857           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16858             break;
16859           std::swap(LHS, RHS);
16860         }
16861         Opcode = X86ISD::FMAX;
16862         break;
16863       case ISD::SETULE:
16864         // Converting this to a max would handle both negative zeros and NaNs
16865         // incorrectly, but we can swap the operands to fix both.
16866         std::swap(LHS, RHS);
16867       case ISD::SETOLT:
16868       case ISD::SETLT:
16869       case ISD::SETLE:
16870         Opcode = X86ISD::FMAX;
16871         break;
16872       }
16873     }
16874
16875     if (Opcode)
16876       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16877   }
16878
16879   EVT CondVT = Cond.getValueType();
16880   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
16881       CondVT.getVectorElementType() == MVT::i1) {
16882     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
16883     // lowering on AVX-512. In this case we convert it to
16884     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
16885     // The same situation for all 128 and 256-bit vectors of i8 and i16
16886     EVT OpVT = LHS.getValueType();
16887     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
16888         (OpVT.getVectorElementType() == MVT::i8 ||
16889          OpVT.getVectorElementType() == MVT::i16)) {
16890       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
16891       DCI.AddToWorklist(Cond.getNode());
16892       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
16893     }
16894   }
16895   // If this is a select between two integer constants, try to do some
16896   // optimizations.
16897   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16898     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16899       // Don't do this for crazy integer types.
16900       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16901         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16902         // so that TrueC (the true value) is larger than FalseC.
16903         bool NeedsCondInvert = false;
16904
16905         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16906             // Efficiently invertible.
16907             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16908              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16909               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16910           NeedsCondInvert = true;
16911           std::swap(TrueC, FalseC);
16912         }
16913
16914         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16915         if (FalseC->getAPIntValue() == 0 &&
16916             TrueC->getAPIntValue().isPowerOf2()) {
16917           if (NeedsCondInvert) // Invert the condition if needed.
16918             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16919                                DAG.getConstant(1, Cond.getValueType()));
16920
16921           // Zero extend the condition if needed.
16922           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16923
16924           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16925           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16926                              DAG.getConstant(ShAmt, MVT::i8));
16927         }
16928
16929         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16930         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16931           if (NeedsCondInvert) // Invert the condition if needed.
16932             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16933                                DAG.getConstant(1, Cond.getValueType()));
16934
16935           // Zero extend the condition if needed.
16936           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16937                              FalseC->getValueType(0), Cond);
16938           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16939                              SDValue(FalseC, 0));
16940         }
16941
16942         // Optimize cases that will turn into an LEA instruction.  This requires
16943         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16944         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16945           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16946           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16947
16948           bool isFastMultiplier = false;
16949           if (Diff < 10) {
16950             switch ((unsigned char)Diff) {
16951               default: break;
16952               case 1:  // result = add base, cond
16953               case 2:  // result = lea base(    , cond*2)
16954               case 3:  // result = lea base(cond, cond*2)
16955               case 4:  // result = lea base(    , cond*4)
16956               case 5:  // result = lea base(cond, cond*4)
16957               case 8:  // result = lea base(    , cond*8)
16958               case 9:  // result = lea base(cond, cond*8)
16959                 isFastMultiplier = true;
16960                 break;
16961             }
16962           }
16963
16964           if (isFastMultiplier) {
16965             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16966             if (NeedsCondInvert) // Invert the condition if needed.
16967               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16968                                  DAG.getConstant(1, Cond.getValueType()));
16969
16970             // Zero extend the condition if needed.
16971             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16972                                Cond);
16973             // Scale the condition by the difference.
16974             if (Diff != 1)
16975               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16976                                  DAG.getConstant(Diff, Cond.getValueType()));
16977
16978             // Add the base if non-zero.
16979             if (FalseC->getAPIntValue() != 0)
16980               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16981                                  SDValue(FalseC, 0));
16982             return Cond;
16983           }
16984         }
16985       }
16986   }
16987
16988   // Canonicalize max and min:
16989   // (x > y) ? x : y -> (x >= y) ? x : y
16990   // (x < y) ? x : y -> (x <= y) ? x : y
16991   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16992   // the need for an extra compare
16993   // against zero. e.g.
16994   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16995   // subl   %esi, %edi
16996   // testl  %edi, %edi
16997   // movl   $0, %eax
16998   // cmovgl %edi, %eax
16999   // =>
17000   // xorl   %eax, %eax
17001   // subl   %esi, $edi
17002   // cmovsl %eax, %edi
17003   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17004       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17005       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17006     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17007     switch (CC) {
17008     default: break;
17009     case ISD::SETLT:
17010     case ISD::SETGT: {
17011       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17012       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17013                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17014       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17015     }
17016     }
17017   }
17018
17019   // Early exit check
17020   if (!TLI.isTypeLegal(VT))
17021     return SDValue();
17022
17023   // Match VSELECTs into subs with unsigned saturation.
17024   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17025       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17026       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17027        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17028     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17029
17030     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17031     // left side invert the predicate to simplify logic below.
17032     SDValue Other;
17033     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17034       Other = RHS;
17035       CC = ISD::getSetCCInverse(CC, true);
17036     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17037       Other = LHS;
17038     }
17039
17040     if (Other.getNode() && Other->getNumOperands() == 2 &&
17041         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17042       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17043       SDValue CondRHS = Cond->getOperand(1);
17044
17045       // Look for a general sub with unsigned saturation first.
17046       // x >= y ? x-y : 0 --> subus x, y
17047       // x >  y ? x-y : 0 --> subus x, y
17048       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17049           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17050         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17051
17052       // If the RHS is a constant we have to reverse the const canonicalization.
17053       // x > C-1 ? x+-C : 0 --> subus x, C
17054       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17055           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17056         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17057         if (CondRHS.getConstantOperandVal(0) == -A-1)
17058           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17059                              DAG.getConstant(-A, VT));
17060       }
17061
17062       // Another special case: If C was a sign bit, the sub has been
17063       // canonicalized into a xor.
17064       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17065       //        it's safe to decanonicalize the xor?
17066       // x s< 0 ? x^C : 0 --> subus x, C
17067       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17068           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17069           isSplatVector(OpRHS.getNode())) {
17070         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17071         if (A.isSignBit())
17072           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17073       }
17074     }
17075   }
17076
17077   // Try to match a min/max vector operation.
17078   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17079     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17080     unsigned Opc = ret.first;
17081     bool NeedSplit = ret.second;
17082
17083     if (Opc && NeedSplit) {
17084       unsigned NumElems = VT.getVectorNumElements();
17085       // Extract the LHS vectors
17086       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17087       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17088
17089       // Extract the RHS vectors
17090       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17091       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17092
17093       // Create min/max for each subvector
17094       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17095       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17096
17097       // Merge the result
17098       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17099     } else if (Opc)
17100       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17101   }
17102
17103   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17104   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17105       // Check if SETCC has already been promoted
17106       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17107       // Check that condition value type matches vselect operand type
17108       CondVT == VT) { 
17109
17110     assert(Cond.getValueType().isVector() &&
17111            "vector select expects a vector selector!");
17112
17113     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17114     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17115
17116     if (!TValIsAllOnes && !FValIsAllZeros) {
17117       // Try invert the condition if true value is not all 1s and false value
17118       // is not all 0s.
17119       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17120       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17121
17122       if (TValIsAllZeros || FValIsAllOnes) {
17123         SDValue CC = Cond.getOperand(2);
17124         ISD::CondCode NewCC =
17125           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17126                                Cond.getOperand(0).getValueType().isInteger());
17127         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17128         std::swap(LHS, RHS);
17129         TValIsAllOnes = FValIsAllOnes;
17130         FValIsAllZeros = TValIsAllZeros;
17131       }
17132     }
17133
17134     if (TValIsAllOnes || FValIsAllZeros) {
17135       SDValue Ret;
17136
17137       if (TValIsAllOnes && FValIsAllZeros)
17138         Ret = Cond;
17139       else if (TValIsAllOnes)
17140         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17141                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17142       else if (FValIsAllZeros)
17143         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17144                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17145
17146       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17147     }
17148   }
17149
17150   // If we know that this node is legal then we know that it is going to be
17151   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17152   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17153   // to simplify previous instructions.
17154   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17155       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17156     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17157
17158     // Don't optimize vector selects that map to mask-registers.
17159     if (BitWidth == 1)
17160       return SDValue();
17161
17162     // Check all uses of that condition operand to check whether it will be
17163     // consumed by non-BLEND instructions, which may depend on all bits are set
17164     // properly.
17165     for (SDNode::use_iterator I = Cond->use_begin(),
17166                               E = Cond->use_end(); I != E; ++I)
17167       if (I->getOpcode() != ISD::VSELECT)
17168         // TODO: Add other opcodes eventually lowered into BLEND.
17169         return SDValue();
17170
17171     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17172     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17173
17174     APInt KnownZero, KnownOne;
17175     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17176                                           DCI.isBeforeLegalizeOps());
17177     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17178         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17179       DCI.CommitTargetLoweringOpt(TLO);
17180   }
17181
17182   return SDValue();
17183 }
17184
17185 // Check whether a boolean test is testing a boolean value generated by
17186 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17187 // code.
17188 //
17189 // Simplify the following patterns:
17190 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17191 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17192 // to (Op EFLAGS Cond)
17193 //
17194 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17195 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17196 // to (Op EFLAGS !Cond)
17197 //
17198 // where Op could be BRCOND or CMOV.
17199 //
17200 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17201   // Quit if not CMP and SUB with its value result used.
17202   if (Cmp.getOpcode() != X86ISD::CMP &&
17203       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17204       return SDValue();
17205
17206   // Quit if not used as a boolean value.
17207   if (CC != X86::COND_E && CC != X86::COND_NE)
17208     return SDValue();
17209
17210   // Check CMP operands. One of them should be 0 or 1 and the other should be
17211   // an SetCC or extended from it.
17212   SDValue Op1 = Cmp.getOperand(0);
17213   SDValue Op2 = Cmp.getOperand(1);
17214
17215   SDValue SetCC;
17216   const ConstantSDNode* C = 0;
17217   bool needOppositeCond = (CC == X86::COND_E);
17218   bool checkAgainstTrue = false; // Is it a comparison against 1?
17219
17220   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17221     SetCC = Op2;
17222   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17223     SetCC = Op1;
17224   else // Quit if all operands are not constants.
17225     return SDValue();
17226
17227   if (C->getZExtValue() == 1) {
17228     needOppositeCond = !needOppositeCond;
17229     checkAgainstTrue = true;
17230   } else if (C->getZExtValue() != 0)
17231     // Quit if the constant is neither 0 or 1.
17232     return SDValue();
17233
17234   bool truncatedToBoolWithAnd = false;
17235   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17236   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17237          SetCC.getOpcode() == ISD::TRUNCATE ||
17238          SetCC.getOpcode() == ISD::AND) {
17239     if (SetCC.getOpcode() == ISD::AND) {
17240       int OpIdx = -1;
17241       ConstantSDNode *CS;
17242       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17243           CS->getZExtValue() == 1)
17244         OpIdx = 1;
17245       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17246           CS->getZExtValue() == 1)
17247         OpIdx = 0;
17248       if (OpIdx == -1)
17249         break;
17250       SetCC = SetCC.getOperand(OpIdx);
17251       truncatedToBoolWithAnd = true;
17252     } else
17253       SetCC = SetCC.getOperand(0);
17254   }
17255
17256   switch (SetCC.getOpcode()) {
17257   case X86ISD::SETCC_CARRY:
17258     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17259     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17260     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17261     // truncated to i1 using 'and'.
17262     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17263       break;
17264     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17265            "Invalid use of SETCC_CARRY!");
17266     // FALL THROUGH
17267   case X86ISD::SETCC:
17268     // Set the condition code or opposite one if necessary.
17269     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17270     if (needOppositeCond)
17271       CC = X86::GetOppositeBranchCondition(CC);
17272     return SetCC.getOperand(1);
17273   case X86ISD::CMOV: {
17274     // Check whether false/true value has canonical one, i.e. 0 or 1.
17275     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17276     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17277     // Quit if true value is not a constant.
17278     if (!TVal)
17279       return SDValue();
17280     // Quit if false value is not a constant.
17281     if (!FVal) {
17282       SDValue Op = SetCC.getOperand(0);
17283       // Skip 'zext' or 'trunc' node.
17284       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17285           Op.getOpcode() == ISD::TRUNCATE)
17286         Op = Op.getOperand(0);
17287       // A special case for rdrand/rdseed, where 0 is set if false cond is
17288       // found.
17289       if ((Op.getOpcode() != X86ISD::RDRAND &&
17290            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17291         return SDValue();
17292     }
17293     // Quit if false value is not the constant 0 or 1.
17294     bool FValIsFalse = true;
17295     if (FVal && FVal->getZExtValue() != 0) {
17296       if (FVal->getZExtValue() != 1)
17297         return SDValue();
17298       // If FVal is 1, opposite cond is needed.
17299       needOppositeCond = !needOppositeCond;
17300       FValIsFalse = false;
17301     }
17302     // Quit if TVal is not the constant opposite of FVal.
17303     if (FValIsFalse && TVal->getZExtValue() != 1)
17304       return SDValue();
17305     if (!FValIsFalse && TVal->getZExtValue() != 0)
17306       return SDValue();
17307     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17308     if (needOppositeCond)
17309       CC = X86::GetOppositeBranchCondition(CC);
17310     return SetCC.getOperand(3);
17311   }
17312   }
17313
17314   return SDValue();
17315 }
17316
17317 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17318 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17319                                   TargetLowering::DAGCombinerInfo &DCI,
17320                                   const X86Subtarget *Subtarget) {
17321   SDLoc DL(N);
17322
17323   // If the flag operand isn't dead, don't touch this CMOV.
17324   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17325     return SDValue();
17326
17327   SDValue FalseOp = N->getOperand(0);
17328   SDValue TrueOp = N->getOperand(1);
17329   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17330   SDValue Cond = N->getOperand(3);
17331
17332   if (CC == X86::COND_E || CC == X86::COND_NE) {
17333     switch (Cond.getOpcode()) {
17334     default: break;
17335     case X86ISD::BSR:
17336     case X86ISD::BSF:
17337       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17338       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17339         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17340     }
17341   }
17342
17343   SDValue Flags;
17344
17345   Flags = checkBoolTestSetCCCombine(Cond, CC);
17346   if (Flags.getNode() &&
17347       // Extra check as FCMOV only supports a subset of X86 cond.
17348       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17349     SDValue Ops[] = { FalseOp, TrueOp,
17350                       DAG.getConstant(CC, MVT::i8), Flags };
17351     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17352                        Ops, array_lengthof(Ops));
17353   }
17354
17355   // If this is a select between two integer constants, try to do some
17356   // optimizations.  Note that the operands are ordered the opposite of SELECT
17357   // operands.
17358   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17359     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17360       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17361       // larger than FalseC (the false value).
17362       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17363         CC = X86::GetOppositeBranchCondition(CC);
17364         std::swap(TrueC, FalseC);
17365         std::swap(TrueOp, FalseOp);
17366       }
17367
17368       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17369       // This is efficient for any integer data type (including i8/i16) and
17370       // shift amount.
17371       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17372         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17373                            DAG.getConstant(CC, MVT::i8), Cond);
17374
17375         // Zero extend the condition if needed.
17376         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17377
17378         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17379         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17380                            DAG.getConstant(ShAmt, MVT::i8));
17381         if (N->getNumValues() == 2)  // Dead flag value?
17382           return DCI.CombineTo(N, Cond, SDValue());
17383         return Cond;
17384       }
17385
17386       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17387       // for any integer data type, including i8/i16.
17388       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17389         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17390                            DAG.getConstant(CC, MVT::i8), Cond);
17391
17392         // Zero extend the condition if needed.
17393         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17394                            FalseC->getValueType(0), Cond);
17395         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17396                            SDValue(FalseC, 0));
17397
17398         if (N->getNumValues() == 2)  // Dead flag value?
17399           return DCI.CombineTo(N, Cond, SDValue());
17400         return Cond;
17401       }
17402
17403       // Optimize cases that will turn into an LEA instruction.  This requires
17404       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17405       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17406         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17407         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17408
17409         bool isFastMultiplier = false;
17410         if (Diff < 10) {
17411           switch ((unsigned char)Diff) {
17412           default: break;
17413           case 1:  // result = add base, cond
17414           case 2:  // result = lea base(    , cond*2)
17415           case 3:  // result = lea base(cond, cond*2)
17416           case 4:  // result = lea base(    , cond*4)
17417           case 5:  // result = lea base(cond, cond*4)
17418           case 8:  // result = lea base(    , cond*8)
17419           case 9:  // result = lea base(cond, cond*8)
17420             isFastMultiplier = true;
17421             break;
17422           }
17423         }
17424
17425         if (isFastMultiplier) {
17426           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17427           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17428                              DAG.getConstant(CC, MVT::i8), Cond);
17429           // Zero extend the condition if needed.
17430           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17431                              Cond);
17432           // Scale the condition by the difference.
17433           if (Diff != 1)
17434             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17435                                DAG.getConstant(Diff, Cond.getValueType()));
17436
17437           // Add the base if non-zero.
17438           if (FalseC->getAPIntValue() != 0)
17439             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17440                                SDValue(FalseC, 0));
17441           if (N->getNumValues() == 2)  // Dead flag value?
17442             return DCI.CombineTo(N, Cond, SDValue());
17443           return Cond;
17444         }
17445       }
17446     }
17447   }
17448
17449   // Handle these cases:
17450   //   (select (x != c), e, c) -> select (x != c), e, x),
17451   //   (select (x == c), c, e) -> select (x == c), x, e)
17452   // where the c is an integer constant, and the "select" is the combination
17453   // of CMOV and CMP.
17454   //
17455   // The rationale for this change is that the conditional-move from a constant
17456   // needs two instructions, however, conditional-move from a register needs
17457   // only one instruction.
17458   //
17459   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17460   //  some instruction-combining opportunities. This opt needs to be
17461   //  postponed as late as possible.
17462   //
17463   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17464     // the DCI.xxxx conditions are provided to postpone the optimization as
17465     // late as possible.
17466
17467     ConstantSDNode *CmpAgainst = 0;
17468     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17469         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17470         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17471
17472       if (CC == X86::COND_NE &&
17473           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17474         CC = X86::GetOppositeBranchCondition(CC);
17475         std::swap(TrueOp, FalseOp);
17476       }
17477
17478       if (CC == X86::COND_E &&
17479           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17480         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17481                           DAG.getConstant(CC, MVT::i8), Cond };
17482         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17483                            array_lengthof(Ops));
17484       }
17485     }
17486   }
17487
17488   return SDValue();
17489 }
17490
17491 /// PerformMulCombine - Optimize a single multiply with constant into two
17492 /// in order to implement it with two cheaper instructions, e.g.
17493 /// LEA + SHL, LEA + LEA.
17494 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17495                                  TargetLowering::DAGCombinerInfo &DCI) {
17496   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17497     return SDValue();
17498
17499   EVT VT = N->getValueType(0);
17500   if (VT != MVT::i64)
17501     return SDValue();
17502
17503   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17504   if (!C)
17505     return SDValue();
17506   uint64_t MulAmt = C->getZExtValue();
17507   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17508     return SDValue();
17509
17510   uint64_t MulAmt1 = 0;
17511   uint64_t MulAmt2 = 0;
17512   if ((MulAmt % 9) == 0) {
17513     MulAmt1 = 9;
17514     MulAmt2 = MulAmt / 9;
17515   } else if ((MulAmt % 5) == 0) {
17516     MulAmt1 = 5;
17517     MulAmt2 = MulAmt / 5;
17518   } else if ((MulAmt % 3) == 0) {
17519     MulAmt1 = 3;
17520     MulAmt2 = MulAmt / 3;
17521   }
17522   if (MulAmt2 &&
17523       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17524     SDLoc DL(N);
17525
17526     if (isPowerOf2_64(MulAmt2) &&
17527         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17528       // If second multiplifer is pow2, issue it first. We want the multiply by
17529       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17530       // is an add.
17531       std::swap(MulAmt1, MulAmt2);
17532
17533     SDValue NewMul;
17534     if (isPowerOf2_64(MulAmt1))
17535       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17536                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17537     else
17538       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17539                            DAG.getConstant(MulAmt1, VT));
17540
17541     if (isPowerOf2_64(MulAmt2))
17542       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17543                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17544     else
17545       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17546                            DAG.getConstant(MulAmt2, VT));
17547
17548     // Do not add new nodes to DAG combiner worklist.
17549     DCI.CombineTo(N, NewMul, false);
17550   }
17551   return SDValue();
17552 }
17553
17554 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17555   SDValue N0 = N->getOperand(0);
17556   SDValue N1 = N->getOperand(1);
17557   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17558   EVT VT = N0.getValueType();
17559
17560   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17561   // since the result of setcc_c is all zero's or all ones.
17562   if (VT.isInteger() && !VT.isVector() &&
17563       N1C && N0.getOpcode() == ISD::AND &&
17564       N0.getOperand(1).getOpcode() == ISD::Constant) {
17565     SDValue N00 = N0.getOperand(0);
17566     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17567         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17568           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17569          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17570       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17571       APInt ShAmt = N1C->getAPIntValue();
17572       Mask = Mask.shl(ShAmt);
17573       if (Mask != 0)
17574         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17575                            N00, DAG.getConstant(Mask, VT));
17576     }
17577   }
17578
17579   // Hardware support for vector shifts is sparse which makes us scalarize the
17580   // vector operations in many cases. Also, on sandybridge ADD is faster than
17581   // shl.
17582   // (shl V, 1) -> add V,V
17583   if (isSplatVector(N1.getNode())) {
17584     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17585     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17586     // We shift all of the values by one. In many cases we do not have
17587     // hardware support for this operation. This is better expressed as an ADD
17588     // of two values.
17589     if (N1C && (1 == N1C->getZExtValue())) {
17590       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17591     }
17592   }
17593
17594   return SDValue();
17595 }
17596
17597 /// \brief Returns a vector of 0s if the node in input is a vector logical
17598 /// shift by a constant amount which is known to be bigger than or equal
17599 /// to the vector element size in bits.
17600 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17601                                       const X86Subtarget *Subtarget) {
17602   EVT VT = N->getValueType(0);
17603
17604   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17605       (!Subtarget->hasInt256() ||
17606        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17607     return SDValue();
17608
17609   SDValue Amt = N->getOperand(1);
17610   SDLoc DL(N);
17611   if (isSplatVector(Amt.getNode())) {
17612     SDValue SclrAmt = Amt->getOperand(0);
17613     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17614       APInt ShiftAmt = C->getAPIntValue();
17615       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17616
17617       // SSE2/AVX2 logical shifts always return a vector of 0s
17618       // if the shift amount is bigger than or equal to
17619       // the element size. The constant shift amount will be
17620       // encoded as a 8-bit immediate.
17621       if (ShiftAmt.trunc(8).uge(MaxAmount))
17622         return getZeroVector(VT, Subtarget, DAG, DL);
17623     }
17624   }
17625
17626   return SDValue();
17627 }
17628
17629 /// PerformShiftCombine - Combine shifts.
17630 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17631                                    TargetLowering::DAGCombinerInfo &DCI,
17632                                    const X86Subtarget *Subtarget) {
17633   if (N->getOpcode() == ISD::SHL) {
17634     SDValue V = PerformSHLCombine(N, DAG);
17635     if (V.getNode()) return V;
17636   }
17637
17638   if (N->getOpcode() != ISD::SRA) {
17639     // Try to fold this logical shift into a zero vector.
17640     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17641     if (V.getNode()) return V;
17642   }
17643
17644   return SDValue();
17645 }
17646
17647 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17648 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17649 // and friends.  Likewise for OR -> CMPNEQSS.
17650 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17651                             TargetLowering::DAGCombinerInfo &DCI,
17652                             const X86Subtarget *Subtarget) {
17653   unsigned opcode;
17654
17655   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17656   // we're requiring SSE2 for both.
17657   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17658     SDValue N0 = N->getOperand(0);
17659     SDValue N1 = N->getOperand(1);
17660     SDValue CMP0 = N0->getOperand(1);
17661     SDValue CMP1 = N1->getOperand(1);
17662     SDLoc DL(N);
17663
17664     // The SETCCs should both refer to the same CMP.
17665     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17666       return SDValue();
17667
17668     SDValue CMP00 = CMP0->getOperand(0);
17669     SDValue CMP01 = CMP0->getOperand(1);
17670     EVT     VT    = CMP00.getValueType();
17671
17672     if (VT == MVT::f32 || VT == MVT::f64) {
17673       bool ExpectingFlags = false;
17674       // Check for any users that want flags:
17675       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17676            !ExpectingFlags && UI != UE; ++UI)
17677         switch (UI->getOpcode()) {
17678         default:
17679         case ISD::BR_CC:
17680         case ISD::BRCOND:
17681         case ISD::SELECT:
17682           ExpectingFlags = true;
17683           break;
17684         case ISD::CopyToReg:
17685         case ISD::SIGN_EXTEND:
17686         case ISD::ZERO_EXTEND:
17687         case ISD::ANY_EXTEND:
17688           break;
17689         }
17690
17691       if (!ExpectingFlags) {
17692         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17693         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17694
17695         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17696           X86::CondCode tmp = cc0;
17697           cc0 = cc1;
17698           cc1 = tmp;
17699         }
17700
17701         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
17702             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17703           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17704           // FIXME: need symbolic constants for these magic numbers.
17705           // See X86ATTInstPrinter.cpp:printSSECC().
17706           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17707           if (Subtarget->hasAVX512()) {
17708             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00, CMP01,
17709                                DAG.getConstant(x86cc, MVT::i8));
17710             if (N->getValueType(0) != MVT::i1)
17711               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0), FSetCC);
17712             return FSetCC;
17713           }
17714           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00, CMP01,
17715                                               DAG.getConstant(x86cc, MVT::i8));
17716           MVT IntVT = (is64BitFP ? MVT::i64 : MVT::i32); 
17717           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
17718                                               OnesOrZeroesF);
17719           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
17720                                       DAG.getConstant(1, IntVT));
17721           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17722           return OneBitOfTruth;
17723         }
17724       }
17725     }
17726   }
17727   return SDValue();
17728 }
17729
17730 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17731 /// so it can be folded inside ANDNP.
17732 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17733   EVT VT = N->getValueType(0);
17734
17735   // Match direct AllOnes for 128 and 256-bit vectors
17736   if (ISD::isBuildVectorAllOnes(N))
17737     return true;
17738
17739   // Look through a bit convert.
17740   if (N->getOpcode() == ISD::BITCAST)
17741     N = N->getOperand(0).getNode();
17742
17743   // Sometimes the operand may come from a insert_subvector building a 256-bit
17744   // allones vector
17745   if (VT.is256BitVector() &&
17746       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17747     SDValue V1 = N->getOperand(0);
17748     SDValue V2 = N->getOperand(1);
17749
17750     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17751         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17752         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17753         ISD::isBuildVectorAllOnes(V2.getNode()))
17754       return true;
17755   }
17756
17757   return false;
17758 }
17759
17760 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17761 // register. In most cases we actually compare or select YMM-sized registers
17762 // and mixing the two types creates horrible code. This method optimizes
17763 // some of the transition sequences.
17764 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17765                                  TargetLowering::DAGCombinerInfo &DCI,
17766                                  const X86Subtarget *Subtarget) {
17767   EVT VT = N->getValueType(0);
17768   if (!VT.is256BitVector())
17769     return SDValue();
17770
17771   assert((N->getOpcode() == ISD::ANY_EXTEND ||
17772           N->getOpcode() == ISD::ZERO_EXTEND ||
17773           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17774
17775   SDValue Narrow = N->getOperand(0);
17776   EVT NarrowVT = Narrow->getValueType(0);
17777   if (!NarrowVT.is128BitVector())
17778     return SDValue();
17779
17780   if (Narrow->getOpcode() != ISD::XOR &&
17781       Narrow->getOpcode() != ISD::AND &&
17782       Narrow->getOpcode() != ISD::OR)
17783     return SDValue();
17784
17785   SDValue N0  = Narrow->getOperand(0);
17786   SDValue N1  = Narrow->getOperand(1);
17787   SDLoc DL(Narrow);
17788
17789   // The Left side has to be a trunc.
17790   if (N0.getOpcode() != ISD::TRUNCATE)
17791     return SDValue();
17792
17793   // The type of the truncated inputs.
17794   EVT WideVT = N0->getOperand(0)->getValueType(0);
17795   if (WideVT != VT)
17796     return SDValue();
17797
17798   // The right side has to be a 'trunc' or a constant vector.
17799   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17800   bool RHSConst = (isSplatVector(N1.getNode()) &&
17801                    isa<ConstantSDNode>(N1->getOperand(0)));
17802   if (!RHSTrunc && !RHSConst)
17803     return SDValue();
17804
17805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17806
17807   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17808     return SDValue();
17809
17810   // Set N0 and N1 to hold the inputs to the new wide operation.
17811   N0 = N0->getOperand(0);
17812   if (RHSConst) {
17813     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17814                      N1->getOperand(0));
17815     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17816     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17817   } else if (RHSTrunc) {
17818     N1 = N1->getOperand(0);
17819   }
17820
17821   // Generate the wide operation.
17822   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17823   unsigned Opcode = N->getOpcode();
17824   switch (Opcode) {
17825   case ISD::ANY_EXTEND:
17826     return Op;
17827   case ISD::ZERO_EXTEND: {
17828     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17829     APInt Mask = APInt::getAllOnesValue(InBits);
17830     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17831     return DAG.getNode(ISD::AND, DL, VT,
17832                        Op, DAG.getConstant(Mask, VT));
17833   }
17834   case ISD::SIGN_EXTEND:
17835     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17836                        Op, DAG.getValueType(NarrowVT));
17837   default:
17838     llvm_unreachable("Unexpected opcode");
17839   }
17840 }
17841
17842 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17843                                  TargetLowering::DAGCombinerInfo &DCI,
17844                                  const X86Subtarget *Subtarget) {
17845   EVT VT = N->getValueType(0);
17846   if (DCI.isBeforeLegalizeOps())
17847     return SDValue();
17848
17849   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17850   if (R.getNode())
17851     return R;
17852
17853   // Create BLSI, BLSR, and BZHI instructions
17854   // BLSI is X & (-X)
17855   // BLSR is X & (X-1)
17856   // BZHI is X & ((1 << Y) - 1)
17857   // BEXTR is ((X >> imm) & (2**size-1))
17858   if (VT == MVT::i32 || VT == MVT::i64) {
17859     SDValue N0 = N->getOperand(0);
17860     SDValue N1 = N->getOperand(1);
17861     SDLoc DL(N);
17862
17863     if (Subtarget->hasBMI()) {
17864       // Check LHS for neg
17865       if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17866           isZero(N0.getOperand(0)))
17867         return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17868
17869       // Check RHS for neg
17870       if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17871           isZero(N1.getOperand(0)))
17872         return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17873
17874       // Check LHS for X-1
17875       if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17876           isAllOnes(N0.getOperand(1)))
17877         return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17878
17879       // Check RHS for X-1
17880       if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17881           isAllOnes(N1.getOperand(1)))
17882         return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17883     }
17884
17885     if (Subtarget->hasBMI2()) {
17886       // Check for (and (add (shl 1, Y), -1), X)
17887       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
17888         SDValue N00 = N0.getOperand(0);
17889         if (N00.getOpcode() == ISD::SHL) {
17890           SDValue N001 = N00.getOperand(1);
17891           assert(N001.getValueType() == MVT::i8 && "unexpected type");
17892           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
17893           if (C && C->getZExtValue() == 1)
17894             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
17895         }
17896       }
17897
17898       // Check for (and X, (add (shl 1, Y), -1))
17899       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
17900         SDValue N10 = N1.getOperand(0);
17901         if (N10.getOpcode() == ISD::SHL) {
17902           SDValue N101 = N10.getOperand(1);
17903           assert(N101.getValueType() == MVT::i8 && "unexpected type");
17904           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
17905           if (C && C->getZExtValue() == 1)
17906             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
17907         }
17908       }
17909     }
17910
17911     // Check for BEXTR.
17912     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
17913         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
17914       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
17915       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17916       if (MaskNode && ShiftNode) {
17917         uint64_t Mask = MaskNode->getZExtValue();
17918         uint64_t Shift = ShiftNode->getZExtValue();
17919         if (isMask_64(Mask)) {
17920           uint64_t MaskSize = CountPopulation_64(Mask);
17921           if (Shift + MaskSize <= VT.getSizeInBits())
17922             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
17923                                DAG.getConstant(Shift | (MaskSize << 8), VT));
17924         }
17925       }
17926     } // BEXTR
17927
17928     return SDValue();
17929   }
17930
17931   // Want to form ANDNP nodes:
17932   // 1) In the hopes of then easily combining them with OR and AND nodes
17933   //    to form PBLEND/PSIGN.
17934   // 2) To match ANDN packed intrinsics
17935   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17936     return SDValue();
17937
17938   SDValue N0 = N->getOperand(0);
17939   SDValue N1 = N->getOperand(1);
17940   SDLoc DL(N);
17941
17942   // Check LHS for vnot
17943   if (N0.getOpcode() == ISD::XOR &&
17944       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17945       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17946     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17947
17948   // Check RHS for vnot
17949   if (N1.getOpcode() == ISD::XOR &&
17950       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17951       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17952     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17953
17954   return SDValue();
17955 }
17956
17957 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17958                                 TargetLowering::DAGCombinerInfo &DCI,
17959                                 const X86Subtarget *Subtarget) {
17960   EVT VT = N->getValueType(0);
17961   if (DCI.isBeforeLegalizeOps())
17962     return SDValue();
17963
17964   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17965   if (R.getNode())
17966     return R;
17967
17968   SDValue N0 = N->getOperand(0);
17969   SDValue N1 = N->getOperand(1);
17970
17971   // look for psign/blend
17972   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17973     if (!Subtarget->hasSSSE3() ||
17974         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17975       return SDValue();
17976
17977     // Canonicalize pandn to RHS
17978     if (N0.getOpcode() == X86ISD::ANDNP)
17979       std::swap(N0, N1);
17980     // or (and (m, y), (pandn m, x))
17981     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17982       SDValue Mask = N1.getOperand(0);
17983       SDValue X    = N1.getOperand(1);
17984       SDValue Y;
17985       if (N0.getOperand(0) == Mask)
17986         Y = N0.getOperand(1);
17987       if (N0.getOperand(1) == Mask)
17988         Y = N0.getOperand(0);
17989
17990       // Check to see if the mask appeared in both the AND and ANDNP and
17991       if (!Y.getNode())
17992         return SDValue();
17993
17994       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17995       // Look through mask bitcast.
17996       if (Mask.getOpcode() == ISD::BITCAST)
17997         Mask = Mask.getOperand(0);
17998       if (X.getOpcode() == ISD::BITCAST)
17999         X = X.getOperand(0);
18000       if (Y.getOpcode() == ISD::BITCAST)
18001         Y = Y.getOperand(0);
18002
18003       EVT MaskVT = Mask.getValueType();
18004
18005       // Validate that the Mask operand is a vector sra node.
18006       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18007       // there is no psrai.b
18008       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18009       unsigned SraAmt = ~0;
18010       if (Mask.getOpcode() == ISD::SRA) {
18011         SDValue Amt = Mask.getOperand(1);
18012         if (isSplatVector(Amt.getNode())) {
18013           SDValue SclrAmt = Amt->getOperand(0);
18014           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18015             SraAmt = C->getZExtValue();
18016         }
18017       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18018         SDValue SraC = Mask.getOperand(1);
18019         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18020       }
18021       if ((SraAmt + 1) != EltBits)
18022         return SDValue();
18023
18024       SDLoc DL(N);
18025
18026       // Now we know we at least have a plendvb with the mask val.  See if
18027       // we can form a psignb/w/d.
18028       // psign = x.type == y.type == mask.type && y = sub(0, x);
18029       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18030           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18031           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18032         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18033                "Unsupported VT for PSIGN");
18034         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18035         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18036       }
18037       // PBLENDVB only available on SSE 4.1
18038       if (!Subtarget->hasSSE41())
18039         return SDValue();
18040
18041       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18042
18043       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18044       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18045       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18046       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18047       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18048     }
18049   }
18050
18051   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18052     return SDValue();
18053
18054   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18055   MachineFunction &MF = DAG.getMachineFunction();
18056   bool OptForSize = MF.getFunction()->getAttributes().
18057     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18058
18059   // SHLD/SHRD instructions have lower register pressure, but on some
18060   // platforms they have higher latency than the equivalent
18061   // series of shifts/or that would otherwise be generated.
18062   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18063   // have higher latencies and we are not optimizing for size.
18064   if (!OptForSize && Subtarget->isSHLDSlow())
18065     return SDValue();
18066
18067   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18068     std::swap(N0, N1);
18069   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18070     return SDValue();
18071   if (!N0.hasOneUse() || !N1.hasOneUse())
18072     return SDValue();
18073
18074   SDValue ShAmt0 = N0.getOperand(1);
18075   if (ShAmt0.getValueType() != MVT::i8)
18076     return SDValue();
18077   SDValue ShAmt1 = N1.getOperand(1);
18078   if (ShAmt1.getValueType() != MVT::i8)
18079     return SDValue();
18080   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18081     ShAmt0 = ShAmt0.getOperand(0);
18082   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18083     ShAmt1 = ShAmt1.getOperand(0);
18084
18085   SDLoc DL(N);
18086   unsigned Opc = X86ISD::SHLD;
18087   SDValue Op0 = N0.getOperand(0);
18088   SDValue Op1 = N1.getOperand(0);
18089   if (ShAmt0.getOpcode() == ISD::SUB) {
18090     Opc = X86ISD::SHRD;
18091     std::swap(Op0, Op1);
18092     std::swap(ShAmt0, ShAmt1);
18093   }
18094
18095   unsigned Bits = VT.getSizeInBits();
18096   if (ShAmt1.getOpcode() == ISD::SUB) {
18097     SDValue Sum = ShAmt1.getOperand(0);
18098     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18099       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18100       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18101         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18102       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18103         return DAG.getNode(Opc, DL, VT,
18104                            Op0, Op1,
18105                            DAG.getNode(ISD::TRUNCATE, DL,
18106                                        MVT::i8, ShAmt0));
18107     }
18108   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18109     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18110     if (ShAmt0C &&
18111         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18112       return DAG.getNode(Opc, DL, VT,
18113                          N0.getOperand(0), N1.getOperand(0),
18114                          DAG.getNode(ISD::TRUNCATE, DL,
18115                                        MVT::i8, ShAmt0));
18116   }
18117
18118   return SDValue();
18119 }
18120
18121 // Generate NEG and CMOV for integer abs.
18122 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18123   EVT VT = N->getValueType(0);
18124
18125   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18126   // 8-bit integer abs to NEG and CMOV.
18127   if (VT.isInteger() && VT.getSizeInBits() == 8)
18128     return SDValue();
18129
18130   SDValue N0 = N->getOperand(0);
18131   SDValue N1 = N->getOperand(1);
18132   SDLoc DL(N);
18133
18134   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18135   // and change it to SUB and CMOV.
18136   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18137       N0.getOpcode() == ISD::ADD &&
18138       N0.getOperand(1) == N1 &&
18139       N1.getOpcode() == ISD::SRA &&
18140       N1.getOperand(0) == N0.getOperand(0))
18141     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18142       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18143         // Generate SUB & CMOV.
18144         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18145                                   DAG.getConstant(0, VT), N0.getOperand(0));
18146
18147         SDValue Ops[] = { N0.getOperand(0), Neg,
18148                           DAG.getConstant(X86::COND_GE, MVT::i8),
18149                           SDValue(Neg.getNode(), 1) };
18150         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18151                            Ops, array_lengthof(Ops));
18152       }
18153   return SDValue();
18154 }
18155
18156 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18157 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18158                                  TargetLowering::DAGCombinerInfo &DCI,
18159                                  const X86Subtarget *Subtarget) {
18160   EVT VT = N->getValueType(0);
18161   if (DCI.isBeforeLegalizeOps())
18162     return SDValue();
18163
18164   if (Subtarget->hasCMov()) {
18165     SDValue RV = performIntegerAbsCombine(N, DAG);
18166     if (RV.getNode())
18167       return RV;
18168   }
18169
18170   // Try forming BMI if it is available.
18171   if (!Subtarget->hasBMI())
18172     return SDValue();
18173
18174   if (VT != MVT::i32 && VT != MVT::i64)
18175     return SDValue();
18176
18177   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
18178
18179   // Create BLSMSK instructions by finding X ^ (X-1)
18180   SDValue N0 = N->getOperand(0);
18181   SDValue N1 = N->getOperand(1);
18182   SDLoc DL(N);
18183
18184   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
18185       isAllOnes(N0.getOperand(1)))
18186     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
18187
18188   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
18189       isAllOnes(N1.getOperand(1)))
18190     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
18191
18192   return SDValue();
18193 }
18194
18195 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18196 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18197                                   TargetLowering::DAGCombinerInfo &DCI,
18198                                   const X86Subtarget *Subtarget) {
18199   LoadSDNode *Ld = cast<LoadSDNode>(N);
18200   EVT RegVT = Ld->getValueType(0);
18201   EVT MemVT = Ld->getMemoryVT();
18202   SDLoc dl(Ld);
18203   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18204   unsigned RegSz = RegVT.getSizeInBits();
18205
18206   // On Sandybridge unaligned 256bit loads are inefficient.
18207   ISD::LoadExtType Ext = Ld->getExtensionType();
18208   unsigned Alignment = Ld->getAlignment();
18209   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18210   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18211       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18212     unsigned NumElems = RegVT.getVectorNumElements();
18213     if (NumElems < 2)
18214       return SDValue();
18215
18216     SDValue Ptr = Ld->getBasePtr();
18217     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18218
18219     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18220                                   NumElems/2);
18221     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18222                                 Ld->getPointerInfo(), Ld->isVolatile(),
18223                                 Ld->isNonTemporal(), Ld->isInvariant(),
18224                                 Alignment);
18225     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18226     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18227                                 Ld->getPointerInfo(), Ld->isVolatile(),
18228                                 Ld->isNonTemporal(), Ld->isInvariant(),
18229                                 std::min(16U, Alignment));
18230     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18231                              Load1.getValue(1),
18232                              Load2.getValue(1));
18233
18234     SDValue NewVec = DAG.getUNDEF(RegVT);
18235     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18236     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18237     return DCI.CombineTo(N, NewVec, TF, true);
18238   }
18239
18240   // If this is a vector EXT Load then attempt to optimize it using a
18241   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18242   // expansion is still better than scalar code.
18243   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18244   // emit a shuffle and a arithmetic shift.
18245   // TODO: It is possible to support ZExt by zeroing the undef values
18246   // during the shuffle phase or after the shuffle.
18247   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18248       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18249     assert(MemVT != RegVT && "Cannot extend to the same type");
18250     assert(MemVT.isVector() && "Must load a vector from memory");
18251
18252     unsigned NumElems = RegVT.getVectorNumElements();
18253     unsigned MemSz = MemVT.getSizeInBits();
18254     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18255
18256     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18257       return SDValue();
18258
18259     // All sizes must be a power of two.
18260     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18261       return SDValue();
18262
18263     // Attempt to load the original value using scalar loads.
18264     // Find the largest scalar type that divides the total loaded size.
18265     MVT SclrLoadTy = MVT::i8;
18266     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18267          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18268       MVT Tp = (MVT::SimpleValueType)tp;
18269       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18270         SclrLoadTy = Tp;
18271       }
18272     }
18273
18274     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18275     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18276         (64 <= MemSz))
18277       SclrLoadTy = MVT::f64;
18278
18279     // Calculate the number of scalar loads that we need to perform
18280     // in order to load our vector from memory.
18281     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18282     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18283       return SDValue();
18284
18285     unsigned loadRegZize = RegSz;
18286     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18287       loadRegZize /= 2;
18288
18289     // Represent our vector as a sequence of elements which are the
18290     // largest scalar that we can load.
18291     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18292       loadRegZize/SclrLoadTy.getSizeInBits());
18293
18294     // Represent the data using the same element type that is stored in
18295     // memory. In practice, we ''widen'' MemVT.
18296     EVT WideVecVT =
18297           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18298                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18299
18300     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18301       "Invalid vector type");
18302
18303     // We can't shuffle using an illegal type.
18304     if (!TLI.isTypeLegal(WideVecVT))
18305       return SDValue();
18306
18307     SmallVector<SDValue, 8> Chains;
18308     SDValue Ptr = Ld->getBasePtr();
18309     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18310                                         TLI.getPointerTy());
18311     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18312
18313     for (unsigned i = 0; i < NumLoads; ++i) {
18314       // Perform a single load.
18315       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18316                                        Ptr, Ld->getPointerInfo(),
18317                                        Ld->isVolatile(), Ld->isNonTemporal(),
18318                                        Ld->isInvariant(), Ld->getAlignment());
18319       Chains.push_back(ScalarLoad.getValue(1));
18320       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18321       // another round of DAGCombining.
18322       if (i == 0)
18323         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18324       else
18325         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18326                           ScalarLoad, DAG.getIntPtrConstant(i));
18327
18328       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18329     }
18330
18331     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18332                                Chains.size());
18333
18334     // Bitcast the loaded value to a vector of the original element type, in
18335     // the size of the target vector type.
18336     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18337     unsigned SizeRatio = RegSz/MemSz;
18338
18339     if (Ext == ISD::SEXTLOAD) {
18340       // If we have SSE4.1 we can directly emit a VSEXT node.
18341       if (Subtarget->hasSSE41()) {
18342         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18343         return DCI.CombineTo(N, Sext, TF, true);
18344       }
18345
18346       // Otherwise we'll shuffle the small elements in the high bits of the
18347       // larger type and perform an arithmetic shift. If the shift is not legal
18348       // it's better to scalarize.
18349       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18350         return SDValue();
18351
18352       // Redistribute the loaded elements into the different locations.
18353       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18354       for (unsigned i = 0; i != NumElems; ++i)
18355         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18356
18357       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18358                                            DAG.getUNDEF(WideVecVT),
18359                                            &ShuffleVec[0]);
18360
18361       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18362
18363       // Build the arithmetic shift.
18364       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18365                      MemVT.getVectorElementType().getSizeInBits();
18366       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18367                           DAG.getConstant(Amt, RegVT));
18368
18369       return DCI.CombineTo(N, Shuff, TF, true);
18370     }
18371
18372     // Redistribute the loaded elements into the different locations.
18373     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18374     for (unsigned i = 0; i != NumElems; ++i)
18375       ShuffleVec[i*SizeRatio] = i;
18376
18377     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18378                                          DAG.getUNDEF(WideVecVT),
18379                                          &ShuffleVec[0]);
18380
18381     // Bitcast to the requested type.
18382     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18383     // Replace the original load with the new sequence
18384     // and return the new chain.
18385     return DCI.CombineTo(N, Shuff, TF, true);
18386   }
18387
18388   return SDValue();
18389 }
18390
18391 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18392 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18393                                    const X86Subtarget *Subtarget) {
18394   StoreSDNode *St = cast<StoreSDNode>(N);
18395   EVT VT = St->getValue().getValueType();
18396   EVT StVT = St->getMemoryVT();
18397   SDLoc dl(St);
18398   SDValue StoredVal = St->getOperand(1);
18399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18400
18401   // If we are saving a concatenation of two XMM registers, perform two stores.
18402   // On Sandy Bridge, 256-bit memory operations are executed by two
18403   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18404   // memory  operation.
18405   unsigned Alignment = St->getAlignment();
18406   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18407   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18408       StVT == VT && !IsAligned) {
18409     unsigned NumElems = VT.getVectorNumElements();
18410     if (NumElems < 2)
18411       return SDValue();
18412
18413     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18414     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18415
18416     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18417     SDValue Ptr0 = St->getBasePtr();
18418     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18419
18420     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18421                                 St->getPointerInfo(), St->isVolatile(),
18422                                 St->isNonTemporal(), Alignment);
18423     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18424                                 St->getPointerInfo(), St->isVolatile(),
18425                                 St->isNonTemporal(),
18426                                 std::min(16U, Alignment));
18427     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18428   }
18429
18430   // Optimize trunc store (of multiple scalars) to shuffle and store.
18431   // First, pack all of the elements in one place. Next, store to memory
18432   // in fewer chunks.
18433   if (St->isTruncatingStore() && VT.isVector()) {
18434     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18435     unsigned NumElems = VT.getVectorNumElements();
18436     assert(StVT != VT && "Cannot truncate to the same type");
18437     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18438     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18439
18440     // From, To sizes and ElemCount must be pow of two
18441     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18442     // We are going to use the original vector elt for storing.
18443     // Accumulated smaller vector elements must be a multiple of the store size.
18444     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18445
18446     unsigned SizeRatio  = FromSz / ToSz;
18447
18448     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18449
18450     // Create a type on which we perform the shuffle
18451     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18452             StVT.getScalarType(), NumElems*SizeRatio);
18453
18454     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18455
18456     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18457     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18458     for (unsigned i = 0; i != NumElems; ++i)
18459       ShuffleVec[i] = i * SizeRatio;
18460
18461     // Can't shuffle using an illegal type.
18462     if (!TLI.isTypeLegal(WideVecVT))
18463       return SDValue();
18464
18465     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18466                                          DAG.getUNDEF(WideVecVT),
18467                                          &ShuffleVec[0]);
18468     // At this point all of the data is stored at the bottom of the
18469     // register. We now need to save it to mem.
18470
18471     // Find the largest store unit
18472     MVT StoreType = MVT::i8;
18473     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18474          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18475       MVT Tp = (MVT::SimpleValueType)tp;
18476       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18477         StoreType = Tp;
18478     }
18479
18480     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18481     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18482         (64 <= NumElems * ToSz))
18483       StoreType = MVT::f64;
18484
18485     // Bitcast the original vector into a vector of store-size units
18486     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18487             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18488     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18489     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18490     SmallVector<SDValue, 8> Chains;
18491     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18492                                         TLI.getPointerTy());
18493     SDValue Ptr = St->getBasePtr();
18494
18495     // Perform one or more big stores into memory.
18496     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18497       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18498                                    StoreType, ShuffWide,
18499                                    DAG.getIntPtrConstant(i));
18500       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18501                                 St->getPointerInfo(), St->isVolatile(),
18502                                 St->isNonTemporal(), St->getAlignment());
18503       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18504       Chains.push_back(Ch);
18505     }
18506
18507     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18508                                Chains.size());
18509   }
18510
18511   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18512   // the FP state in cases where an emms may be missing.
18513   // A preferable solution to the general problem is to figure out the right
18514   // places to insert EMMS.  This qualifies as a quick hack.
18515
18516   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18517   if (VT.getSizeInBits() != 64)
18518     return SDValue();
18519
18520   const Function *F = DAG.getMachineFunction().getFunction();
18521   bool NoImplicitFloatOps = F->getAttributes().
18522     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18523   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18524                      && Subtarget->hasSSE2();
18525   if ((VT.isVector() ||
18526        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18527       isa<LoadSDNode>(St->getValue()) &&
18528       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18529       St->getChain().hasOneUse() && !St->isVolatile()) {
18530     SDNode* LdVal = St->getValue().getNode();
18531     LoadSDNode *Ld = 0;
18532     int TokenFactorIndex = -1;
18533     SmallVector<SDValue, 8> Ops;
18534     SDNode* ChainVal = St->getChain().getNode();
18535     // Must be a store of a load.  We currently handle two cases:  the load
18536     // is a direct child, and it's under an intervening TokenFactor.  It is
18537     // possible to dig deeper under nested TokenFactors.
18538     if (ChainVal == LdVal)
18539       Ld = cast<LoadSDNode>(St->getChain());
18540     else if (St->getValue().hasOneUse() &&
18541              ChainVal->getOpcode() == ISD::TokenFactor) {
18542       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18543         if (ChainVal->getOperand(i).getNode() == LdVal) {
18544           TokenFactorIndex = i;
18545           Ld = cast<LoadSDNode>(St->getValue());
18546         } else
18547           Ops.push_back(ChainVal->getOperand(i));
18548       }
18549     }
18550
18551     if (!Ld || !ISD::isNormalLoad(Ld))
18552       return SDValue();
18553
18554     // If this is not the MMX case, i.e. we are just turning i64 load/store
18555     // into f64 load/store, avoid the transformation if there are multiple
18556     // uses of the loaded value.
18557     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18558       return SDValue();
18559
18560     SDLoc LdDL(Ld);
18561     SDLoc StDL(N);
18562     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18563     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18564     // pair instead.
18565     if (Subtarget->is64Bit() || F64IsLegal) {
18566       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18567       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18568                                   Ld->getPointerInfo(), Ld->isVolatile(),
18569                                   Ld->isNonTemporal(), Ld->isInvariant(),
18570                                   Ld->getAlignment());
18571       SDValue NewChain = NewLd.getValue(1);
18572       if (TokenFactorIndex != -1) {
18573         Ops.push_back(NewChain);
18574         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18575                                Ops.size());
18576       }
18577       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18578                           St->getPointerInfo(),
18579                           St->isVolatile(), St->isNonTemporal(),
18580                           St->getAlignment());
18581     }
18582
18583     // Otherwise, lower to two pairs of 32-bit loads / stores.
18584     SDValue LoAddr = Ld->getBasePtr();
18585     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18586                                  DAG.getConstant(4, MVT::i32));
18587
18588     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18589                                Ld->getPointerInfo(),
18590                                Ld->isVolatile(), Ld->isNonTemporal(),
18591                                Ld->isInvariant(), Ld->getAlignment());
18592     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18593                                Ld->getPointerInfo().getWithOffset(4),
18594                                Ld->isVolatile(), Ld->isNonTemporal(),
18595                                Ld->isInvariant(),
18596                                MinAlign(Ld->getAlignment(), 4));
18597
18598     SDValue NewChain = LoLd.getValue(1);
18599     if (TokenFactorIndex != -1) {
18600       Ops.push_back(LoLd);
18601       Ops.push_back(HiLd);
18602       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18603                              Ops.size());
18604     }
18605
18606     LoAddr = St->getBasePtr();
18607     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18608                          DAG.getConstant(4, MVT::i32));
18609
18610     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18611                                 St->getPointerInfo(),
18612                                 St->isVolatile(), St->isNonTemporal(),
18613                                 St->getAlignment());
18614     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18615                                 St->getPointerInfo().getWithOffset(4),
18616                                 St->isVolatile(),
18617                                 St->isNonTemporal(),
18618                                 MinAlign(St->getAlignment(), 4));
18619     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18620   }
18621   return SDValue();
18622 }
18623
18624 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18625 /// and return the operands for the horizontal operation in LHS and RHS.  A
18626 /// horizontal operation performs the binary operation on successive elements
18627 /// of its first operand, then on successive elements of its second operand,
18628 /// returning the resulting values in a vector.  For example, if
18629 ///   A = < float a0, float a1, float a2, float a3 >
18630 /// and
18631 ///   B = < float b0, float b1, float b2, float b3 >
18632 /// then the result of doing a horizontal operation on A and B is
18633 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18634 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18635 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18636 /// set to A, RHS to B, and the routine returns 'true'.
18637 /// Note that the binary operation should have the property that if one of the
18638 /// operands is UNDEF then the result is UNDEF.
18639 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18640   // Look for the following pattern: if
18641   //   A = < float a0, float a1, float a2, float a3 >
18642   //   B = < float b0, float b1, float b2, float b3 >
18643   // and
18644   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18645   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18646   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18647   // which is A horizontal-op B.
18648
18649   // At least one of the operands should be a vector shuffle.
18650   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18651       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18652     return false;
18653
18654   MVT VT = LHS.getSimpleValueType();
18655
18656   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18657          "Unsupported vector type for horizontal add/sub");
18658
18659   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18660   // operate independently on 128-bit lanes.
18661   unsigned NumElts = VT.getVectorNumElements();
18662   unsigned NumLanes = VT.getSizeInBits()/128;
18663   unsigned NumLaneElts = NumElts / NumLanes;
18664   assert((NumLaneElts % 2 == 0) &&
18665          "Vector type should have an even number of elements in each lane");
18666   unsigned HalfLaneElts = NumLaneElts/2;
18667
18668   // View LHS in the form
18669   //   LHS = VECTOR_SHUFFLE A, B, LMask
18670   // If LHS is not a shuffle then pretend it is the shuffle
18671   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18672   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18673   // type VT.
18674   SDValue A, B;
18675   SmallVector<int, 16> LMask(NumElts);
18676   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18677     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18678       A = LHS.getOperand(0);
18679     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18680       B = LHS.getOperand(1);
18681     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18682     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18683   } else {
18684     if (LHS.getOpcode() != ISD::UNDEF)
18685       A = LHS;
18686     for (unsigned i = 0; i != NumElts; ++i)
18687       LMask[i] = i;
18688   }
18689
18690   // Likewise, view RHS in the form
18691   //   RHS = VECTOR_SHUFFLE C, D, RMask
18692   SDValue C, D;
18693   SmallVector<int, 16> RMask(NumElts);
18694   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18695     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18696       C = RHS.getOperand(0);
18697     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18698       D = RHS.getOperand(1);
18699     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18700     std::copy(Mask.begin(), Mask.end(), RMask.begin());
18701   } else {
18702     if (RHS.getOpcode() != ISD::UNDEF)
18703       C = RHS;
18704     for (unsigned i = 0; i != NumElts; ++i)
18705       RMask[i] = i;
18706   }
18707
18708   // Check that the shuffles are both shuffling the same vectors.
18709   if (!(A == C && B == D) && !(A == D && B == C))
18710     return false;
18711
18712   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18713   if (!A.getNode() && !B.getNode())
18714     return false;
18715
18716   // If A and B occur in reverse order in RHS, then "swap" them (which means
18717   // rewriting the mask).
18718   if (A != C)
18719     CommuteVectorShuffleMask(RMask, NumElts);
18720
18721   // At this point LHS and RHS are equivalent to
18722   //   LHS = VECTOR_SHUFFLE A, B, LMask
18723   //   RHS = VECTOR_SHUFFLE A, B, RMask
18724   // Check that the masks correspond to performing a horizontal operation.
18725   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18726     for (unsigned i = 0; i != NumLaneElts; ++i) {
18727       int LIdx = LMask[i+l], RIdx = RMask[i+l];
18728
18729       // Ignore any UNDEF components.
18730       if (LIdx < 0 || RIdx < 0 ||
18731           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18732           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18733         continue;
18734
18735       // Check that successive elements are being operated on.  If not, this is
18736       // not a horizontal operation.
18737       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18738       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18739       if (!(LIdx == Index && RIdx == Index + 1) &&
18740           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18741         return false;
18742     }
18743   }
18744
18745   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18746   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18747   return true;
18748 }
18749
18750 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18751 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18752                                   const X86Subtarget *Subtarget) {
18753   EVT VT = N->getValueType(0);
18754   SDValue LHS = N->getOperand(0);
18755   SDValue RHS = N->getOperand(1);
18756
18757   // Try to synthesize horizontal adds from adds of shuffles.
18758   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18759        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18760       isHorizontalBinOp(LHS, RHS, true))
18761     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18762   return SDValue();
18763 }
18764
18765 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18766 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18767                                   const X86Subtarget *Subtarget) {
18768   EVT VT = N->getValueType(0);
18769   SDValue LHS = N->getOperand(0);
18770   SDValue RHS = N->getOperand(1);
18771
18772   // Try to synthesize horizontal subs from subs of shuffles.
18773   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18774        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18775       isHorizontalBinOp(LHS, RHS, false))
18776     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18777   return SDValue();
18778 }
18779
18780 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18781 /// X86ISD::FXOR nodes.
18782 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18783   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18784   // F[X]OR(0.0, x) -> x
18785   // F[X]OR(x, 0.0) -> x
18786   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18787     if (C->getValueAPF().isPosZero())
18788       return N->getOperand(1);
18789   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18790     if (C->getValueAPF().isPosZero())
18791       return N->getOperand(0);
18792   return SDValue();
18793 }
18794
18795 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18796 /// X86ISD::FMAX nodes.
18797 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18798   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18799
18800   // Only perform optimizations if UnsafeMath is used.
18801   if (!DAG.getTarget().Options.UnsafeFPMath)
18802     return SDValue();
18803
18804   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18805   // into FMINC and FMAXC, which are Commutative operations.
18806   unsigned NewOp = 0;
18807   switch (N->getOpcode()) {
18808     default: llvm_unreachable("unknown opcode");
18809     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
18810     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
18811   }
18812
18813   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18814                      N->getOperand(0), N->getOperand(1));
18815 }
18816
18817 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18818 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18819   // FAND(0.0, x) -> 0.0
18820   // FAND(x, 0.0) -> 0.0
18821   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18822     if (C->getValueAPF().isPosZero())
18823       return N->getOperand(0);
18824   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18825     if (C->getValueAPF().isPosZero())
18826       return N->getOperand(1);
18827   return SDValue();
18828 }
18829
18830 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18831 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18832   // FANDN(x, 0.0) -> 0.0
18833   // FANDN(0.0, x) -> x
18834   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18835     if (C->getValueAPF().isPosZero())
18836       return N->getOperand(1);
18837   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18838     if (C->getValueAPF().isPosZero())
18839       return N->getOperand(1);
18840   return SDValue();
18841 }
18842
18843 static SDValue PerformBTCombine(SDNode *N,
18844                                 SelectionDAG &DAG,
18845                                 TargetLowering::DAGCombinerInfo &DCI) {
18846   // BT ignores high bits in the bit index operand.
18847   SDValue Op1 = N->getOperand(1);
18848   if (Op1.hasOneUse()) {
18849     unsigned BitWidth = Op1.getValueSizeInBits();
18850     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18851     APInt KnownZero, KnownOne;
18852     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18853                                           !DCI.isBeforeLegalizeOps());
18854     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18855     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18856         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18857       DCI.CommitTargetLoweringOpt(TLO);
18858   }
18859   return SDValue();
18860 }
18861
18862 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18863   SDValue Op = N->getOperand(0);
18864   if (Op.getOpcode() == ISD::BITCAST)
18865     Op = Op.getOperand(0);
18866   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18867   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18868       VT.getVectorElementType().getSizeInBits() ==
18869       OpVT.getVectorElementType().getSizeInBits()) {
18870     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18871   }
18872   return SDValue();
18873 }
18874
18875 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18876                                                const X86Subtarget *Subtarget) {
18877   EVT VT = N->getValueType(0);
18878   if (!VT.isVector())
18879     return SDValue();
18880
18881   SDValue N0 = N->getOperand(0);
18882   SDValue N1 = N->getOperand(1);
18883   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18884   SDLoc dl(N);
18885
18886   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18887   // both SSE and AVX2 since there is no sign-extended shift right
18888   // operation on a vector with 64-bit elements.
18889   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18890   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18891   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18892       N0.getOpcode() == ISD::SIGN_EXTEND)) {
18893     SDValue N00 = N0.getOperand(0);
18894
18895     // EXTLOAD has a better solution on AVX2,
18896     // it may be replaced with X86ISD::VSEXT node.
18897     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18898       if (!ISD::isNormalLoad(N00.getNode()))
18899         return SDValue();
18900
18901     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18902         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18903                                   N00, N1);
18904       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18905     }
18906   }
18907   return SDValue();
18908 }
18909
18910 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18911                                   TargetLowering::DAGCombinerInfo &DCI,
18912                                   const X86Subtarget *Subtarget) {
18913   if (!DCI.isBeforeLegalizeOps())
18914     return SDValue();
18915
18916   if (!Subtarget->hasFp256())
18917     return SDValue();
18918
18919   EVT VT = N->getValueType(0);
18920   if (VT.isVector() && VT.getSizeInBits() == 256) {
18921     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18922     if (R.getNode())
18923       return R;
18924   }
18925
18926   return SDValue();
18927 }
18928
18929 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18930                                  const X86Subtarget* Subtarget) {
18931   SDLoc dl(N);
18932   EVT VT = N->getValueType(0);
18933
18934   // Let legalize expand this if it isn't a legal type yet.
18935   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18936     return SDValue();
18937
18938   EVT ScalarVT = VT.getScalarType();
18939   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18940       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18941     return SDValue();
18942
18943   SDValue A = N->getOperand(0);
18944   SDValue B = N->getOperand(1);
18945   SDValue C = N->getOperand(2);
18946
18947   bool NegA = (A.getOpcode() == ISD::FNEG);
18948   bool NegB = (B.getOpcode() == ISD::FNEG);
18949   bool NegC = (C.getOpcode() == ISD::FNEG);
18950
18951   // Negative multiplication when NegA xor NegB
18952   bool NegMul = (NegA != NegB);
18953   if (NegA)
18954     A = A.getOperand(0);
18955   if (NegB)
18956     B = B.getOperand(0);
18957   if (NegC)
18958     C = C.getOperand(0);
18959
18960   unsigned Opcode;
18961   if (!NegMul)
18962     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18963   else
18964     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18965
18966   return DAG.getNode(Opcode, dl, VT, A, B, C);
18967 }
18968
18969 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18970                                   TargetLowering::DAGCombinerInfo &DCI,
18971                                   const X86Subtarget *Subtarget) {
18972   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18973   //           (and (i32 x86isd::setcc_carry), 1)
18974   // This eliminates the zext. This transformation is necessary because
18975   // ISD::SETCC is always legalized to i8.
18976   SDLoc dl(N);
18977   SDValue N0 = N->getOperand(0);
18978   EVT VT = N->getValueType(0);
18979
18980   if (N0.getOpcode() == ISD::AND &&
18981       N0.hasOneUse() &&
18982       N0.getOperand(0).hasOneUse()) {
18983     SDValue N00 = N0.getOperand(0);
18984     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18985       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18986       if (!C || C->getZExtValue() != 1)
18987         return SDValue();
18988       return DAG.getNode(ISD::AND, dl, VT,
18989                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18990                                      N00.getOperand(0), N00.getOperand(1)),
18991                          DAG.getConstant(1, VT));
18992     }
18993   }
18994
18995   if (N0.getOpcode() == ISD::TRUNCATE &&
18996       N0.hasOneUse() &&
18997       N0.getOperand(0).hasOneUse()) {
18998     SDValue N00 = N0.getOperand(0);
18999     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19000       return DAG.getNode(ISD::AND, dl, VT,
19001                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19002                                      N00.getOperand(0), N00.getOperand(1)),
19003                          DAG.getConstant(1, VT));
19004     }
19005   }
19006   if (VT.is256BitVector()) {
19007     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19008     if (R.getNode())
19009       return R;
19010   }
19011
19012   return SDValue();
19013 }
19014
19015 // Optimize x == -y --> x+y == 0
19016 //          x != -y --> x+y != 0
19017 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
19018   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19019   SDValue LHS = N->getOperand(0);
19020   SDValue RHS = N->getOperand(1);
19021
19022   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19023     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19024       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19025         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19026                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19027         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19028                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19029       }
19030   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19031     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19032       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19033         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19034                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19035         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19036                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19037       }
19038   return SDValue();
19039 }
19040
19041 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19042 // as "sbb reg,reg", since it can be extended without zext and produces
19043 // an all-ones bit which is more useful than 0/1 in some cases.
19044 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19045                                MVT VT) {
19046   if (VT == MVT::i8)
19047     return DAG.getNode(ISD::AND, DL, VT,
19048                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19049                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19050                        DAG.getConstant(1, VT));
19051   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19052   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19053                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19054                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19055 }
19056
19057 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19058 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19059                                    TargetLowering::DAGCombinerInfo &DCI,
19060                                    const X86Subtarget *Subtarget) {
19061   SDLoc DL(N);
19062   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19063   SDValue EFLAGS = N->getOperand(1);
19064
19065   if (CC == X86::COND_A) {
19066     // Try to convert COND_A into COND_B in an attempt to facilitate
19067     // materializing "setb reg".
19068     //
19069     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19070     // cannot take an immediate as its first operand.
19071     //
19072     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19073         EFLAGS.getValueType().isInteger() &&
19074         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19075       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19076                                    EFLAGS.getNode()->getVTList(),
19077                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19078       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19079       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19080     }
19081   }
19082
19083   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19084   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19085   // cases.
19086   if (CC == X86::COND_B)
19087     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19088
19089   SDValue Flags;
19090
19091   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19092   if (Flags.getNode()) {
19093     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19094     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19095   }
19096
19097   return SDValue();
19098 }
19099
19100 // Optimize branch condition evaluation.
19101 //
19102 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19103                                     TargetLowering::DAGCombinerInfo &DCI,
19104                                     const X86Subtarget *Subtarget) {
19105   SDLoc DL(N);
19106   SDValue Chain = N->getOperand(0);
19107   SDValue Dest = N->getOperand(1);
19108   SDValue EFLAGS = N->getOperand(3);
19109   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19110
19111   SDValue Flags;
19112
19113   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19114   if (Flags.getNode()) {
19115     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19116     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19117                        Flags);
19118   }
19119
19120   return SDValue();
19121 }
19122
19123 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19124                                         const X86TargetLowering *XTLI) {
19125   SDValue Op0 = N->getOperand(0);
19126   EVT InVT = Op0->getValueType(0);
19127
19128   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19129   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19130     SDLoc dl(N);
19131     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19132     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19133     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19134   }
19135
19136   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19137   // a 32-bit target where SSE doesn't support i64->FP operations.
19138   if (Op0.getOpcode() == ISD::LOAD) {
19139     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19140     EVT VT = Ld->getValueType(0);
19141     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19142         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19143         !XTLI->getSubtarget()->is64Bit() &&
19144         VT == MVT::i64) {
19145       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19146                                           Ld->getChain(), Op0, DAG);
19147       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19148       return FILDChain;
19149     }
19150   }
19151   return SDValue();
19152 }
19153
19154 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19155 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19156                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19157   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19158   // the result is either zero or one (depending on the input carry bit).
19159   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19160   if (X86::isZeroNode(N->getOperand(0)) &&
19161       X86::isZeroNode(N->getOperand(1)) &&
19162       // We don't have a good way to replace an EFLAGS use, so only do this when
19163       // dead right now.
19164       SDValue(N, 1).use_empty()) {
19165     SDLoc DL(N);
19166     EVT VT = N->getValueType(0);
19167     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19168     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19169                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19170                                            DAG.getConstant(X86::COND_B,MVT::i8),
19171                                            N->getOperand(2)),
19172                                DAG.getConstant(1, VT));
19173     return DCI.CombineTo(N, Res1, CarryOut);
19174   }
19175
19176   return SDValue();
19177 }
19178
19179 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19180 //      (add Y, (setne X, 0)) -> sbb -1, Y
19181 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19182 //      (sub (setne X, 0), Y) -> adc -1, Y
19183 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19184   SDLoc DL(N);
19185
19186   // Look through ZExts.
19187   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19188   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19189     return SDValue();
19190
19191   SDValue SetCC = Ext.getOperand(0);
19192   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19193     return SDValue();
19194
19195   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19196   if (CC != X86::COND_E && CC != X86::COND_NE)
19197     return SDValue();
19198
19199   SDValue Cmp = SetCC.getOperand(1);
19200   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19201       !X86::isZeroNode(Cmp.getOperand(1)) ||
19202       !Cmp.getOperand(0).getValueType().isInteger())
19203     return SDValue();
19204
19205   SDValue CmpOp0 = Cmp.getOperand(0);
19206   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19207                                DAG.getConstant(1, CmpOp0.getValueType()));
19208
19209   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19210   if (CC == X86::COND_NE)
19211     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19212                        DL, OtherVal.getValueType(), OtherVal,
19213                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19214   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19215                      DL, OtherVal.getValueType(), OtherVal,
19216                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19217 }
19218
19219 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19220 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19221                                  const X86Subtarget *Subtarget) {
19222   EVT VT = N->getValueType(0);
19223   SDValue Op0 = N->getOperand(0);
19224   SDValue Op1 = N->getOperand(1);
19225
19226   // Try to synthesize horizontal adds from adds of shuffles.
19227   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19228        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19229       isHorizontalBinOp(Op0, Op1, true))
19230     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19231
19232   return OptimizeConditionalInDecrement(N, DAG);
19233 }
19234
19235 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19236                                  const X86Subtarget *Subtarget) {
19237   SDValue Op0 = N->getOperand(0);
19238   SDValue Op1 = N->getOperand(1);
19239
19240   // X86 can't encode an immediate LHS of a sub. See if we can push the
19241   // negation into a preceding instruction.
19242   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19243     // If the RHS of the sub is a XOR with one use and a constant, invert the
19244     // immediate. Then add one to the LHS of the sub so we can turn
19245     // X-Y -> X+~Y+1, saving one register.
19246     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19247         isa<ConstantSDNode>(Op1.getOperand(1))) {
19248       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19249       EVT VT = Op0.getValueType();
19250       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19251                                    Op1.getOperand(0),
19252                                    DAG.getConstant(~XorC, VT));
19253       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19254                          DAG.getConstant(C->getAPIntValue()+1, VT));
19255     }
19256   }
19257
19258   // Try to synthesize horizontal adds from adds of shuffles.
19259   EVT VT = N->getValueType(0);
19260   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19261        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19262       isHorizontalBinOp(Op0, Op1, true))
19263     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19264
19265   return OptimizeConditionalInDecrement(N, DAG);
19266 }
19267
19268 /// performVZEXTCombine - Performs build vector combines
19269 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19270                                         TargetLowering::DAGCombinerInfo &DCI,
19271                                         const X86Subtarget *Subtarget) {
19272   // (vzext (bitcast (vzext (x)) -> (vzext x)
19273   SDValue In = N->getOperand(0);
19274   while (In.getOpcode() == ISD::BITCAST)
19275     In = In.getOperand(0);
19276
19277   if (In.getOpcode() != X86ISD::VZEXT)
19278     return SDValue();
19279
19280   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19281                      In.getOperand(0));
19282 }
19283
19284 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19285                                              DAGCombinerInfo &DCI) const {
19286   SelectionDAG &DAG = DCI.DAG;
19287   switch (N->getOpcode()) {
19288   default: break;
19289   case ISD::EXTRACT_VECTOR_ELT:
19290     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19291   case ISD::VSELECT:
19292   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19293   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19294   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19295   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19296   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19297   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19298   case ISD::SHL:
19299   case ISD::SRA:
19300   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19301   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19302   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19303   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19304   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19305   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19306   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19307   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19308   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19309   case X86ISD::FXOR:
19310   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19311   case X86ISD::FMIN:
19312   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19313   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19314   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19315   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19316   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19317   case ISD::ANY_EXTEND:
19318   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19319   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19320   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19321   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19322   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
19323   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19324   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19325   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19326   case X86ISD::SHUFP:       // Handle all target specific shuffles
19327   case X86ISD::PALIGNR:
19328   case X86ISD::UNPCKH:
19329   case X86ISD::UNPCKL:
19330   case X86ISD::MOVHLPS:
19331   case X86ISD::MOVLHPS:
19332   case X86ISD::PSHUFD:
19333   case X86ISD::PSHUFHW:
19334   case X86ISD::PSHUFLW:
19335   case X86ISD::MOVSS:
19336   case X86ISD::MOVSD:
19337   case X86ISD::VPERMILP:
19338   case X86ISD::VPERM2X128:
19339   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19340   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19341   }
19342
19343   return SDValue();
19344 }
19345
19346 /// isTypeDesirableForOp - Return true if the target has native support for
19347 /// the specified value type and it is 'desirable' to use the type for the
19348 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19349 /// instruction encodings are longer and some i16 instructions are slow.
19350 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19351   if (!isTypeLegal(VT))
19352     return false;
19353   if (VT != MVT::i16)
19354     return true;
19355
19356   switch (Opc) {
19357   default:
19358     return true;
19359   case ISD::LOAD:
19360   case ISD::SIGN_EXTEND:
19361   case ISD::ZERO_EXTEND:
19362   case ISD::ANY_EXTEND:
19363   case ISD::SHL:
19364   case ISD::SRL:
19365   case ISD::SUB:
19366   case ISD::ADD:
19367   case ISD::MUL:
19368   case ISD::AND:
19369   case ISD::OR:
19370   case ISD::XOR:
19371     return false;
19372   }
19373 }
19374
19375 /// IsDesirableToPromoteOp - This method query the target whether it is
19376 /// beneficial for dag combiner to promote the specified node. If true, it
19377 /// should return the desired promotion type by reference.
19378 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19379   EVT VT = Op.getValueType();
19380   if (VT != MVT::i16)
19381     return false;
19382
19383   bool Promote = false;
19384   bool Commute = false;
19385   switch (Op.getOpcode()) {
19386   default: break;
19387   case ISD::LOAD: {
19388     LoadSDNode *LD = cast<LoadSDNode>(Op);
19389     // If the non-extending load has a single use and it's not live out, then it
19390     // might be folded.
19391     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19392                                                      Op.hasOneUse()*/) {
19393       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19394              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19395         // The only case where we'd want to promote LOAD (rather then it being
19396         // promoted as an operand is when it's only use is liveout.
19397         if (UI->getOpcode() != ISD::CopyToReg)
19398           return false;
19399       }
19400     }
19401     Promote = true;
19402     break;
19403   }
19404   case ISD::SIGN_EXTEND:
19405   case ISD::ZERO_EXTEND:
19406   case ISD::ANY_EXTEND:
19407     Promote = true;
19408     break;
19409   case ISD::SHL:
19410   case ISD::SRL: {
19411     SDValue N0 = Op.getOperand(0);
19412     // Look out for (store (shl (load), x)).
19413     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19414       return false;
19415     Promote = true;
19416     break;
19417   }
19418   case ISD::ADD:
19419   case ISD::MUL:
19420   case ISD::AND:
19421   case ISD::OR:
19422   case ISD::XOR:
19423     Commute = true;
19424     // fallthrough
19425   case ISD::SUB: {
19426     SDValue N0 = Op.getOperand(0);
19427     SDValue N1 = Op.getOperand(1);
19428     if (!Commute && MayFoldLoad(N1))
19429       return false;
19430     // Avoid disabling potential load folding opportunities.
19431     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19432       return false;
19433     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19434       return false;
19435     Promote = true;
19436   }
19437   }
19438
19439   PVT = MVT::i32;
19440   return Promote;
19441 }
19442
19443 //===----------------------------------------------------------------------===//
19444 //                           X86 Inline Assembly Support
19445 //===----------------------------------------------------------------------===//
19446
19447 namespace {
19448   // Helper to match a string separated by whitespace.
19449   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19450     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19451
19452     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19453       StringRef piece(*args[i]);
19454       if (!s.startswith(piece)) // Check if the piece matches.
19455         return false;
19456
19457       s = s.substr(piece.size());
19458       StringRef::size_type pos = s.find_first_not_of(" \t");
19459       if (pos == 0) // We matched a prefix.
19460         return false;
19461
19462       s = s.substr(pos);
19463     }
19464
19465     return s.empty();
19466   }
19467   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19468 }
19469
19470 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19471
19472   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19473     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19474         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19475         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19476
19477       if (AsmPieces.size() == 3)
19478         return true;
19479       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19480         return true;
19481     }
19482   }
19483   return false;
19484 }
19485
19486 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19487   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19488
19489   std::string AsmStr = IA->getAsmString();
19490
19491   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19492   if (!Ty || Ty->getBitWidth() % 16 != 0)
19493     return false;
19494
19495   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19496   SmallVector<StringRef, 4> AsmPieces;
19497   SplitString(AsmStr, AsmPieces, ";\n");
19498
19499   switch (AsmPieces.size()) {
19500   default: return false;
19501   case 1:
19502     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19503     // we will turn this bswap into something that will be lowered to logical
19504     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19505     // lower so don't worry about this.
19506     // bswap $0
19507     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19508         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19509         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19510         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19511         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19512         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19513       // No need to check constraints, nothing other than the equivalent of
19514       // "=r,0" would be valid here.
19515       return IntrinsicLowering::LowerToByteSwap(CI);
19516     }
19517
19518     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19519     if (CI->getType()->isIntegerTy(16) &&
19520         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19521         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19522          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19523       AsmPieces.clear();
19524       const std::string &ConstraintsStr = IA->getConstraintString();
19525       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19526       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19527       if (clobbersFlagRegisters(AsmPieces))
19528         return IntrinsicLowering::LowerToByteSwap(CI);
19529     }
19530     break;
19531   case 3:
19532     if (CI->getType()->isIntegerTy(32) &&
19533         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19534         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19535         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19536         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19537       AsmPieces.clear();
19538       const std::string &ConstraintsStr = IA->getConstraintString();
19539       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19540       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19541       if (clobbersFlagRegisters(AsmPieces))
19542         return IntrinsicLowering::LowerToByteSwap(CI);
19543     }
19544
19545     if (CI->getType()->isIntegerTy(64)) {
19546       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19547       if (Constraints.size() >= 2 &&
19548           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19549           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19550         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19551         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19552             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19553             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19554           return IntrinsicLowering::LowerToByteSwap(CI);
19555       }
19556     }
19557     break;
19558   }
19559   return false;
19560 }
19561
19562 /// getConstraintType - Given a constraint letter, return the type of
19563 /// constraint it is for this target.
19564 X86TargetLowering::ConstraintType
19565 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19566   if (Constraint.size() == 1) {
19567     switch (Constraint[0]) {
19568     case 'R':
19569     case 'q':
19570     case 'Q':
19571     case 'f':
19572     case 't':
19573     case 'u':
19574     case 'y':
19575     case 'x':
19576     case 'Y':
19577     case 'l':
19578       return C_RegisterClass;
19579     case 'a':
19580     case 'b':
19581     case 'c':
19582     case 'd':
19583     case 'S':
19584     case 'D':
19585     case 'A':
19586       return C_Register;
19587     case 'I':
19588     case 'J':
19589     case 'K':
19590     case 'L':
19591     case 'M':
19592     case 'N':
19593     case 'G':
19594     case 'C':
19595     case 'e':
19596     case 'Z':
19597       return C_Other;
19598     default:
19599       break;
19600     }
19601   }
19602   return TargetLowering::getConstraintType(Constraint);
19603 }
19604
19605 /// Examine constraint type and operand type and determine a weight value.
19606 /// This object must already have been set up with the operand type
19607 /// and the current alternative constraint selected.
19608 TargetLowering::ConstraintWeight
19609   X86TargetLowering::getSingleConstraintMatchWeight(
19610     AsmOperandInfo &info, const char *constraint) const {
19611   ConstraintWeight weight = CW_Invalid;
19612   Value *CallOperandVal = info.CallOperandVal;
19613     // If we don't have a value, we can't do a match,
19614     // but allow it at the lowest weight.
19615   if (CallOperandVal == NULL)
19616     return CW_Default;
19617   Type *type = CallOperandVal->getType();
19618   // Look at the constraint type.
19619   switch (*constraint) {
19620   default:
19621     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19622   case 'R':
19623   case 'q':
19624   case 'Q':
19625   case 'a':
19626   case 'b':
19627   case 'c':
19628   case 'd':
19629   case 'S':
19630   case 'D':
19631   case 'A':
19632     if (CallOperandVal->getType()->isIntegerTy())
19633       weight = CW_SpecificReg;
19634     break;
19635   case 'f':
19636   case 't':
19637   case 'u':
19638     if (type->isFloatingPointTy())
19639       weight = CW_SpecificReg;
19640     break;
19641   case 'y':
19642     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19643       weight = CW_SpecificReg;
19644     break;
19645   case 'x':
19646   case 'Y':
19647     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19648         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19649       weight = CW_Register;
19650     break;
19651   case 'I':
19652     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19653       if (C->getZExtValue() <= 31)
19654         weight = CW_Constant;
19655     }
19656     break;
19657   case 'J':
19658     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19659       if (C->getZExtValue() <= 63)
19660         weight = CW_Constant;
19661     }
19662     break;
19663   case 'K':
19664     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19665       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19666         weight = CW_Constant;
19667     }
19668     break;
19669   case 'L':
19670     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19671       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19672         weight = CW_Constant;
19673     }
19674     break;
19675   case 'M':
19676     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19677       if (C->getZExtValue() <= 3)
19678         weight = CW_Constant;
19679     }
19680     break;
19681   case 'N':
19682     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19683       if (C->getZExtValue() <= 0xff)
19684         weight = CW_Constant;
19685     }
19686     break;
19687   case 'G':
19688   case 'C':
19689     if (dyn_cast<ConstantFP>(CallOperandVal)) {
19690       weight = CW_Constant;
19691     }
19692     break;
19693   case 'e':
19694     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19695       if ((C->getSExtValue() >= -0x80000000LL) &&
19696           (C->getSExtValue() <= 0x7fffffffLL))
19697         weight = CW_Constant;
19698     }
19699     break;
19700   case 'Z':
19701     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19702       if (C->getZExtValue() <= 0xffffffff)
19703         weight = CW_Constant;
19704     }
19705     break;
19706   }
19707   return weight;
19708 }
19709
19710 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19711 /// with another that has more specific requirements based on the type of the
19712 /// corresponding operand.
19713 const char *X86TargetLowering::
19714 LowerXConstraint(EVT ConstraintVT) const {
19715   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19716   // 'f' like normal targets.
19717   if (ConstraintVT.isFloatingPoint()) {
19718     if (Subtarget->hasSSE2())
19719       return "Y";
19720     if (Subtarget->hasSSE1())
19721       return "x";
19722   }
19723
19724   return TargetLowering::LowerXConstraint(ConstraintVT);
19725 }
19726
19727 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19728 /// vector.  If it is invalid, don't add anything to Ops.
19729 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19730                                                      std::string &Constraint,
19731                                                      std::vector<SDValue>&Ops,
19732                                                      SelectionDAG &DAG) const {
19733   SDValue Result(0, 0);
19734
19735   // Only support length 1 constraints for now.
19736   if (Constraint.length() > 1) return;
19737
19738   char ConstraintLetter = Constraint[0];
19739   switch (ConstraintLetter) {
19740   default: break;
19741   case 'I':
19742     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19743       if (C->getZExtValue() <= 31) {
19744         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19745         break;
19746       }
19747     }
19748     return;
19749   case 'J':
19750     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19751       if (C->getZExtValue() <= 63) {
19752         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19753         break;
19754       }
19755     }
19756     return;
19757   case 'K':
19758     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19759       if (isInt<8>(C->getSExtValue())) {
19760         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19761         break;
19762       }
19763     }
19764     return;
19765   case 'N':
19766     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19767       if (C->getZExtValue() <= 255) {
19768         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19769         break;
19770       }
19771     }
19772     return;
19773   case 'e': {
19774     // 32-bit signed value
19775     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19776       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19777                                            C->getSExtValue())) {
19778         // Widen to 64 bits here to get it sign extended.
19779         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
19780         break;
19781       }
19782     // FIXME gcc accepts some relocatable values here too, but only in certain
19783     // memory models; it's complicated.
19784     }
19785     return;
19786   }
19787   case 'Z': {
19788     // 32-bit unsigned value
19789     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19790       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19791                                            C->getZExtValue())) {
19792         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19793         break;
19794       }
19795     }
19796     // FIXME gcc accepts some relocatable values here too, but only in certain
19797     // memory models; it's complicated.
19798     return;
19799   }
19800   case 'i': {
19801     // Literal immediates are always ok.
19802     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19803       // Widen to 64 bits here to get it sign extended.
19804       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19805       break;
19806     }
19807
19808     // In any sort of PIC mode addresses need to be computed at runtime by
19809     // adding in a register or some sort of table lookup.  These can't
19810     // be used as immediates.
19811     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19812       return;
19813
19814     // If we are in non-pic codegen mode, we allow the address of a global (with
19815     // an optional displacement) to be used with 'i'.
19816     GlobalAddressSDNode *GA = 0;
19817     int64_t Offset = 0;
19818
19819     // Match either (GA), (GA+C), (GA+C1+C2), etc.
19820     while (1) {
19821       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19822         Offset += GA->getOffset();
19823         break;
19824       } else if (Op.getOpcode() == ISD::ADD) {
19825         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19826           Offset += C->getZExtValue();
19827           Op = Op.getOperand(0);
19828           continue;
19829         }
19830       } else if (Op.getOpcode() == ISD::SUB) {
19831         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19832           Offset += -C->getZExtValue();
19833           Op = Op.getOperand(0);
19834           continue;
19835         }
19836       }
19837
19838       // Otherwise, this isn't something we can handle, reject it.
19839       return;
19840     }
19841
19842     const GlobalValue *GV = GA->getGlobal();
19843     // If we require an extra load to get this address, as in PIC mode, we
19844     // can't accept it.
19845     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19846                                                         getTargetMachine())))
19847       return;
19848
19849     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19850                                         GA->getValueType(0), Offset);
19851     break;
19852   }
19853   }
19854
19855   if (Result.getNode()) {
19856     Ops.push_back(Result);
19857     return;
19858   }
19859   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19860 }
19861
19862 std::pair<unsigned, const TargetRegisterClass*>
19863 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19864                                                 MVT VT) const {
19865   // First, see if this is a constraint that directly corresponds to an LLVM
19866   // register class.
19867   if (Constraint.size() == 1) {
19868     // GCC Constraint Letters
19869     switch (Constraint[0]) {
19870     default: break;
19871       // TODO: Slight differences here in allocation order and leaving
19872       // RIP in the class. Do they matter any more here than they do
19873       // in the normal allocation?
19874     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19875       if (Subtarget->is64Bit()) {
19876         if (VT == MVT::i32 || VT == MVT::f32)
19877           return std::make_pair(0U, &X86::GR32RegClass);
19878         if (VT == MVT::i16)
19879           return std::make_pair(0U, &X86::GR16RegClass);
19880         if (VT == MVT::i8 || VT == MVT::i1)
19881           return std::make_pair(0U, &X86::GR8RegClass);
19882         if (VT == MVT::i64 || VT == MVT::f64)
19883           return std::make_pair(0U, &X86::GR64RegClass);
19884         break;
19885       }
19886       // 32-bit fallthrough
19887     case 'Q':   // Q_REGS
19888       if (VT == MVT::i32 || VT == MVT::f32)
19889         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19890       if (VT == MVT::i16)
19891         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19892       if (VT == MVT::i8 || VT == MVT::i1)
19893         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19894       if (VT == MVT::i64)
19895         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19896       break;
19897     case 'r':   // GENERAL_REGS
19898     case 'l':   // INDEX_REGS
19899       if (VT == MVT::i8 || VT == MVT::i1)
19900         return std::make_pair(0U, &X86::GR8RegClass);
19901       if (VT == MVT::i16)
19902         return std::make_pair(0U, &X86::GR16RegClass);
19903       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19904         return std::make_pair(0U, &X86::GR32RegClass);
19905       return std::make_pair(0U, &X86::GR64RegClass);
19906     case 'R':   // LEGACY_REGS
19907       if (VT == MVT::i8 || VT == MVT::i1)
19908         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19909       if (VT == MVT::i16)
19910         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19911       if (VT == MVT::i32 || !Subtarget->is64Bit())
19912         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19913       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19914     case 'f':  // FP Stack registers.
19915       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19916       // value to the correct fpstack register class.
19917       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19918         return std::make_pair(0U, &X86::RFP32RegClass);
19919       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19920         return std::make_pair(0U, &X86::RFP64RegClass);
19921       return std::make_pair(0U, &X86::RFP80RegClass);
19922     case 'y':   // MMX_REGS if MMX allowed.
19923       if (!Subtarget->hasMMX()) break;
19924       return std::make_pair(0U, &X86::VR64RegClass);
19925     case 'Y':   // SSE_REGS if SSE2 allowed
19926       if (!Subtarget->hasSSE2()) break;
19927       // FALL THROUGH.
19928     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19929       if (!Subtarget->hasSSE1()) break;
19930
19931       switch (VT.SimpleTy) {
19932       default: break;
19933       // Scalar SSE types.
19934       case MVT::f32:
19935       case MVT::i32:
19936         return std::make_pair(0U, &X86::FR32RegClass);
19937       case MVT::f64:
19938       case MVT::i64:
19939         return std::make_pair(0U, &X86::FR64RegClass);
19940       // Vector types.
19941       case MVT::v16i8:
19942       case MVT::v8i16:
19943       case MVT::v4i32:
19944       case MVT::v2i64:
19945       case MVT::v4f32:
19946       case MVT::v2f64:
19947         return std::make_pair(0U, &X86::VR128RegClass);
19948       // AVX types.
19949       case MVT::v32i8:
19950       case MVT::v16i16:
19951       case MVT::v8i32:
19952       case MVT::v4i64:
19953       case MVT::v8f32:
19954       case MVT::v4f64:
19955         return std::make_pair(0U, &X86::VR256RegClass);
19956       case MVT::v8f64:
19957       case MVT::v16f32:
19958       case MVT::v16i32:
19959       case MVT::v8i64:
19960         return std::make_pair(0U, &X86::VR512RegClass);
19961       }
19962       break;
19963     }
19964   }
19965
19966   // Use the default implementation in TargetLowering to convert the register
19967   // constraint into a member of a register class.
19968   std::pair<unsigned, const TargetRegisterClass*> Res;
19969   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19970
19971   // Not found as a standard register?
19972   if (Res.second == 0) {
19973     // Map st(0) -> st(7) -> ST0
19974     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19975         tolower(Constraint[1]) == 's' &&
19976         tolower(Constraint[2]) == 't' &&
19977         Constraint[3] == '(' &&
19978         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19979         Constraint[5] == ')' &&
19980         Constraint[6] == '}') {
19981
19982       Res.first = X86::ST0+Constraint[4]-'0';
19983       Res.second = &X86::RFP80RegClass;
19984       return Res;
19985     }
19986
19987     // GCC allows "st(0)" to be called just plain "st".
19988     if (StringRef("{st}").equals_lower(Constraint)) {
19989       Res.first = X86::ST0;
19990       Res.second = &X86::RFP80RegClass;
19991       return Res;
19992     }
19993
19994     // flags -> EFLAGS
19995     if (StringRef("{flags}").equals_lower(Constraint)) {
19996       Res.first = X86::EFLAGS;
19997       Res.second = &X86::CCRRegClass;
19998       return Res;
19999     }
20000
20001     // 'A' means EAX + EDX.
20002     if (Constraint == "A") {
20003       Res.first = X86::EAX;
20004       Res.second = &X86::GR32_ADRegClass;
20005       return Res;
20006     }
20007     return Res;
20008   }
20009
20010   // Otherwise, check to see if this is a register class of the wrong value
20011   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20012   // turn into {ax},{dx}.
20013   if (Res.second->hasType(VT))
20014     return Res;   // Correct type already, nothing to do.
20015
20016   // All of the single-register GCC register classes map their values onto
20017   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20018   // really want an 8-bit or 32-bit register, map to the appropriate register
20019   // class and return the appropriate register.
20020   if (Res.second == &X86::GR16RegClass) {
20021     if (VT == MVT::i8 || VT == MVT::i1) {
20022       unsigned DestReg = 0;
20023       switch (Res.first) {
20024       default: break;
20025       case X86::AX: DestReg = X86::AL; break;
20026       case X86::DX: DestReg = X86::DL; break;
20027       case X86::CX: DestReg = X86::CL; break;
20028       case X86::BX: DestReg = X86::BL; break;
20029       }
20030       if (DestReg) {
20031         Res.first = DestReg;
20032         Res.second = &X86::GR8RegClass;
20033       }
20034     } else if (VT == MVT::i32 || VT == MVT::f32) {
20035       unsigned DestReg = 0;
20036       switch (Res.first) {
20037       default: break;
20038       case X86::AX: DestReg = X86::EAX; break;
20039       case X86::DX: DestReg = X86::EDX; break;
20040       case X86::CX: DestReg = X86::ECX; break;
20041       case X86::BX: DestReg = X86::EBX; break;
20042       case X86::SI: DestReg = X86::ESI; break;
20043       case X86::DI: DestReg = X86::EDI; break;
20044       case X86::BP: DestReg = X86::EBP; break;
20045       case X86::SP: DestReg = X86::ESP; break;
20046       }
20047       if (DestReg) {
20048         Res.first = DestReg;
20049         Res.second = &X86::GR32RegClass;
20050       }
20051     } else if (VT == MVT::i64 || VT == MVT::f64) {
20052       unsigned DestReg = 0;
20053       switch (Res.first) {
20054       default: break;
20055       case X86::AX: DestReg = X86::RAX; break;
20056       case X86::DX: DestReg = X86::RDX; break;
20057       case X86::CX: DestReg = X86::RCX; break;
20058       case X86::BX: DestReg = X86::RBX; break;
20059       case X86::SI: DestReg = X86::RSI; break;
20060       case X86::DI: DestReg = X86::RDI; break;
20061       case X86::BP: DestReg = X86::RBP; break;
20062       case X86::SP: DestReg = X86::RSP; break;
20063       }
20064       if (DestReg) {
20065         Res.first = DestReg;
20066         Res.second = &X86::GR64RegClass;
20067       }
20068     }
20069   } else if (Res.second == &X86::FR32RegClass ||
20070              Res.second == &X86::FR64RegClass ||
20071              Res.second == &X86::VR128RegClass ||
20072              Res.second == &X86::VR256RegClass ||
20073              Res.second == &X86::FR32XRegClass ||
20074              Res.second == &X86::FR64XRegClass ||
20075              Res.second == &X86::VR128XRegClass ||
20076              Res.second == &X86::VR256XRegClass ||
20077              Res.second == &X86::VR512RegClass) {
20078     // Handle references to XMM physical registers that got mapped into the
20079     // wrong class.  This can happen with constraints like {xmm0} where the
20080     // target independent register mapper will just pick the first match it can
20081     // find, ignoring the required type.
20082
20083     if (VT == MVT::f32 || VT == MVT::i32)
20084       Res.second = &X86::FR32RegClass;
20085     else if (VT == MVT::f64 || VT == MVT::i64)
20086       Res.second = &X86::FR64RegClass;
20087     else if (X86::VR128RegClass.hasType(VT))
20088       Res.second = &X86::VR128RegClass;
20089     else if (X86::VR256RegClass.hasType(VT))
20090       Res.second = &X86::VR256RegClass;
20091     else if (X86::VR512RegClass.hasType(VT))
20092       Res.second = &X86::VR512RegClass;
20093   }
20094
20095   return Res;
20096 }