85999a21818872b04840bedb13de68d98b149cc6
[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)
10239         return Op0;
10240
10241       CCode = X86::GetOppositeBranchCondition(CCode);
10242       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10243                                   DAG.getConstant(CCode, MVT::i8),
10244                                   Op0.getOperand(1));
10245       if (VT == MVT::i1)
10246         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10247       return SetCC;
10248     }
10249   }
10250
10251   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10252   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10253   if (X86CC == X86::COND_INVALID)
10254     return SDValue();
10255
10256   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
10257   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10258   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10259                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10260   if (VT == MVT::i1)
10261     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10262   return SetCC;
10263 }
10264
10265 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10266 static bool isX86LogicalCmp(SDValue Op) {
10267   unsigned Opc = Op.getNode()->getOpcode();
10268   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10269       Opc == X86ISD::SAHF)
10270     return true;
10271   if (Op.getResNo() == 1 &&
10272       (Opc == X86ISD::ADD ||
10273        Opc == X86ISD::SUB ||
10274        Opc == X86ISD::ADC ||
10275        Opc == X86ISD::SBB ||
10276        Opc == X86ISD::SMUL ||
10277        Opc == X86ISD::UMUL ||
10278        Opc == X86ISD::INC ||
10279        Opc == X86ISD::DEC ||
10280        Opc == X86ISD::OR ||
10281        Opc == X86ISD::XOR ||
10282        Opc == X86ISD::AND))
10283     return true;
10284
10285   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10286     return true;
10287
10288   return false;
10289 }
10290
10291 static bool isZero(SDValue V) {
10292   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10293   return C && C->isNullValue();
10294 }
10295
10296 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10297   if (V.getOpcode() != ISD::TRUNCATE)
10298     return false;
10299
10300   SDValue VOp0 = V.getOperand(0);
10301   unsigned InBits = VOp0.getValueSizeInBits();
10302   unsigned Bits = V.getValueSizeInBits();
10303   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10304 }
10305
10306 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10307   bool addTest = true;
10308   SDValue Cond  = Op.getOperand(0);
10309   SDValue Op1 = Op.getOperand(1);
10310   SDValue Op2 = Op.getOperand(2);
10311   SDLoc DL(Op);
10312   EVT VT = Op1.getValueType();
10313   SDValue CC;
10314
10315   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10316   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10317   // sequence later on.
10318   if (Cond.getOpcode() == ISD::SETCC &&
10319       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10320        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10321       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10322     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10323     int SSECC = translateX86FSETCC(
10324         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10325
10326     if (SSECC != 8) {
10327       if (Subtarget->hasAVX512()) {
10328         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10329                                   DAG.getConstant(SSECC, MVT::i8));
10330         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10331       }
10332       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10333                                 DAG.getConstant(SSECC, MVT::i8));
10334       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10335       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10336       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10337     }
10338   }
10339
10340   if (Cond.getOpcode() == ISD::SETCC) {
10341     SDValue NewCond = LowerSETCC(Cond, DAG);
10342     if (NewCond.getNode())
10343       Cond = NewCond;
10344   }
10345
10346   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10347   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10348   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10349   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10350   if (Cond.getOpcode() == X86ISD::SETCC &&
10351       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10352       isZero(Cond.getOperand(1).getOperand(1))) {
10353     SDValue Cmp = Cond.getOperand(1);
10354
10355     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10356
10357     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10358         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10359       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10360
10361       SDValue CmpOp0 = Cmp.getOperand(0);
10362       // Apply further optimizations for special cases
10363       // (select (x != 0), -1, 0) -> neg & sbb
10364       // (select (x == 0), 0, -1) -> neg & sbb
10365       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10366         if (YC->isNullValue() &&
10367             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10368           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10369           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10370                                     DAG.getConstant(0, CmpOp0.getValueType()),
10371                                     CmpOp0);
10372           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10373                                     DAG.getConstant(X86::COND_B, MVT::i8),
10374                                     SDValue(Neg.getNode(), 1));
10375           return Res;
10376         }
10377
10378       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10379                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10380       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10381
10382       SDValue Res =   // Res = 0 or -1.
10383         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10384                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10385
10386       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10387         Res = DAG.getNOT(DL, Res, Res.getValueType());
10388
10389       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10390       if (N2C == 0 || !N2C->isNullValue())
10391         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10392       return Res;
10393     }
10394   }
10395
10396   // Look past (and (setcc_carry (cmp ...)), 1).
10397   if (Cond.getOpcode() == ISD::AND &&
10398       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10399     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10400     if (C && C->getAPIntValue() == 1)
10401       Cond = Cond.getOperand(0);
10402   }
10403
10404   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10405   // setting operand in place of the X86ISD::SETCC.
10406   unsigned CondOpcode = Cond.getOpcode();
10407   if (CondOpcode == X86ISD::SETCC ||
10408       CondOpcode == X86ISD::SETCC_CARRY) {
10409     CC = Cond.getOperand(0);
10410
10411     SDValue Cmp = Cond.getOperand(1);
10412     unsigned Opc = Cmp.getOpcode();
10413     MVT VT = Op.getSimpleValueType();
10414
10415     bool IllegalFPCMov = false;
10416     if (VT.isFloatingPoint() && !VT.isVector() &&
10417         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10418       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10419
10420     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10421         Opc == X86ISD::BT) { // FIXME
10422       Cond = Cmp;
10423       addTest = false;
10424     }
10425   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10426              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10427              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10428               Cond.getOperand(0).getValueType() != MVT::i8)) {
10429     SDValue LHS = Cond.getOperand(0);
10430     SDValue RHS = Cond.getOperand(1);
10431     unsigned X86Opcode;
10432     unsigned X86Cond;
10433     SDVTList VTs;
10434     switch (CondOpcode) {
10435     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10436     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10437     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10438     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10439     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10440     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10441     default: llvm_unreachable("unexpected overflowing operator");
10442     }
10443     if (CondOpcode == ISD::UMULO)
10444       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10445                           MVT::i32);
10446     else
10447       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10448
10449     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10450
10451     if (CondOpcode == ISD::UMULO)
10452       Cond = X86Op.getValue(2);
10453     else
10454       Cond = X86Op.getValue(1);
10455
10456     CC = DAG.getConstant(X86Cond, MVT::i8);
10457     addTest = false;
10458   }
10459
10460   if (addTest) {
10461     // Look pass the truncate if the high bits are known zero.
10462     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10463         Cond = Cond.getOperand(0);
10464
10465     // We know the result of AND is compared against zero. Try to match
10466     // it to BT.
10467     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10468       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10469       if (NewSetCC.getNode()) {
10470         CC = NewSetCC.getOperand(0);
10471         Cond = NewSetCC.getOperand(1);
10472         addTest = false;
10473       }
10474     }
10475   }
10476
10477   if (addTest) {
10478     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10479     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10480   }
10481
10482   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10483   // a <  b ?  0 : -1 -> RES = setcc_carry
10484   // a >= b ? -1 :  0 -> RES = setcc_carry
10485   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10486   if (Cond.getOpcode() == X86ISD::SUB) {
10487     Cond = ConvertCmpIfNecessary(Cond, DAG);
10488     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10489
10490     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10491         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10492       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10493                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10494       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10495         return DAG.getNOT(DL, Res, Res.getValueType());
10496       return Res;
10497     }
10498   }
10499
10500   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10501   // widen the cmov and push the truncate through. This avoids introducing a new
10502   // branch during isel and doesn't add any extensions.
10503   if (Op.getValueType() == MVT::i8 &&
10504       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10505     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10506     if (T1.getValueType() == T2.getValueType() &&
10507         // Blacklist CopyFromReg to avoid partial register stalls.
10508         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10509       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10510       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10511       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10512     }
10513   }
10514
10515   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10516   // condition is true.
10517   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10518   SDValue Ops[] = { Op2, Op1, CC, Cond };
10519   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10520 }
10521
10522 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10523   MVT VT = Op->getSimpleValueType(0);
10524   SDValue In = Op->getOperand(0);
10525   MVT InVT = In.getSimpleValueType();
10526   SDLoc dl(Op);
10527
10528   unsigned int NumElts = VT.getVectorNumElements();
10529   if (NumElts != 8 && NumElts != 16)
10530     return SDValue();
10531
10532   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10533     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10534
10535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10536   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10537
10538   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10539   Constant *C = ConstantInt::get(*DAG.getContext(),
10540     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10541
10542   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10543   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10544   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10545                           MachinePointerInfo::getConstantPool(),
10546                           false, false, false, Alignment);
10547   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10548   if (VT.is512BitVector())
10549     return Brcst;
10550   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10551 }
10552
10553 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10554                                 SelectionDAG &DAG) {
10555   MVT VT = Op->getSimpleValueType(0);
10556   SDValue In = Op->getOperand(0);
10557   MVT InVT = In.getSimpleValueType();
10558   SDLoc dl(Op);
10559
10560   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10561     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10562
10563   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10564       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10565       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10566     return SDValue();
10567
10568   if (Subtarget->hasInt256())
10569     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10570
10571   // Optimize vectors in AVX mode
10572   // Sign extend  v8i16 to v8i32 and
10573   //              v4i32 to v4i64
10574   //
10575   // Divide input vector into two parts
10576   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10577   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10578   // concat the vectors to original VT
10579
10580   unsigned NumElems = InVT.getVectorNumElements();
10581   SDValue Undef = DAG.getUNDEF(InVT);
10582
10583   SmallVector<int,8> ShufMask1(NumElems, -1);
10584   for (unsigned i = 0; i != NumElems/2; ++i)
10585     ShufMask1[i] = i;
10586
10587   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10588
10589   SmallVector<int,8> ShufMask2(NumElems, -1);
10590   for (unsigned i = 0; i != NumElems/2; ++i)
10591     ShufMask2[i] = i + NumElems/2;
10592
10593   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10594
10595   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10596                                 VT.getVectorNumElements()/2);
10597
10598   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10599   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10600
10601   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10602 }
10603
10604 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10605 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10606 // from the AND / OR.
10607 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10608   Opc = Op.getOpcode();
10609   if (Opc != ISD::OR && Opc != ISD::AND)
10610     return false;
10611   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10612           Op.getOperand(0).hasOneUse() &&
10613           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10614           Op.getOperand(1).hasOneUse());
10615 }
10616
10617 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10618 // 1 and that the SETCC node has a single use.
10619 static bool isXor1OfSetCC(SDValue Op) {
10620   if (Op.getOpcode() != ISD::XOR)
10621     return false;
10622   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10623   if (N1C && N1C->getAPIntValue() == 1) {
10624     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10625       Op.getOperand(0).hasOneUse();
10626   }
10627   return false;
10628 }
10629
10630 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10631   bool addTest = true;
10632   SDValue Chain = Op.getOperand(0);
10633   SDValue Cond  = Op.getOperand(1);
10634   SDValue Dest  = Op.getOperand(2);
10635   SDLoc dl(Op);
10636   SDValue CC;
10637   bool Inverted = false;
10638
10639   if (Cond.getOpcode() == ISD::SETCC) {
10640     // Check for setcc([su]{add,sub,mul}o == 0).
10641     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10642         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10643         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10644         Cond.getOperand(0).getResNo() == 1 &&
10645         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10646          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10647          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10648          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10649          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10650          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10651       Inverted = true;
10652       Cond = Cond.getOperand(0);
10653     } else {
10654       SDValue NewCond = LowerSETCC(Cond, DAG);
10655       if (NewCond.getNode())
10656         Cond = NewCond;
10657     }
10658   }
10659 #if 0
10660   // FIXME: LowerXALUO doesn't handle these!!
10661   else if (Cond.getOpcode() == X86ISD::ADD  ||
10662            Cond.getOpcode() == X86ISD::SUB  ||
10663            Cond.getOpcode() == X86ISD::SMUL ||
10664            Cond.getOpcode() == X86ISD::UMUL)
10665     Cond = LowerXALUO(Cond, DAG);
10666 #endif
10667
10668   // Look pass (and (setcc_carry (cmp ...)), 1).
10669   if (Cond.getOpcode() == ISD::AND &&
10670       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10671     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10672     if (C && C->getAPIntValue() == 1)
10673       Cond = Cond.getOperand(0);
10674   }
10675
10676   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10677   // setting operand in place of the X86ISD::SETCC.
10678   unsigned CondOpcode = Cond.getOpcode();
10679   if (CondOpcode == X86ISD::SETCC ||
10680       CondOpcode == X86ISD::SETCC_CARRY) {
10681     CC = Cond.getOperand(0);
10682
10683     SDValue Cmp = Cond.getOperand(1);
10684     unsigned Opc = Cmp.getOpcode();
10685     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10686     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10687       Cond = Cmp;
10688       addTest = false;
10689     } else {
10690       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10691       default: break;
10692       case X86::COND_O:
10693       case X86::COND_B:
10694         // These can only come from an arithmetic instruction with overflow,
10695         // e.g. SADDO, UADDO.
10696         Cond = Cond.getNode()->getOperand(1);
10697         addTest = false;
10698         break;
10699       }
10700     }
10701   }
10702   CondOpcode = Cond.getOpcode();
10703   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10704       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10705       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10706        Cond.getOperand(0).getValueType() != MVT::i8)) {
10707     SDValue LHS = Cond.getOperand(0);
10708     SDValue RHS = Cond.getOperand(1);
10709     unsigned X86Opcode;
10710     unsigned X86Cond;
10711     SDVTList VTs;
10712     switch (CondOpcode) {
10713     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10714     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10715     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10716     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10717     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10718     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10719     default: llvm_unreachable("unexpected overflowing operator");
10720     }
10721     if (Inverted)
10722       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10723     if (CondOpcode == ISD::UMULO)
10724       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10725                           MVT::i32);
10726     else
10727       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10728
10729     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10730
10731     if (CondOpcode == ISD::UMULO)
10732       Cond = X86Op.getValue(2);
10733     else
10734       Cond = X86Op.getValue(1);
10735
10736     CC = DAG.getConstant(X86Cond, MVT::i8);
10737     addTest = false;
10738   } else {
10739     unsigned CondOpc;
10740     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10741       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10742       if (CondOpc == ISD::OR) {
10743         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10744         // two branches instead of an explicit OR instruction with a
10745         // separate test.
10746         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10747             isX86LogicalCmp(Cmp)) {
10748           CC = Cond.getOperand(0).getOperand(0);
10749           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10750                               Chain, Dest, CC, Cmp);
10751           CC = Cond.getOperand(1).getOperand(0);
10752           Cond = Cmp;
10753           addTest = false;
10754         }
10755       } else { // ISD::AND
10756         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10757         // two branches instead of an explicit AND instruction with a
10758         // separate test. However, we only do this if this block doesn't
10759         // have a fall-through edge, because this requires an explicit
10760         // jmp when the condition is false.
10761         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10762             isX86LogicalCmp(Cmp) &&
10763             Op.getNode()->hasOneUse()) {
10764           X86::CondCode CCode =
10765             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10766           CCode = X86::GetOppositeBranchCondition(CCode);
10767           CC = DAG.getConstant(CCode, MVT::i8);
10768           SDNode *User = *Op.getNode()->use_begin();
10769           // Look for an unconditional branch following this conditional branch.
10770           // We need this because we need to reverse the successors in order
10771           // to implement FCMP_OEQ.
10772           if (User->getOpcode() == ISD::BR) {
10773             SDValue FalseBB = User->getOperand(1);
10774             SDNode *NewBR =
10775               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10776             assert(NewBR == User);
10777             (void)NewBR;
10778             Dest = FalseBB;
10779
10780             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10781                                 Chain, Dest, CC, Cmp);
10782             X86::CondCode CCode =
10783               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10784             CCode = X86::GetOppositeBranchCondition(CCode);
10785             CC = DAG.getConstant(CCode, MVT::i8);
10786             Cond = Cmp;
10787             addTest = false;
10788           }
10789         }
10790       }
10791     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10792       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10793       // It should be transformed during dag combiner except when the condition
10794       // is set by a arithmetics with overflow node.
10795       X86::CondCode CCode =
10796         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10797       CCode = X86::GetOppositeBranchCondition(CCode);
10798       CC = DAG.getConstant(CCode, MVT::i8);
10799       Cond = Cond.getOperand(0).getOperand(1);
10800       addTest = false;
10801     } else if (Cond.getOpcode() == ISD::SETCC &&
10802                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10803       // For FCMP_OEQ, we can emit
10804       // two branches instead of an explicit AND instruction with a
10805       // separate test. However, we only do this if this block doesn't
10806       // have a fall-through edge, because this requires an explicit
10807       // jmp when the condition is false.
10808       if (Op.getNode()->hasOneUse()) {
10809         SDNode *User = *Op.getNode()->use_begin();
10810         // Look for an unconditional branch following this conditional branch.
10811         // We need this because we need to reverse the successors in order
10812         // to implement FCMP_OEQ.
10813         if (User->getOpcode() == ISD::BR) {
10814           SDValue FalseBB = User->getOperand(1);
10815           SDNode *NewBR =
10816             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10817           assert(NewBR == User);
10818           (void)NewBR;
10819           Dest = FalseBB;
10820
10821           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10822                                     Cond.getOperand(0), Cond.getOperand(1));
10823           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10824           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10825           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10826                               Chain, Dest, CC, Cmp);
10827           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10828           Cond = Cmp;
10829           addTest = false;
10830         }
10831       }
10832     } else if (Cond.getOpcode() == ISD::SETCC &&
10833                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10834       // For FCMP_UNE, we can emit
10835       // two branches instead of an explicit AND instruction with a
10836       // separate test. However, we only do this if this block doesn't
10837       // have a fall-through edge, because this requires an explicit
10838       // jmp when the condition is false.
10839       if (Op.getNode()->hasOneUse()) {
10840         SDNode *User = *Op.getNode()->use_begin();
10841         // Look for an unconditional branch following this conditional branch.
10842         // We need this because we need to reverse the successors in order
10843         // to implement FCMP_UNE.
10844         if (User->getOpcode() == ISD::BR) {
10845           SDValue FalseBB = User->getOperand(1);
10846           SDNode *NewBR =
10847             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10848           assert(NewBR == User);
10849           (void)NewBR;
10850
10851           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10852                                     Cond.getOperand(0), Cond.getOperand(1));
10853           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10854           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10855           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10856                               Chain, Dest, CC, Cmp);
10857           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10858           Cond = Cmp;
10859           addTest = false;
10860           Dest = FalseBB;
10861         }
10862       }
10863     }
10864   }
10865
10866   if (addTest) {
10867     // Look pass the truncate if the high bits are known zero.
10868     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10869         Cond = Cond.getOperand(0);
10870
10871     // We know the result of AND is compared against zero. Try to match
10872     // it to BT.
10873     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10874       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10875       if (NewSetCC.getNode()) {
10876         CC = NewSetCC.getOperand(0);
10877         Cond = NewSetCC.getOperand(1);
10878         addTest = false;
10879       }
10880     }
10881   }
10882
10883   if (addTest) {
10884     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10885     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10886   }
10887   Cond = ConvertCmpIfNecessary(Cond, DAG);
10888   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10889                      Chain, Dest, CC, Cond);
10890 }
10891
10892 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10893 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10894 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10895 // that the guard pages used by the OS virtual memory manager are allocated in
10896 // correct sequence.
10897 SDValue
10898 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10899                                            SelectionDAG &DAG) const {
10900   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10901           getTargetMachine().Options.EnableSegmentedStacks) &&
10902          "This should be used only on Windows targets or when segmented stacks "
10903          "are being used");
10904   assert(!Subtarget->isTargetMacho() && "Not implemented");
10905   SDLoc dl(Op);
10906
10907   // Get the inputs.
10908   SDValue Chain = Op.getOperand(0);
10909   SDValue Size  = Op.getOperand(1);
10910   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10911   EVT VT = Op.getNode()->getValueType(0);
10912
10913   bool Is64Bit = Subtarget->is64Bit();
10914   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10915
10916   if (getTargetMachine().Options.EnableSegmentedStacks) {
10917     MachineFunction &MF = DAG.getMachineFunction();
10918     MachineRegisterInfo &MRI = MF.getRegInfo();
10919
10920     if (Is64Bit) {
10921       // The 64 bit implementation of segmented stacks needs to clobber both r10
10922       // r11. This makes it impossible to use it along with nested parameters.
10923       const Function *F = MF.getFunction();
10924
10925       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10926            I != E; ++I)
10927         if (I->hasNestAttr())
10928           report_fatal_error("Cannot use segmented stacks with functions that "
10929                              "have nested arguments.");
10930     }
10931
10932     const TargetRegisterClass *AddrRegClass =
10933       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10934     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10935     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10936     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10937                                 DAG.getRegister(Vreg, SPTy));
10938     SDValue Ops1[2] = { Value, Chain };
10939     return DAG.getMergeValues(Ops1, 2, dl);
10940   } else {
10941     SDValue Flag;
10942     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10943
10944     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10945     Flag = Chain.getValue(1);
10946     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10947
10948     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10949
10950     const X86RegisterInfo *RegInfo =
10951       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10952     unsigned SPReg = RegInfo->getStackRegister();
10953     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
10954     Chain = SP.getValue(1);
10955
10956     if (Align) {
10957       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10958                        DAG.getConstant(-(uint64_t)Align, VT));
10959       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
10960     }
10961
10962     SDValue Ops1[2] = { SP, Chain };
10963     return DAG.getMergeValues(Ops1, 2, dl);
10964   }
10965 }
10966
10967 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10968   MachineFunction &MF = DAG.getMachineFunction();
10969   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10970
10971   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10972   SDLoc DL(Op);
10973
10974   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10975     // vastart just stores the address of the VarArgsFrameIndex slot into the
10976     // memory location argument.
10977     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10978                                    getPointerTy());
10979     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10980                         MachinePointerInfo(SV), false, false, 0);
10981   }
10982
10983   // __va_list_tag:
10984   //   gp_offset         (0 - 6 * 8)
10985   //   fp_offset         (48 - 48 + 8 * 16)
10986   //   overflow_arg_area (point to parameters coming in memory).
10987   //   reg_save_area
10988   SmallVector<SDValue, 8> MemOps;
10989   SDValue FIN = Op.getOperand(1);
10990   // Store gp_offset
10991   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10992                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10993                                                MVT::i32),
10994                                FIN, MachinePointerInfo(SV), false, false, 0);
10995   MemOps.push_back(Store);
10996
10997   // Store fp_offset
10998   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10999                     FIN, DAG.getIntPtrConstant(4));
11000   Store = DAG.getStore(Op.getOperand(0), DL,
11001                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11002                                        MVT::i32),
11003                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11004   MemOps.push_back(Store);
11005
11006   // Store ptr to overflow_arg_area
11007   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11008                     FIN, DAG.getIntPtrConstant(4));
11009   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11010                                     getPointerTy());
11011   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11012                        MachinePointerInfo(SV, 8),
11013                        false, false, 0);
11014   MemOps.push_back(Store);
11015
11016   // Store ptr to reg_save_area.
11017   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11018                     FIN, DAG.getIntPtrConstant(8));
11019   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11020                                     getPointerTy());
11021   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11022                        MachinePointerInfo(SV, 16), false, false, 0);
11023   MemOps.push_back(Store);
11024   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11025                      &MemOps[0], MemOps.size());
11026 }
11027
11028 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11029   assert(Subtarget->is64Bit() &&
11030          "LowerVAARG only handles 64-bit va_arg!");
11031   assert((Subtarget->isTargetLinux() ||
11032           Subtarget->isTargetDarwin()) &&
11033           "Unhandled target in LowerVAARG");
11034   assert(Op.getNode()->getNumOperands() == 4);
11035   SDValue Chain = Op.getOperand(0);
11036   SDValue SrcPtr = Op.getOperand(1);
11037   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11038   unsigned Align = Op.getConstantOperandVal(3);
11039   SDLoc dl(Op);
11040
11041   EVT ArgVT = Op.getNode()->getValueType(0);
11042   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11043   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11044   uint8_t ArgMode;
11045
11046   // Decide which area this value should be read from.
11047   // TODO: Implement the AMD64 ABI in its entirety. This simple
11048   // selection mechanism works only for the basic types.
11049   if (ArgVT == MVT::f80) {
11050     llvm_unreachable("va_arg for f80 not yet implemented");
11051   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11052     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11053   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11054     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11055   } else {
11056     llvm_unreachable("Unhandled argument type in LowerVAARG");
11057   }
11058
11059   if (ArgMode == 2) {
11060     // Sanity Check: Make sure using fp_offset makes sense.
11061     assert(!getTargetMachine().Options.UseSoftFloat &&
11062            !(DAG.getMachineFunction()
11063                 .getFunction()->getAttributes()
11064                 .hasAttribute(AttributeSet::FunctionIndex,
11065                               Attribute::NoImplicitFloat)) &&
11066            Subtarget->hasSSE1());
11067   }
11068
11069   // Insert VAARG_64 node into the DAG
11070   // VAARG_64 returns two values: Variable Argument Address, Chain
11071   SmallVector<SDValue, 11> InstOps;
11072   InstOps.push_back(Chain);
11073   InstOps.push_back(SrcPtr);
11074   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11075   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11076   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11077   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11078   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11079                                           VTs, &InstOps[0], InstOps.size(),
11080                                           MVT::i64,
11081                                           MachinePointerInfo(SV),
11082                                           /*Align=*/0,
11083                                           /*Volatile=*/false,
11084                                           /*ReadMem=*/true,
11085                                           /*WriteMem=*/true);
11086   Chain = VAARG.getValue(1);
11087
11088   // Load the next argument and return it
11089   return DAG.getLoad(ArgVT, dl,
11090                      Chain,
11091                      VAARG,
11092                      MachinePointerInfo(),
11093                      false, false, false, 0);
11094 }
11095
11096 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11097                            SelectionDAG &DAG) {
11098   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11099   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11100   SDValue Chain = Op.getOperand(0);
11101   SDValue DstPtr = Op.getOperand(1);
11102   SDValue SrcPtr = Op.getOperand(2);
11103   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11104   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11105   SDLoc DL(Op);
11106
11107   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11108                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11109                        false,
11110                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11111 }
11112
11113 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11114 // amount is a constant. Takes immediate version of shift as input.
11115 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11116                                           SDValue SrcOp, uint64_t ShiftAmt,
11117                                           SelectionDAG &DAG) {
11118   MVT ElementType = VT.getVectorElementType();
11119
11120   // Check for ShiftAmt >= element width
11121   if (ShiftAmt >= ElementType.getSizeInBits()) {
11122     if (Opc == X86ISD::VSRAI)
11123       ShiftAmt = ElementType.getSizeInBits() - 1;
11124     else
11125       return DAG.getConstant(0, VT);
11126   }
11127
11128   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11129          && "Unknown target vector shift-by-constant node");
11130
11131   // Fold this packed vector shift into a build vector if SrcOp is a
11132   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11133   if (VT == SrcOp.getSimpleValueType() &&
11134       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11135     SmallVector<SDValue, 8> Elts;
11136     unsigned NumElts = SrcOp->getNumOperands();
11137     ConstantSDNode *ND;
11138
11139     switch(Opc) {
11140     default: llvm_unreachable(0);
11141     case X86ISD::VSHLI:
11142       for (unsigned i=0; i!=NumElts; ++i) {
11143         SDValue CurrentOp = SrcOp->getOperand(i);
11144         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11145           Elts.push_back(CurrentOp);
11146           continue;
11147         }
11148         ND = cast<ConstantSDNode>(CurrentOp);
11149         const APInt &C = ND->getAPIntValue();
11150         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11151       }
11152       break;
11153     case X86ISD::VSRLI:
11154       for (unsigned i=0; i!=NumElts; ++i) {
11155         SDValue CurrentOp = SrcOp->getOperand(i);
11156         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11157           Elts.push_back(CurrentOp);
11158           continue;
11159         }
11160         ND = cast<ConstantSDNode>(CurrentOp);
11161         const APInt &C = ND->getAPIntValue();
11162         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11163       }
11164       break;
11165     case X86ISD::VSRAI:
11166       for (unsigned i=0; i!=NumElts; ++i) {
11167         SDValue CurrentOp = SrcOp->getOperand(i);
11168         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11169           Elts.push_back(CurrentOp);
11170           continue;
11171         }
11172         ND = cast<ConstantSDNode>(CurrentOp);
11173         const APInt &C = ND->getAPIntValue();
11174         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11175       }
11176       break;
11177     }
11178
11179     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Elts[0], NumElts);
11180   }
11181
11182   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11183 }
11184
11185 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11186 // may or may not be a constant. Takes immediate version of shift as input.
11187 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11188                                    SDValue SrcOp, SDValue ShAmt,
11189                                    SelectionDAG &DAG) {
11190   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11191
11192   // Catch shift-by-constant.
11193   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11194     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11195                                       CShAmt->getZExtValue(), DAG);
11196
11197   // Change opcode to non-immediate version
11198   switch (Opc) {
11199     default: llvm_unreachable("Unknown target vector shift node");
11200     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11201     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11202     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11203   }
11204
11205   // Need to build a vector containing shift amount
11206   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11207   SDValue ShOps[4];
11208   ShOps[0] = ShAmt;
11209   ShOps[1] = DAG.getConstant(0, MVT::i32);
11210   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11211   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
11212
11213   // The return type has to be a 128-bit type with the same element
11214   // type as the input type.
11215   MVT EltVT = VT.getVectorElementType();
11216   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11217
11218   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11219   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11220 }
11221
11222 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11223   SDLoc dl(Op);
11224   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11225   switch (IntNo) {
11226   default: return SDValue();    // Don't custom lower most intrinsics.
11227   // Comparison intrinsics.
11228   case Intrinsic::x86_sse_comieq_ss:
11229   case Intrinsic::x86_sse_comilt_ss:
11230   case Intrinsic::x86_sse_comile_ss:
11231   case Intrinsic::x86_sse_comigt_ss:
11232   case Intrinsic::x86_sse_comige_ss:
11233   case Intrinsic::x86_sse_comineq_ss:
11234   case Intrinsic::x86_sse_ucomieq_ss:
11235   case Intrinsic::x86_sse_ucomilt_ss:
11236   case Intrinsic::x86_sse_ucomile_ss:
11237   case Intrinsic::x86_sse_ucomigt_ss:
11238   case Intrinsic::x86_sse_ucomige_ss:
11239   case Intrinsic::x86_sse_ucomineq_ss:
11240   case Intrinsic::x86_sse2_comieq_sd:
11241   case Intrinsic::x86_sse2_comilt_sd:
11242   case Intrinsic::x86_sse2_comile_sd:
11243   case Intrinsic::x86_sse2_comigt_sd:
11244   case Intrinsic::x86_sse2_comige_sd:
11245   case Intrinsic::x86_sse2_comineq_sd:
11246   case Intrinsic::x86_sse2_ucomieq_sd:
11247   case Intrinsic::x86_sse2_ucomilt_sd:
11248   case Intrinsic::x86_sse2_ucomile_sd:
11249   case Intrinsic::x86_sse2_ucomigt_sd:
11250   case Intrinsic::x86_sse2_ucomige_sd:
11251   case Intrinsic::x86_sse2_ucomineq_sd: {
11252     unsigned Opc;
11253     ISD::CondCode CC;
11254     switch (IntNo) {
11255     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11256     case Intrinsic::x86_sse_comieq_ss:
11257     case Intrinsic::x86_sse2_comieq_sd:
11258       Opc = X86ISD::COMI;
11259       CC = ISD::SETEQ;
11260       break;
11261     case Intrinsic::x86_sse_comilt_ss:
11262     case Intrinsic::x86_sse2_comilt_sd:
11263       Opc = X86ISD::COMI;
11264       CC = ISD::SETLT;
11265       break;
11266     case Intrinsic::x86_sse_comile_ss:
11267     case Intrinsic::x86_sse2_comile_sd:
11268       Opc = X86ISD::COMI;
11269       CC = ISD::SETLE;
11270       break;
11271     case Intrinsic::x86_sse_comigt_ss:
11272     case Intrinsic::x86_sse2_comigt_sd:
11273       Opc = X86ISD::COMI;
11274       CC = ISD::SETGT;
11275       break;
11276     case Intrinsic::x86_sse_comige_ss:
11277     case Intrinsic::x86_sse2_comige_sd:
11278       Opc = X86ISD::COMI;
11279       CC = ISD::SETGE;
11280       break;
11281     case Intrinsic::x86_sse_comineq_ss:
11282     case Intrinsic::x86_sse2_comineq_sd:
11283       Opc = X86ISD::COMI;
11284       CC = ISD::SETNE;
11285       break;
11286     case Intrinsic::x86_sse_ucomieq_ss:
11287     case Intrinsic::x86_sse2_ucomieq_sd:
11288       Opc = X86ISD::UCOMI;
11289       CC = ISD::SETEQ;
11290       break;
11291     case Intrinsic::x86_sse_ucomilt_ss:
11292     case Intrinsic::x86_sse2_ucomilt_sd:
11293       Opc = X86ISD::UCOMI;
11294       CC = ISD::SETLT;
11295       break;
11296     case Intrinsic::x86_sse_ucomile_ss:
11297     case Intrinsic::x86_sse2_ucomile_sd:
11298       Opc = X86ISD::UCOMI;
11299       CC = ISD::SETLE;
11300       break;
11301     case Intrinsic::x86_sse_ucomigt_ss:
11302     case Intrinsic::x86_sse2_ucomigt_sd:
11303       Opc = X86ISD::UCOMI;
11304       CC = ISD::SETGT;
11305       break;
11306     case Intrinsic::x86_sse_ucomige_ss:
11307     case Intrinsic::x86_sse2_ucomige_sd:
11308       Opc = X86ISD::UCOMI;
11309       CC = ISD::SETGE;
11310       break;
11311     case Intrinsic::x86_sse_ucomineq_ss:
11312     case Intrinsic::x86_sse2_ucomineq_sd:
11313       Opc = X86ISD::UCOMI;
11314       CC = ISD::SETNE;
11315       break;
11316     }
11317
11318     SDValue LHS = Op.getOperand(1);
11319     SDValue RHS = Op.getOperand(2);
11320     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11321     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11322     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11323     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11324                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11325     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11326   }
11327
11328   // Arithmetic intrinsics.
11329   case Intrinsic::x86_sse2_pmulu_dq:
11330   case Intrinsic::x86_avx2_pmulu_dq:
11331     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11332                        Op.getOperand(1), Op.getOperand(2));
11333
11334   // SSE2/AVX2 sub with unsigned saturation intrinsics
11335   case Intrinsic::x86_sse2_psubus_b:
11336   case Intrinsic::x86_sse2_psubus_w:
11337   case Intrinsic::x86_avx2_psubus_b:
11338   case Intrinsic::x86_avx2_psubus_w:
11339     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11340                        Op.getOperand(1), Op.getOperand(2));
11341
11342   // SSE3/AVX horizontal add/sub intrinsics
11343   case Intrinsic::x86_sse3_hadd_ps:
11344   case Intrinsic::x86_sse3_hadd_pd:
11345   case Intrinsic::x86_avx_hadd_ps_256:
11346   case Intrinsic::x86_avx_hadd_pd_256:
11347   case Intrinsic::x86_sse3_hsub_ps:
11348   case Intrinsic::x86_sse3_hsub_pd:
11349   case Intrinsic::x86_avx_hsub_ps_256:
11350   case Intrinsic::x86_avx_hsub_pd_256:
11351   case Intrinsic::x86_ssse3_phadd_w_128:
11352   case Intrinsic::x86_ssse3_phadd_d_128:
11353   case Intrinsic::x86_avx2_phadd_w:
11354   case Intrinsic::x86_avx2_phadd_d:
11355   case Intrinsic::x86_ssse3_phsub_w_128:
11356   case Intrinsic::x86_ssse3_phsub_d_128:
11357   case Intrinsic::x86_avx2_phsub_w:
11358   case Intrinsic::x86_avx2_phsub_d: {
11359     unsigned Opcode;
11360     switch (IntNo) {
11361     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11362     case Intrinsic::x86_sse3_hadd_ps:
11363     case Intrinsic::x86_sse3_hadd_pd:
11364     case Intrinsic::x86_avx_hadd_ps_256:
11365     case Intrinsic::x86_avx_hadd_pd_256:
11366       Opcode = X86ISD::FHADD;
11367       break;
11368     case Intrinsic::x86_sse3_hsub_ps:
11369     case Intrinsic::x86_sse3_hsub_pd:
11370     case Intrinsic::x86_avx_hsub_ps_256:
11371     case Intrinsic::x86_avx_hsub_pd_256:
11372       Opcode = X86ISD::FHSUB;
11373       break;
11374     case Intrinsic::x86_ssse3_phadd_w_128:
11375     case Intrinsic::x86_ssse3_phadd_d_128:
11376     case Intrinsic::x86_avx2_phadd_w:
11377     case Intrinsic::x86_avx2_phadd_d:
11378       Opcode = X86ISD::HADD;
11379       break;
11380     case Intrinsic::x86_ssse3_phsub_w_128:
11381     case Intrinsic::x86_ssse3_phsub_d_128:
11382     case Intrinsic::x86_avx2_phsub_w:
11383     case Intrinsic::x86_avx2_phsub_d:
11384       Opcode = X86ISD::HSUB;
11385       break;
11386     }
11387     return DAG.getNode(Opcode, dl, Op.getValueType(),
11388                        Op.getOperand(1), Op.getOperand(2));
11389   }
11390
11391   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11392   case Intrinsic::x86_sse2_pmaxu_b:
11393   case Intrinsic::x86_sse41_pmaxuw:
11394   case Intrinsic::x86_sse41_pmaxud:
11395   case Intrinsic::x86_avx2_pmaxu_b:
11396   case Intrinsic::x86_avx2_pmaxu_w:
11397   case Intrinsic::x86_avx2_pmaxu_d:
11398   case Intrinsic::x86_sse2_pminu_b:
11399   case Intrinsic::x86_sse41_pminuw:
11400   case Intrinsic::x86_sse41_pminud:
11401   case Intrinsic::x86_avx2_pminu_b:
11402   case Intrinsic::x86_avx2_pminu_w:
11403   case Intrinsic::x86_avx2_pminu_d:
11404   case Intrinsic::x86_sse41_pmaxsb:
11405   case Intrinsic::x86_sse2_pmaxs_w:
11406   case Intrinsic::x86_sse41_pmaxsd:
11407   case Intrinsic::x86_avx2_pmaxs_b:
11408   case Intrinsic::x86_avx2_pmaxs_w:
11409   case Intrinsic::x86_avx2_pmaxs_d:
11410   case Intrinsic::x86_sse41_pminsb:
11411   case Intrinsic::x86_sse2_pmins_w:
11412   case Intrinsic::x86_sse41_pminsd:
11413   case Intrinsic::x86_avx2_pmins_b:
11414   case Intrinsic::x86_avx2_pmins_w:
11415   case Intrinsic::x86_avx2_pmins_d: {
11416     unsigned Opcode;
11417     switch (IntNo) {
11418     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11419     case Intrinsic::x86_sse2_pmaxu_b:
11420     case Intrinsic::x86_sse41_pmaxuw:
11421     case Intrinsic::x86_sse41_pmaxud:
11422     case Intrinsic::x86_avx2_pmaxu_b:
11423     case Intrinsic::x86_avx2_pmaxu_w:
11424     case Intrinsic::x86_avx2_pmaxu_d:
11425       Opcode = X86ISD::UMAX;
11426       break;
11427     case Intrinsic::x86_sse2_pminu_b:
11428     case Intrinsic::x86_sse41_pminuw:
11429     case Intrinsic::x86_sse41_pminud:
11430     case Intrinsic::x86_avx2_pminu_b:
11431     case Intrinsic::x86_avx2_pminu_w:
11432     case Intrinsic::x86_avx2_pminu_d:
11433       Opcode = X86ISD::UMIN;
11434       break;
11435     case Intrinsic::x86_sse41_pmaxsb:
11436     case Intrinsic::x86_sse2_pmaxs_w:
11437     case Intrinsic::x86_sse41_pmaxsd:
11438     case Intrinsic::x86_avx2_pmaxs_b:
11439     case Intrinsic::x86_avx2_pmaxs_w:
11440     case Intrinsic::x86_avx2_pmaxs_d:
11441       Opcode = X86ISD::SMAX;
11442       break;
11443     case Intrinsic::x86_sse41_pminsb:
11444     case Intrinsic::x86_sse2_pmins_w:
11445     case Intrinsic::x86_sse41_pminsd:
11446     case Intrinsic::x86_avx2_pmins_b:
11447     case Intrinsic::x86_avx2_pmins_w:
11448     case Intrinsic::x86_avx2_pmins_d:
11449       Opcode = X86ISD::SMIN;
11450       break;
11451     }
11452     return DAG.getNode(Opcode, dl, Op.getValueType(),
11453                        Op.getOperand(1), Op.getOperand(2));
11454   }
11455
11456   // SSE/SSE2/AVX floating point max/min intrinsics.
11457   case Intrinsic::x86_sse_max_ps:
11458   case Intrinsic::x86_sse2_max_pd:
11459   case Intrinsic::x86_avx_max_ps_256:
11460   case Intrinsic::x86_avx_max_pd_256:
11461   case Intrinsic::x86_sse_min_ps:
11462   case Intrinsic::x86_sse2_min_pd:
11463   case Intrinsic::x86_avx_min_ps_256:
11464   case Intrinsic::x86_avx_min_pd_256: {
11465     unsigned Opcode;
11466     switch (IntNo) {
11467     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11468     case Intrinsic::x86_sse_max_ps:
11469     case Intrinsic::x86_sse2_max_pd:
11470     case Intrinsic::x86_avx_max_ps_256:
11471     case Intrinsic::x86_avx_max_pd_256:
11472       Opcode = X86ISD::FMAX;
11473       break;
11474     case Intrinsic::x86_sse_min_ps:
11475     case Intrinsic::x86_sse2_min_pd:
11476     case Intrinsic::x86_avx_min_ps_256:
11477     case Intrinsic::x86_avx_min_pd_256:
11478       Opcode = X86ISD::FMIN;
11479       break;
11480     }
11481     return DAG.getNode(Opcode, dl, Op.getValueType(),
11482                        Op.getOperand(1), Op.getOperand(2));
11483   }
11484
11485   // AVX2 variable shift intrinsics
11486   case Intrinsic::x86_avx2_psllv_d:
11487   case Intrinsic::x86_avx2_psllv_q:
11488   case Intrinsic::x86_avx2_psllv_d_256:
11489   case Intrinsic::x86_avx2_psllv_q_256:
11490   case Intrinsic::x86_avx2_psrlv_d:
11491   case Intrinsic::x86_avx2_psrlv_q:
11492   case Intrinsic::x86_avx2_psrlv_d_256:
11493   case Intrinsic::x86_avx2_psrlv_q_256:
11494   case Intrinsic::x86_avx2_psrav_d:
11495   case Intrinsic::x86_avx2_psrav_d_256: {
11496     unsigned Opcode;
11497     switch (IntNo) {
11498     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11499     case Intrinsic::x86_avx2_psllv_d:
11500     case Intrinsic::x86_avx2_psllv_q:
11501     case Intrinsic::x86_avx2_psllv_d_256:
11502     case Intrinsic::x86_avx2_psllv_q_256:
11503       Opcode = ISD::SHL;
11504       break;
11505     case Intrinsic::x86_avx2_psrlv_d:
11506     case Intrinsic::x86_avx2_psrlv_q:
11507     case Intrinsic::x86_avx2_psrlv_d_256:
11508     case Intrinsic::x86_avx2_psrlv_q_256:
11509       Opcode = ISD::SRL;
11510       break;
11511     case Intrinsic::x86_avx2_psrav_d:
11512     case Intrinsic::x86_avx2_psrav_d_256:
11513       Opcode = ISD::SRA;
11514       break;
11515     }
11516     return DAG.getNode(Opcode, dl, Op.getValueType(),
11517                        Op.getOperand(1), Op.getOperand(2));
11518   }
11519
11520   case Intrinsic::x86_ssse3_pshuf_b_128:
11521   case Intrinsic::x86_avx2_pshuf_b:
11522     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11523                        Op.getOperand(1), Op.getOperand(2));
11524
11525   case Intrinsic::x86_ssse3_psign_b_128:
11526   case Intrinsic::x86_ssse3_psign_w_128:
11527   case Intrinsic::x86_ssse3_psign_d_128:
11528   case Intrinsic::x86_avx2_psign_b:
11529   case Intrinsic::x86_avx2_psign_w:
11530   case Intrinsic::x86_avx2_psign_d:
11531     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11532                        Op.getOperand(1), Op.getOperand(2));
11533
11534   case Intrinsic::x86_sse41_insertps:
11535     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11536                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11537
11538   case Intrinsic::x86_avx_vperm2f128_ps_256:
11539   case Intrinsic::x86_avx_vperm2f128_pd_256:
11540   case Intrinsic::x86_avx_vperm2f128_si_256:
11541   case Intrinsic::x86_avx2_vperm2i128:
11542     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11543                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11544
11545   case Intrinsic::x86_avx2_permd:
11546   case Intrinsic::x86_avx2_permps:
11547     // Operands intentionally swapped. Mask is last operand to intrinsic,
11548     // but second operand for node/instruction.
11549     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11550                        Op.getOperand(2), Op.getOperand(1));
11551
11552   case Intrinsic::x86_sse_sqrt_ps:
11553   case Intrinsic::x86_sse2_sqrt_pd:
11554   case Intrinsic::x86_avx_sqrt_ps_256:
11555   case Intrinsic::x86_avx_sqrt_pd_256:
11556     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11557
11558   // ptest and testp intrinsics. The intrinsic these come from are designed to
11559   // return an integer value, not just an instruction so lower it to the ptest
11560   // or testp pattern and a setcc for the result.
11561   case Intrinsic::x86_sse41_ptestz:
11562   case Intrinsic::x86_sse41_ptestc:
11563   case Intrinsic::x86_sse41_ptestnzc:
11564   case Intrinsic::x86_avx_ptestz_256:
11565   case Intrinsic::x86_avx_ptestc_256:
11566   case Intrinsic::x86_avx_ptestnzc_256:
11567   case Intrinsic::x86_avx_vtestz_ps:
11568   case Intrinsic::x86_avx_vtestc_ps:
11569   case Intrinsic::x86_avx_vtestnzc_ps:
11570   case Intrinsic::x86_avx_vtestz_pd:
11571   case Intrinsic::x86_avx_vtestc_pd:
11572   case Intrinsic::x86_avx_vtestnzc_pd:
11573   case Intrinsic::x86_avx_vtestz_ps_256:
11574   case Intrinsic::x86_avx_vtestc_ps_256:
11575   case Intrinsic::x86_avx_vtestnzc_ps_256:
11576   case Intrinsic::x86_avx_vtestz_pd_256:
11577   case Intrinsic::x86_avx_vtestc_pd_256:
11578   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11579     bool IsTestPacked = false;
11580     unsigned X86CC;
11581     switch (IntNo) {
11582     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11583     case Intrinsic::x86_avx_vtestz_ps:
11584     case Intrinsic::x86_avx_vtestz_pd:
11585     case Intrinsic::x86_avx_vtestz_ps_256:
11586     case Intrinsic::x86_avx_vtestz_pd_256:
11587       IsTestPacked = true; // Fallthrough
11588     case Intrinsic::x86_sse41_ptestz:
11589     case Intrinsic::x86_avx_ptestz_256:
11590       // ZF = 1
11591       X86CC = X86::COND_E;
11592       break;
11593     case Intrinsic::x86_avx_vtestc_ps:
11594     case Intrinsic::x86_avx_vtestc_pd:
11595     case Intrinsic::x86_avx_vtestc_ps_256:
11596     case Intrinsic::x86_avx_vtestc_pd_256:
11597       IsTestPacked = true; // Fallthrough
11598     case Intrinsic::x86_sse41_ptestc:
11599     case Intrinsic::x86_avx_ptestc_256:
11600       // CF = 1
11601       X86CC = X86::COND_B;
11602       break;
11603     case Intrinsic::x86_avx_vtestnzc_ps:
11604     case Intrinsic::x86_avx_vtestnzc_pd:
11605     case Intrinsic::x86_avx_vtestnzc_ps_256:
11606     case Intrinsic::x86_avx_vtestnzc_pd_256:
11607       IsTestPacked = true; // Fallthrough
11608     case Intrinsic::x86_sse41_ptestnzc:
11609     case Intrinsic::x86_avx_ptestnzc_256:
11610       // ZF and CF = 0
11611       X86CC = X86::COND_A;
11612       break;
11613     }
11614
11615     SDValue LHS = Op.getOperand(1);
11616     SDValue RHS = Op.getOperand(2);
11617     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11618     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11619     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11620     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11621     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11622   }
11623   case Intrinsic::x86_avx512_kortestz_w:
11624   case Intrinsic::x86_avx512_kortestc_w: {
11625     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
11626     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
11627     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
11628     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11629     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
11630     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
11631     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11632   }
11633
11634   // SSE/AVX shift intrinsics
11635   case Intrinsic::x86_sse2_psll_w:
11636   case Intrinsic::x86_sse2_psll_d:
11637   case Intrinsic::x86_sse2_psll_q:
11638   case Intrinsic::x86_avx2_psll_w:
11639   case Intrinsic::x86_avx2_psll_d:
11640   case Intrinsic::x86_avx2_psll_q:
11641   case Intrinsic::x86_sse2_psrl_w:
11642   case Intrinsic::x86_sse2_psrl_d:
11643   case Intrinsic::x86_sse2_psrl_q:
11644   case Intrinsic::x86_avx2_psrl_w:
11645   case Intrinsic::x86_avx2_psrl_d:
11646   case Intrinsic::x86_avx2_psrl_q:
11647   case Intrinsic::x86_sse2_psra_w:
11648   case Intrinsic::x86_sse2_psra_d:
11649   case Intrinsic::x86_avx2_psra_w:
11650   case Intrinsic::x86_avx2_psra_d: {
11651     unsigned Opcode;
11652     switch (IntNo) {
11653     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11654     case Intrinsic::x86_sse2_psll_w:
11655     case Intrinsic::x86_sse2_psll_d:
11656     case Intrinsic::x86_sse2_psll_q:
11657     case Intrinsic::x86_avx2_psll_w:
11658     case Intrinsic::x86_avx2_psll_d:
11659     case Intrinsic::x86_avx2_psll_q:
11660       Opcode = X86ISD::VSHL;
11661       break;
11662     case Intrinsic::x86_sse2_psrl_w:
11663     case Intrinsic::x86_sse2_psrl_d:
11664     case Intrinsic::x86_sse2_psrl_q:
11665     case Intrinsic::x86_avx2_psrl_w:
11666     case Intrinsic::x86_avx2_psrl_d:
11667     case Intrinsic::x86_avx2_psrl_q:
11668       Opcode = X86ISD::VSRL;
11669       break;
11670     case Intrinsic::x86_sse2_psra_w:
11671     case Intrinsic::x86_sse2_psra_d:
11672     case Intrinsic::x86_avx2_psra_w:
11673     case Intrinsic::x86_avx2_psra_d:
11674       Opcode = X86ISD::VSRA;
11675       break;
11676     }
11677     return DAG.getNode(Opcode, dl, Op.getValueType(),
11678                        Op.getOperand(1), Op.getOperand(2));
11679   }
11680
11681   // SSE/AVX immediate shift intrinsics
11682   case Intrinsic::x86_sse2_pslli_w:
11683   case Intrinsic::x86_sse2_pslli_d:
11684   case Intrinsic::x86_sse2_pslli_q:
11685   case Intrinsic::x86_avx2_pslli_w:
11686   case Intrinsic::x86_avx2_pslli_d:
11687   case Intrinsic::x86_avx2_pslli_q:
11688   case Intrinsic::x86_sse2_psrli_w:
11689   case Intrinsic::x86_sse2_psrli_d:
11690   case Intrinsic::x86_sse2_psrli_q:
11691   case Intrinsic::x86_avx2_psrli_w:
11692   case Intrinsic::x86_avx2_psrli_d:
11693   case Intrinsic::x86_avx2_psrli_q:
11694   case Intrinsic::x86_sse2_psrai_w:
11695   case Intrinsic::x86_sse2_psrai_d:
11696   case Intrinsic::x86_avx2_psrai_w:
11697   case Intrinsic::x86_avx2_psrai_d: {
11698     unsigned Opcode;
11699     switch (IntNo) {
11700     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11701     case Intrinsic::x86_sse2_pslli_w:
11702     case Intrinsic::x86_sse2_pslli_d:
11703     case Intrinsic::x86_sse2_pslli_q:
11704     case Intrinsic::x86_avx2_pslli_w:
11705     case Intrinsic::x86_avx2_pslli_d:
11706     case Intrinsic::x86_avx2_pslli_q:
11707       Opcode = X86ISD::VSHLI;
11708       break;
11709     case Intrinsic::x86_sse2_psrli_w:
11710     case Intrinsic::x86_sse2_psrli_d:
11711     case Intrinsic::x86_sse2_psrli_q:
11712     case Intrinsic::x86_avx2_psrli_w:
11713     case Intrinsic::x86_avx2_psrli_d:
11714     case Intrinsic::x86_avx2_psrli_q:
11715       Opcode = X86ISD::VSRLI;
11716       break;
11717     case Intrinsic::x86_sse2_psrai_w:
11718     case Intrinsic::x86_sse2_psrai_d:
11719     case Intrinsic::x86_avx2_psrai_w:
11720     case Intrinsic::x86_avx2_psrai_d:
11721       Opcode = X86ISD::VSRAI;
11722       break;
11723     }
11724     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
11725                                Op.getOperand(1), Op.getOperand(2), DAG);
11726   }
11727
11728   case Intrinsic::x86_sse42_pcmpistria128:
11729   case Intrinsic::x86_sse42_pcmpestria128:
11730   case Intrinsic::x86_sse42_pcmpistric128:
11731   case Intrinsic::x86_sse42_pcmpestric128:
11732   case Intrinsic::x86_sse42_pcmpistrio128:
11733   case Intrinsic::x86_sse42_pcmpestrio128:
11734   case Intrinsic::x86_sse42_pcmpistris128:
11735   case Intrinsic::x86_sse42_pcmpestris128:
11736   case Intrinsic::x86_sse42_pcmpistriz128:
11737   case Intrinsic::x86_sse42_pcmpestriz128: {
11738     unsigned Opcode;
11739     unsigned X86CC;
11740     switch (IntNo) {
11741     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11742     case Intrinsic::x86_sse42_pcmpistria128:
11743       Opcode = X86ISD::PCMPISTRI;
11744       X86CC = X86::COND_A;
11745       break;
11746     case Intrinsic::x86_sse42_pcmpestria128:
11747       Opcode = X86ISD::PCMPESTRI;
11748       X86CC = X86::COND_A;
11749       break;
11750     case Intrinsic::x86_sse42_pcmpistric128:
11751       Opcode = X86ISD::PCMPISTRI;
11752       X86CC = X86::COND_B;
11753       break;
11754     case Intrinsic::x86_sse42_pcmpestric128:
11755       Opcode = X86ISD::PCMPESTRI;
11756       X86CC = X86::COND_B;
11757       break;
11758     case Intrinsic::x86_sse42_pcmpistrio128:
11759       Opcode = X86ISD::PCMPISTRI;
11760       X86CC = X86::COND_O;
11761       break;
11762     case Intrinsic::x86_sse42_pcmpestrio128:
11763       Opcode = X86ISD::PCMPESTRI;
11764       X86CC = X86::COND_O;
11765       break;
11766     case Intrinsic::x86_sse42_pcmpistris128:
11767       Opcode = X86ISD::PCMPISTRI;
11768       X86CC = X86::COND_S;
11769       break;
11770     case Intrinsic::x86_sse42_pcmpestris128:
11771       Opcode = X86ISD::PCMPESTRI;
11772       X86CC = X86::COND_S;
11773       break;
11774     case Intrinsic::x86_sse42_pcmpistriz128:
11775       Opcode = X86ISD::PCMPISTRI;
11776       X86CC = X86::COND_E;
11777       break;
11778     case Intrinsic::x86_sse42_pcmpestriz128:
11779       Opcode = X86ISD::PCMPESTRI;
11780       X86CC = X86::COND_E;
11781       break;
11782     }
11783     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11784     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11785     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11786     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11787                                 DAG.getConstant(X86CC, MVT::i8),
11788                                 SDValue(PCMP.getNode(), 1));
11789     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11790   }
11791
11792   case Intrinsic::x86_sse42_pcmpistri128:
11793   case Intrinsic::x86_sse42_pcmpestri128: {
11794     unsigned Opcode;
11795     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11796       Opcode = X86ISD::PCMPISTRI;
11797     else
11798       Opcode = X86ISD::PCMPESTRI;
11799
11800     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11801     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11802     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11803   }
11804   case Intrinsic::x86_fma_vfmadd_ps:
11805   case Intrinsic::x86_fma_vfmadd_pd:
11806   case Intrinsic::x86_fma_vfmsub_ps:
11807   case Intrinsic::x86_fma_vfmsub_pd:
11808   case Intrinsic::x86_fma_vfnmadd_ps:
11809   case Intrinsic::x86_fma_vfnmadd_pd:
11810   case Intrinsic::x86_fma_vfnmsub_ps:
11811   case Intrinsic::x86_fma_vfnmsub_pd:
11812   case Intrinsic::x86_fma_vfmaddsub_ps:
11813   case Intrinsic::x86_fma_vfmaddsub_pd:
11814   case Intrinsic::x86_fma_vfmsubadd_ps:
11815   case Intrinsic::x86_fma_vfmsubadd_pd:
11816   case Intrinsic::x86_fma_vfmadd_ps_256:
11817   case Intrinsic::x86_fma_vfmadd_pd_256:
11818   case Intrinsic::x86_fma_vfmsub_ps_256:
11819   case Intrinsic::x86_fma_vfmsub_pd_256:
11820   case Intrinsic::x86_fma_vfnmadd_ps_256:
11821   case Intrinsic::x86_fma_vfnmadd_pd_256:
11822   case Intrinsic::x86_fma_vfnmsub_ps_256:
11823   case Intrinsic::x86_fma_vfnmsub_pd_256:
11824   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11825   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11826   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11827   case Intrinsic::x86_fma_vfmsubadd_pd_256:
11828   case Intrinsic::x86_fma_vfmadd_ps_512:
11829   case Intrinsic::x86_fma_vfmadd_pd_512:
11830   case Intrinsic::x86_fma_vfmsub_ps_512:
11831   case Intrinsic::x86_fma_vfmsub_pd_512:
11832   case Intrinsic::x86_fma_vfnmadd_ps_512:
11833   case Intrinsic::x86_fma_vfnmadd_pd_512:
11834   case Intrinsic::x86_fma_vfnmsub_ps_512:
11835   case Intrinsic::x86_fma_vfnmsub_pd_512:
11836   case Intrinsic::x86_fma_vfmaddsub_ps_512:
11837   case Intrinsic::x86_fma_vfmaddsub_pd_512:
11838   case Intrinsic::x86_fma_vfmsubadd_ps_512:
11839   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
11840     unsigned Opc;
11841     switch (IntNo) {
11842     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11843     case Intrinsic::x86_fma_vfmadd_ps:
11844     case Intrinsic::x86_fma_vfmadd_pd:
11845     case Intrinsic::x86_fma_vfmadd_ps_256:
11846     case Intrinsic::x86_fma_vfmadd_pd_256:
11847     case Intrinsic::x86_fma_vfmadd_ps_512:
11848     case Intrinsic::x86_fma_vfmadd_pd_512:
11849       Opc = X86ISD::FMADD;
11850       break;
11851     case Intrinsic::x86_fma_vfmsub_ps:
11852     case Intrinsic::x86_fma_vfmsub_pd:
11853     case Intrinsic::x86_fma_vfmsub_ps_256:
11854     case Intrinsic::x86_fma_vfmsub_pd_256:
11855     case Intrinsic::x86_fma_vfmsub_ps_512:
11856     case Intrinsic::x86_fma_vfmsub_pd_512:
11857       Opc = X86ISD::FMSUB;
11858       break;
11859     case Intrinsic::x86_fma_vfnmadd_ps:
11860     case Intrinsic::x86_fma_vfnmadd_pd:
11861     case Intrinsic::x86_fma_vfnmadd_ps_256:
11862     case Intrinsic::x86_fma_vfnmadd_pd_256:
11863     case Intrinsic::x86_fma_vfnmadd_ps_512:
11864     case Intrinsic::x86_fma_vfnmadd_pd_512:
11865       Opc = X86ISD::FNMADD;
11866       break;
11867     case Intrinsic::x86_fma_vfnmsub_ps:
11868     case Intrinsic::x86_fma_vfnmsub_pd:
11869     case Intrinsic::x86_fma_vfnmsub_ps_256:
11870     case Intrinsic::x86_fma_vfnmsub_pd_256:
11871     case Intrinsic::x86_fma_vfnmsub_ps_512:
11872     case Intrinsic::x86_fma_vfnmsub_pd_512:
11873       Opc = X86ISD::FNMSUB;
11874       break;
11875     case Intrinsic::x86_fma_vfmaddsub_ps:
11876     case Intrinsic::x86_fma_vfmaddsub_pd:
11877     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11878     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11879     case Intrinsic::x86_fma_vfmaddsub_ps_512:
11880     case Intrinsic::x86_fma_vfmaddsub_pd_512:
11881       Opc = X86ISD::FMADDSUB;
11882       break;
11883     case Intrinsic::x86_fma_vfmsubadd_ps:
11884     case Intrinsic::x86_fma_vfmsubadd_pd:
11885     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11886     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11887     case Intrinsic::x86_fma_vfmsubadd_ps_512:
11888     case Intrinsic::x86_fma_vfmsubadd_pd_512:
11889       Opc = X86ISD::FMSUBADD;
11890       break;
11891     }
11892
11893     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11894                        Op.getOperand(2), Op.getOperand(3));
11895   }
11896   }
11897 }
11898
11899 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11900                              SDValue Base, SDValue Index,
11901                              SDValue ScaleOp, SDValue Chain,
11902                              const X86Subtarget * Subtarget) {
11903   SDLoc dl(Op);
11904   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11905   assert(C && "Invalid scale type");
11906   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11907   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11908   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11909                              Index.getSimpleValueType().getVectorNumElements());
11910   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11911   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11912   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11913   SDValue Segment = DAG.getRegister(0, MVT::i32);
11914   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11915   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11916   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11917   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11918 }
11919
11920 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11921                               SDValue Src, SDValue Mask, SDValue Base,
11922                               SDValue Index, SDValue ScaleOp, SDValue Chain,
11923                               const X86Subtarget * Subtarget) {
11924   SDLoc dl(Op);
11925   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11926   assert(C && "Invalid scale type");
11927   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11928   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11929                              Index.getSimpleValueType().getVectorNumElements());
11930   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11931   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
11932   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11933   SDValue Segment = DAG.getRegister(0, MVT::i32);
11934   if (Src.getOpcode() == ISD::UNDEF)
11935     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
11936   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
11937   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11938   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
11939   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
11940 }
11941
11942 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11943                               SDValue Src, SDValue Base, SDValue Index,
11944                               SDValue ScaleOp, SDValue Chain) {
11945   SDLoc dl(Op);
11946   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11947   assert(C && "Invalid scale type");
11948   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11949   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11950   SDValue Segment = DAG.getRegister(0, MVT::i32);
11951   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11952                              Index.getSimpleValueType().getVectorNumElements());
11953   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
11954   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11955   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11956   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11957   return SDValue(Res, 1);
11958 }
11959
11960 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
11961                                SDValue Src, SDValue Mask, SDValue Base,
11962                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
11963   SDLoc dl(Op);
11964   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
11965   assert(C && "Invalid scale type");
11966   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
11967   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
11968   SDValue Segment = DAG.getRegister(0, MVT::i32);
11969   EVT MaskVT = MVT::getVectorVT(MVT::i1,
11970                              Index.getSimpleValueType().getVectorNumElements());
11971   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
11972   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
11973   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
11974   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
11975   return SDValue(Res, 1);
11976 }
11977
11978 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
11979                                       SelectionDAG &DAG) {
11980   SDLoc dl(Op);
11981   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11982   switch (IntNo) {
11983   default: return SDValue();    // Don't custom lower most intrinsics.
11984
11985   // RDRAND/RDSEED intrinsics.
11986   case Intrinsic::x86_rdrand_16:
11987   case Intrinsic::x86_rdrand_32:
11988   case Intrinsic::x86_rdrand_64:
11989   case Intrinsic::x86_rdseed_16:
11990   case Intrinsic::x86_rdseed_32:
11991   case Intrinsic::x86_rdseed_64: {
11992     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11993                        IntNo == Intrinsic::x86_rdseed_32 ||
11994                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11995                                                             X86ISD::RDRAND;
11996     // Emit the node with the right value type.
11997     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11998     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11999
12000     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12001     // Otherwise return the value from Rand, which is always 0, casted to i32.
12002     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12003                       DAG.getConstant(1, Op->getValueType(1)),
12004                       DAG.getConstant(X86::COND_B, MVT::i32),
12005                       SDValue(Result.getNode(), 1) };
12006     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12007                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12008                                   Ops, array_lengthof(Ops));
12009
12010     // Return { result, isValid, chain }.
12011     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12012                        SDValue(Result.getNode(), 2));
12013   }
12014   //int_gather(index, base, scale);
12015   case Intrinsic::x86_avx512_gather_qpd_512:
12016   case Intrinsic::x86_avx512_gather_qps_512:
12017   case Intrinsic::x86_avx512_gather_dpd_512:
12018   case Intrinsic::x86_avx512_gather_qpi_512:
12019   case Intrinsic::x86_avx512_gather_qpq_512:
12020   case Intrinsic::x86_avx512_gather_dpq_512:
12021   case Intrinsic::x86_avx512_gather_dps_512:
12022   case Intrinsic::x86_avx512_gather_dpi_512: {
12023     unsigned Opc;
12024     switch (IntNo) {
12025     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12026     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12027     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12028     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12029     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12030     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12031     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12032     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12033     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12034     }
12035     SDValue Chain = Op.getOperand(0);
12036     SDValue Index = Op.getOperand(2);
12037     SDValue Base  = Op.getOperand(3);
12038     SDValue Scale = Op.getOperand(4);
12039     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12040   }
12041   //int_gather_mask(v1, mask, index, base, scale);
12042   case Intrinsic::x86_avx512_gather_qps_mask_512:
12043   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12044   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12045   case Intrinsic::x86_avx512_gather_dps_mask_512:
12046   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12047   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12048   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12049   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12050     unsigned Opc;
12051     switch (IntNo) {
12052     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12053     case Intrinsic::x86_avx512_gather_qps_mask_512:
12054       Opc = X86::VGATHERQPSZrm; break;
12055     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12056       Opc = X86::VGATHERQPDZrm; break;
12057     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12058       Opc = X86::VGATHERDPDZrm; break;
12059     case Intrinsic::x86_avx512_gather_dps_mask_512:
12060       Opc = X86::VGATHERDPSZrm; break;
12061     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12062       Opc = X86::VPGATHERQDZrm; break;
12063     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12064       Opc = X86::VPGATHERQQZrm; break;
12065     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12066       Opc = X86::VPGATHERDDZrm; break;
12067     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12068       Opc = X86::VPGATHERDQZrm; break;
12069     }
12070     SDValue Chain = Op.getOperand(0);
12071     SDValue Src   = Op.getOperand(2);
12072     SDValue Mask  = Op.getOperand(3);
12073     SDValue Index = Op.getOperand(4);
12074     SDValue Base  = Op.getOperand(5);
12075     SDValue Scale = Op.getOperand(6);
12076     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12077                           Subtarget);
12078   }
12079   //int_scatter(base, index, v1, scale);
12080   case Intrinsic::x86_avx512_scatter_qpd_512:
12081   case Intrinsic::x86_avx512_scatter_qps_512:
12082   case Intrinsic::x86_avx512_scatter_dpd_512:
12083   case Intrinsic::x86_avx512_scatter_qpi_512:
12084   case Intrinsic::x86_avx512_scatter_qpq_512:
12085   case Intrinsic::x86_avx512_scatter_dpq_512:
12086   case Intrinsic::x86_avx512_scatter_dps_512:
12087   case Intrinsic::x86_avx512_scatter_dpi_512: {
12088     unsigned Opc;
12089     switch (IntNo) {
12090     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12091     case Intrinsic::x86_avx512_scatter_qpd_512:
12092       Opc = X86::VSCATTERQPDZmr; break;
12093     case Intrinsic::x86_avx512_scatter_qps_512:
12094       Opc = X86::VSCATTERQPSZmr; break;
12095     case Intrinsic::x86_avx512_scatter_dpd_512:
12096       Opc = X86::VSCATTERDPDZmr; break;
12097     case Intrinsic::x86_avx512_scatter_dps_512:
12098       Opc = X86::VSCATTERDPSZmr; break;
12099     case Intrinsic::x86_avx512_scatter_qpi_512:
12100       Opc = X86::VPSCATTERQDZmr; break;
12101     case Intrinsic::x86_avx512_scatter_qpq_512:
12102       Opc = X86::VPSCATTERQQZmr; break;
12103     case Intrinsic::x86_avx512_scatter_dpq_512:
12104       Opc = X86::VPSCATTERDQZmr; break;
12105     case Intrinsic::x86_avx512_scatter_dpi_512:
12106       Opc = X86::VPSCATTERDDZmr; break;
12107     }
12108     SDValue Chain = Op.getOperand(0);
12109     SDValue Base  = Op.getOperand(2);
12110     SDValue Index = Op.getOperand(3);
12111     SDValue Src   = Op.getOperand(4);
12112     SDValue Scale = Op.getOperand(5);
12113     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12114   }
12115   //int_scatter_mask(base, mask, index, v1, scale);
12116   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12117   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12118   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12119   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12120   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12121   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12122   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12123   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12124     unsigned Opc;
12125     switch (IntNo) {
12126     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12127     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12128       Opc = X86::VSCATTERQPDZmr; break;
12129     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12130       Opc = X86::VSCATTERQPSZmr; break;
12131     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12132       Opc = X86::VSCATTERDPDZmr; break;
12133     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12134       Opc = X86::VSCATTERDPSZmr; break;
12135     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12136       Opc = X86::VPSCATTERQDZmr; break;
12137     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12138       Opc = X86::VPSCATTERQQZmr; break;
12139     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12140       Opc = X86::VPSCATTERDQZmr; break;
12141     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12142       Opc = X86::VPSCATTERDDZmr; break;
12143     }
12144     SDValue Chain = Op.getOperand(0);
12145     SDValue Base  = Op.getOperand(2);
12146     SDValue Mask  = Op.getOperand(3);
12147     SDValue Index = Op.getOperand(4);
12148     SDValue Src   = Op.getOperand(5);
12149     SDValue Scale = Op.getOperand(6);
12150     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12151   }
12152   // XTEST intrinsics.
12153   case Intrinsic::x86_xtest: {
12154     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12155     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12156     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12157                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12158                                 InTrans);
12159     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12160     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12161                        Ret, SDValue(InTrans.getNode(), 1));
12162   }
12163   }
12164 }
12165
12166 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12167                                            SelectionDAG &DAG) const {
12168   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12169   MFI->setReturnAddressIsTaken(true);
12170
12171   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12172     return SDValue();
12173
12174   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12175   SDLoc dl(Op);
12176   EVT PtrVT = getPointerTy();
12177
12178   if (Depth > 0) {
12179     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12180     const X86RegisterInfo *RegInfo =
12181       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12182     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12183     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12184                        DAG.getNode(ISD::ADD, dl, PtrVT,
12185                                    FrameAddr, Offset),
12186                        MachinePointerInfo(), false, false, false, 0);
12187   }
12188
12189   // Just load the return address.
12190   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12191   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12192                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12193 }
12194
12195 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12196   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12197   MFI->setFrameAddressIsTaken(true);
12198
12199   EVT VT = Op.getValueType();
12200   SDLoc dl(Op);  // FIXME probably not meaningful
12201   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12202   const X86RegisterInfo *RegInfo =
12203     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12204   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12205   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12206           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12207          "Invalid Frame Register!");
12208   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12209   while (Depth--)
12210     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12211                             MachinePointerInfo(),
12212                             false, false, false, 0);
12213   return FrameAddr;
12214 }
12215
12216 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12217                                                      SelectionDAG &DAG) const {
12218   const X86RegisterInfo *RegInfo =
12219     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12220   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12221 }
12222
12223 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12224   SDValue Chain     = Op.getOperand(0);
12225   SDValue Offset    = Op.getOperand(1);
12226   SDValue Handler   = Op.getOperand(2);
12227   SDLoc dl      (Op);
12228
12229   EVT PtrVT = getPointerTy();
12230   const X86RegisterInfo *RegInfo =
12231     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12232   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12233   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12234           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12235          "Invalid Frame Register!");
12236   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12237   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12238
12239   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12240                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12241   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12242   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12243                        false, false, 0);
12244   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12245
12246   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12247                      DAG.getRegister(StoreAddrReg, PtrVT));
12248 }
12249
12250 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12251                                                SelectionDAG &DAG) const {
12252   SDLoc DL(Op);
12253   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12254                      DAG.getVTList(MVT::i32, MVT::Other),
12255                      Op.getOperand(0), Op.getOperand(1));
12256 }
12257
12258 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12259                                                 SelectionDAG &DAG) const {
12260   SDLoc DL(Op);
12261   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12262                      Op.getOperand(0), Op.getOperand(1));
12263 }
12264
12265 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12266   return Op.getOperand(0);
12267 }
12268
12269 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12270                                                 SelectionDAG &DAG) const {
12271   SDValue Root = Op.getOperand(0);
12272   SDValue Trmp = Op.getOperand(1); // trampoline
12273   SDValue FPtr = Op.getOperand(2); // nested function
12274   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12275   SDLoc dl (Op);
12276
12277   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12278   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12279
12280   if (Subtarget->is64Bit()) {
12281     SDValue OutChains[6];
12282
12283     // Large code-model.
12284     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12285     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12286
12287     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12288     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12289
12290     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12291
12292     // Load the pointer to the nested function into R11.
12293     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12294     SDValue Addr = Trmp;
12295     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12296                                 Addr, MachinePointerInfo(TrmpAddr),
12297                                 false, false, 0);
12298
12299     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12300                        DAG.getConstant(2, MVT::i64));
12301     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12302                                 MachinePointerInfo(TrmpAddr, 2),
12303                                 false, false, 2);
12304
12305     // Load the 'nest' parameter value into R10.
12306     // R10 is specified in X86CallingConv.td
12307     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12308     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12309                        DAG.getConstant(10, MVT::i64));
12310     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12311                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12312                                 false, false, 0);
12313
12314     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12315                        DAG.getConstant(12, MVT::i64));
12316     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12317                                 MachinePointerInfo(TrmpAddr, 12),
12318                                 false, false, 2);
12319
12320     // Jump to the nested function.
12321     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12322     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12323                        DAG.getConstant(20, MVT::i64));
12324     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12325                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12326                                 false, false, 0);
12327
12328     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12329     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12330                        DAG.getConstant(22, MVT::i64));
12331     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12332                                 MachinePointerInfo(TrmpAddr, 22),
12333                                 false, false, 0);
12334
12335     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
12336   } else {
12337     const Function *Func =
12338       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12339     CallingConv::ID CC = Func->getCallingConv();
12340     unsigned NestReg;
12341
12342     switch (CC) {
12343     default:
12344       llvm_unreachable("Unsupported calling convention");
12345     case CallingConv::C:
12346     case CallingConv::X86_StdCall: {
12347       // Pass 'nest' parameter in ECX.
12348       // Must be kept in sync with X86CallingConv.td
12349       NestReg = X86::ECX;
12350
12351       // Check that ECX wasn't needed by an 'inreg' parameter.
12352       FunctionType *FTy = Func->getFunctionType();
12353       const AttributeSet &Attrs = Func->getAttributes();
12354
12355       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12356         unsigned InRegCount = 0;
12357         unsigned Idx = 1;
12358
12359         for (FunctionType::param_iterator I = FTy->param_begin(),
12360              E = FTy->param_end(); I != E; ++I, ++Idx)
12361           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12362             // FIXME: should only count parameters that are lowered to integers.
12363             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12364
12365         if (InRegCount > 2) {
12366           report_fatal_error("Nest register in use - reduce number of inreg"
12367                              " parameters!");
12368         }
12369       }
12370       break;
12371     }
12372     case CallingConv::X86_FastCall:
12373     case CallingConv::X86_ThisCall:
12374     case CallingConv::Fast:
12375       // Pass 'nest' parameter in EAX.
12376       // Must be kept in sync with X86CallingConv.td
12377       NestReg = X86::EAX;
12378       break;
12379     }
12380
12381     SDValue OutChains[4];
12382     SDValue Addr, Disp;
12383
12384     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12385                        DAG.getConstant(10, MVT::i32));
12386     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12387
12388     // This is storing the opcode for MOV32ri.
12389     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12390     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12391     OutChains[0] = DAG.getStore(Root, dl,
12392                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12393                                 Trmp, MachinePointerInfo(TrmpAddr),
12394                                 false, false, 0);
12395
12396     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12397                        DAG.getConstant(1, MVT::i32));
12398     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12399                                 MachinePointerInfo(TrmpAddr, 1),
12400                                 false, false, 1);
12401
12402     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12403     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12404                        DAG.getConstant(5, MVT::i32));
12405     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12406                                 MachinePointerInfo(TrmpAddr, 5),
12407                                 false, false, 1);
12408
12409     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12410                        DAG.getConstant(6, MVT::i32));
12411     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12412                                 MachinePointerInfo(TrmpAddr, 6),
12413                                 false, false, 1);
12414
12415     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
12416   }
12417 }
12418
12419 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12420                                             SelectionDAG &DAG) const {
12421   /*
12422    The rounding mode is in bits 11:10 of FPSR, and has the following
12423    settings:
12424      00 Round to nearest
12425      01 Round to -inf
12426      10 Round to +inf
12427      11 Round to 0
12428
12429   FLT_ROUNDS, on the other hand, expects the following:
12430     -1 Undefined
12431      0 Round to 0
12432      1 Round to nearest
12433      2 Round to +inf
12434      3 Round to -inf
12435
12436   To perform the conversion, we do:
12437     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12438   */
12439
12440   MachineFunction &MF = DAG.getMachineFunction();
12441   const TargetMachine &TM = MF.getTarget();
12442   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12443   unsigned StackAlignment = TFI.getStackAlignment();
12444   MVT VT = Op.getSimpleValueType();
12445   SDLoc DL(Op);
12446
12447   // Save FP Control Word to stack slot
12448   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12449   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12450
12451   MachineMemOperand *MMO =
12452    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12453                            MachineMemOperand::MOStore, 2, 2);
12454
12455   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12456   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12457                                           DAG.getVTList(MVT::Other),
12458                                           Ops, array_lengthof(Ops), MVT::i16,
12459                                           MMO);
12460
12461   // Load FP Control Word from stack slot
12462   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12463                             MachinePointerInfo(), false, false, false, 0);
12464
12465   // Transform as necessary
12466   SDValue CWD1 =
12467     DAG.getNode(ISD::SRL, DL, MVT::i16,
12468                 DAG.getNode(ISD::AND, DL, MVT::i16,
12469                             CWD, DAG.getConstant(0x800, MVT::i16)),
12470                 DAG.getConstant(11, MVT::i8));
12471   SDValue CWD2 =
12472     DAG.getNode(ISD::SRL, DL, MVT::i16,
12473                 DAG.getNode(ISD::AND, DL, MVT::i16,
12474                             CWD, DAG.getConstant(0x400, MVT::i16)),
12475                 DAG.getConstant(9, MVT::i8));
12476
12477   SDValue RetVal =
12478     DAG.getNode(ISD::AND, DL, MVT::i16,
12479                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12480                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12481                             DAG.getConstant(1, MVT::i16)),
12482                 DAG.getConstant(3, MVT::i16));
12483
12484   return DAG.getNode((VT.getSizeInBits() < 16 ?
12485                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12486 }
12487
12488 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12489   MVT VT = Op.getSimpleValueType();
12490   EVT OpVT = VT;
12491   unsigned NumBits = VT.getSizeInBits();
12492   SDLoc dl(Op);
12493
12494   Op = Op.getOperand(0);
12495   if (VT == MVT::i8) {
12496     // Zero extend to i32 since there is not an i8 bsr.
12497     OpVT = MVT::i32;
12498     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12499   }
12500
12501   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12502   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12503   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12504
12505   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12506   SDValue Ops[] = {
12507     Op,
12508     DAG.getConstant(NumBits+NumBits-1, OpVT),
12509     DAG.getConstant(X86::COND_E, MVT::i8),
12510     Op.getValue(1)
12511   };
12512   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
12513
12514   // Finally xor with NumBits-1.
12515   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12516
12517   if (VT == MVT::i8)
12518     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12519   return Op;
12520 }
12521
12522 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12523   MVT VT = Op.getSimpleValueType();
12524   EVT OpVT = VT;
12525   unsigned NumBits = VT.getSizeInBits();
12526   SDLoc dl(Op);
12527
12528   Op = Op.getOperand(0);
12529   if (VT == MVT::i8) {
12530     // Zero extend to i32 since there is not an i8 bsr.
12531     OpVT = MVT::i32;
12532     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12533   }
12534
12535   // Issue a bsr (scan bits in reverse).
12536   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12537   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12538
12539   // And xor with NumBits-1.
12540   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12541
12542   if (VT == MVT::i8)
12543     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12544   return Op;
12545 }
12546
12547 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
12548   MVT VT = Op.getSimpleValueType();
12549   unsigned NumBits = VT.getSizeInBits();
12550   SDLoc dl(Op);
12551   Op = Op.getOperand(0);
12552
12553   // Issue a bsf (scan bits forward) which also sets EFLAGS.
12554   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12555   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
12556
12557   // If src is zero (i.e. bsf sets ZF), returns NumBits.
12558   SDValue Ops[] = {
12559     Op,
12560     DAG.getConstant(NumBits, VT),
12561     DAG.getConstant(X86::COND_E, MVT::i8),
12562     Op.getValue(1)
12563   };
12564   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
12565 }
12566
12567 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
12568 // ones, and then concatenate the result back.
12569 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
12570   MVT VT = Op.getSimpleValueType();
12571
12572   assert(VT.is256BitVector() && VT.isInteger() &&
12573          "Unsupported value type for operation");
12574
12575   unsigned NumElems = VT.getVectorNumElements();
12576   SDLoc dl(Op);
12577
12578   // Extract the LHS vectors
12579   SDValue LHS = Op.getOperand(0);
12580   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12581   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12582
12583   // Extract the RHS vectors
12584   SDValue RHS = Op.getOperand(1);
12585   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12586   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12587
12588   MVT EltVT = VT.getVectorElementType();
12589   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12590
12591   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12592                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
12593                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
12594 }
12595
12596 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
12597   assert(Op.getSimpleValueType().is256BitVector() &&
12598          Op.getSimpleValueType().isInteger() &&
12599          "Only handle AVX 256-bit vector integer operation");
12600   return Lower256IntArith(Op, DAG);
12601 }
12602
12603 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12604   assert(Op.getSimpleValueType().is256BitVector() &&
12605          Op.getSimpleValueType().isInteger() &&
12606          "Only handle AVX 256-bit vector integer operation");
12607   return Lower256IntArith(Op, DAG);
12608 }
12609
12610 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12611                         SelectionDAG &DAG) {
12612   SDLoc dl(Op);
12613   MVT VT = Op.getSimpleValueType();
12614
12615   // Decompose 256-bit ops into smaller 128-bit ops.
12616   if (VT.is256BitVector() && !Subtarget->hasInt256())
12617     return Lower256IntArith(Op, DAG);
12618
12619   SDValue A = Op.getOperand(0);
12620   SDValue B = Op.getOperand(1);
12621
12622   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12623   if (VT == MVT::v4i32) {
12624     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12625            "Should not custom lower when pmuldq is available!");
12626
12627     // Extract the odd parts.
12628     static const int UnpackMask[] = { 1, -1, 3, -1 };
12629     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12630     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12631
12632     // Multiply the even parts.
12633     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12634     // Now multiply odd parts.
12635     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12636
12637     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12638     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12639
12640     // Merge the two vectors back together with a shuffle. This expands into 2
12641     // shuffles.
12642     static const int ShufMask[] = { 0, 4, 2, 6 };
12643     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12644   }
12645
12646   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
12647          "Only know how to lower V2I64/V4I64/V8I64 multiply");
12648
12649   //  Ahi = psrlqi(a, 32);
12650   //  Bhi = psrlqi(b, 32);
12651   //
12652   //  AloBlo = pmuludq(a, b);
12653   //  AloBhi = pmuludq(a, Bhi);
12654   //  AhiBlo = pmuludq(Ahi, b);
12655
12656   //  AloBhi = psllqi(AloBhi, 32);
12657   //  AhiBlo = psllqi(AhiBlo, 32);
12658   //  return AloBlo + AloBhi + AhiBlo;
12659
12660   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
12661   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
12662
12663   // Bit cast to 32-bit vectors for MULUDQ
12664   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
12665                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
12666   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12667   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12668   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12669   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12670
12671   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12672   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12673   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12674
12675   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
12676   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
12677
12678   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12679   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12680 }
12681
12682 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12683   MVT VT = Op.getSimpleValueType();
12684   MVT EltTy = VT.getVectorElementType();
12685   unsigned NumElts = VT.getVectorNumElements();
12686   SDValue N0 = Op.getOperand(0);
12687   SDLoc dl(Op);
12688
12689   // Lower sdiv X, pow2-const.
12690   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12691   if (!C)
12692     return SDValue();
12693
12694   APInt SplatValue, SplatUndef;
12695   unsigned SplatBitSize;
12696   bool HasAnyUndefs;
12697   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12698                           HasAnyUndefs) ||
12699       EltTy.getSizeInBits() < SplatBitSize)
12700     return SDValue();
12701
12702   if ((SplatValue != 0) &&
12703       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12704     unsigned Lg2 = SplatValue.countTrailingZeros();
12705     // Splat the sign bit.
12706     SmallVector<SDValue, 16> Sz(NumElts,
12707                                 DAG.getConstant(EltTy.getSizeInBits() - 1,
12708                                                 EltTy));
12709     SDValue SGN = DAG.getNode(ISD::SRA, dl, VT, N0,
12710                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Sz[0],
12711                                           NumElts));
12712     // Add (N0 < 0) ? abs2 - 1 : 0;
12713     SmallVector<SDValue, 16> Amt(NumElts,
12714                                  DAG.getConstant(EltTy.getSizeInBits() - Lg2,
12715                                                  EltTy));
12716     SDValue SRL = DAG.getNode(ISD::SRL, dl, VT, SGN,
12717                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Amt[0],
12718                                           NumElts));
12719     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12720     SmallVector<SDValue, 16> Lg2Amt(NumElts, DAG.getConstant(Lg2, EltTy));
12721     SDValue SRA = DAG.getNode(ISD::SRA, dl, VT, ADD,
12722                               DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Lg2Amt[0],
12723                                           NumElts));
12724
12725     // If we're dividing by a positive value, we're done.  Otherwise, we must
12726     // negate the result.
12727     if (SplatValue.isNonNegative())
12728       return SRA;
12729
12730     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12731     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12732     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12733   }
12734   return SDValue();
12735 }
12736
12737 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12738                                          const X86Subtarget *Subtarget) {
12739   MVT VT = Op.getSimpleValueType();
12740   SDLoc dl(Op);
12741   SDValue R = Op.getOperand(0);
12742   SDValue Amt = Op.getOperand(1);
12743
12744   // Optimize shl/srl/sra with constant shift amount.
12745   if (isSplatVector(Amt.getNode())) {
12746     SDValue SclrAmt = Amt->getOperand(0);
12747     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12748       uint64_t ShiftAmt = C->getZExtValue();
12749
12750       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12751           (Subtarget->hasInt256() &&
12752            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12753           (Subtarget->hasAVX512() &&
12754            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12755         if (Op.getOpcode() == ISD::SHL)
12756           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12757                                             DAG);
12758         if (Op.getOpcode() == ISD::SRL)
12759           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12760                                             DAG);
12761         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12762           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12763                                             DAG);
12764       }
12765
12766       if (VT == MVT::v16i8) {
12767         if (Op.getOpcode() == ISD::SHL) {
12768           // Make a large shift.
12769           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12770                                                    MVT::v8i16, R, ShiftAmt,
12771                                                    DAG);
12772           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12773           // Zero out the rightmost bits.
12774           SmallVector<SDValue, 16> V(16,
12775                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12776                                                      MVT::i8));
12777           return DAG.getNode(ISD::AND, dl, VT, SHL,
12778                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12779         }
12780         if (Op.getOpcode() == ISD::SRL) {
12781           // Make a large shift.
12782           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12783                                                    MVT::v8i16, R, ShiftAmt,
12784                                                    DAG);
12785           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12786           // Zero out the leftmost bits.
12787           SmallVector<SDValue, 16> V(16,
12788                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12789                                                      MVT::i8));
12790           return DAG.getNode(ISD::AND, dl, VT, SRL,
12791                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12792         }
12793         if (Op.getOpcode() == ISD::SRA) {
12794           if (ShiftAmt == 7) {
12795             // R s>> 7  ===  R s< 0
12796             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12797             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12798           }
12799
12800           // R s>> a === ((R u>> a) ^ m) - m
12801           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12802           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12803                                                          MVT::i8));
12804           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12805           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12806           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12807           return Res;
12808         }
12809         llvm_unreachable("Unknown shift opcode.");
12810       }
12811
12812       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12813         if (Op.getOpcode() == ISD::SHL) {
12814           // Make a large shift.
12815           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
12816                                                    MVT::v16i16, R, ShiftAmt,
12817                                                    DAG);
12818           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12819           // Zero out the rightmost bits.
12820           SmallVector<SDValue, 32> V(32,
12821                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12822                                                      MVT::i8));
12823           return DAG.getNode(ISD::AND, dl, VT, SHL,
12824                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12825         }
12826         if (Op.getOpcode() == ISD::SRL) {
12827           // Make a large shift.
12828           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
12829                                                    MVT::v16i16, R, ShiftAmt,
12830                                                    DAG);
12831           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12832           // Zero out the leftmost bits.
12833           SmallVector<SDValue, 32> V(32,
12834                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12835                                                      MVT::i8));
12836           return DAG.getNode(ISD::AND, dl, VT, SRL,
12837                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12838         }
12839         if (Op.getOpcode() == ISD::SRA) {
12840           if (ShiftAmt == 7) {
12841             // R s>> 7  ===  R s< 0
12842             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12843             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12844           }
12845
12846           // R s>> a === ((R u>> a) ^ m) - m
12847           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12848           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12849                                                          MVT::i8));
12850           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12851           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12852           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12853           return Res;
12854         }
12855         llvm_unreachable("Unknown shift opcode.");
12856       }
12857     }
12858   }
12859
12860   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12861   if (!Subtarget->is64Bit() &&
12862       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12863       Amt.getOpcode() == ISD::BITCAST &&
12864       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12865     Amt = Amt.getOperand(0);
12866     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
12867                      VT.getVectorNumElements();
12868     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12869     uint64_t ShiftAmt = 0;
12870     for (unsigned i = 0; i != Ratio; ++i) {
12871       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12872       if (C == 0)
12873         return SDValue();
12874       // 6 == Log2(64)
12875       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12876     }
12877     // Check remaining shift amounts.
12878     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12879       uint64_t ShAmt = 0;
12880       for (unsigned j = 0; j != Ratio; ++j) {
12881         ConstantSDNode *C =
12882           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12883         if (C == 0)
12884           return SDValue();
12885         // 6 == Log2(64)
12886         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12887       }
12888       if (ShAmt != ShiftAmt)
12889         return SDValue();
12890     }
12891     switch (Op.getOpcode()) {
12892     default:
12893       llvm_unreachable("Unknown shift opcode!");
12894     case ISD::SHL:
12895       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
12896                                         DAG);
12897     case ISD::SRL:
12898       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
12899                                         DAG);
12900     case ISD::SRA:
12901       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
12902                                         DAG);
12903     }
12904   }
12905
12906   return SDValue();
12907 }
12908
12909 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12910                                         const X86Subtarget* Subtarget) {
12911   MVT VT = Op.getSimpleValueType();
12912   SDLoc dl(Op);
12913   SDValue R = Op.getOperand(0);
12914   SDValue Amt = Op.getOperand(1);
12915
12916   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12917       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12918       (Subtarget->hasInt256() &&
12919        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12920         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
12921        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
12922     SDValue BaseShAmt;
12923     EVT EltVT = VT.getVectorElementType();
12924
12925     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12926       unsigned NumElts = VT.getVectorNumElements();
12927       unsigned i, j;
12928       for (i = 0; i != NumElts; ++i) {
12929         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12930           continue;
12931         break;
12932       }
12933       for (j = i; j != NumElts; ++j) {
12934         SDValue Arg = Amt.getOperand(j);
12935         if (Arg.getOpcode() == ISD::UNDEF) continue;
12936         if (Arg != Amt.getOperand(i))
12937           break;
12938       }
12939       if (i != NumElts && j == NumElts)
12940         BaseShAmt = Amt.getOperand(i);
12941     } else {
12942       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12943         Amt = Amt.getOperand(0);
12944       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12945                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12946         SDValue InVec = Amt.getOperand(0);
12947         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12948           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12949           unsigned i = 0;
12950           for (; i != NumElts; ++i) {
12951             SDValue Arg = InVec.getOperand(i);
12952             if (Arg.getOpcode() == ISD::UNDEF) continue;
12953             BaseShAmt = Arg;
12954             break;
12955           }
12956         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12957            if (ConstantSDNode *C =
12958                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12959              unsigned SplatIdx =
12960                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12961              if (C->getZExtValue() == SplatIdx)
12962                BaseShAmt = InVec.getOperand(1);
12963            }
12964         }
12965         if (BaseShAmt.getNode() == 0)
12966           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12967                                   DAG.getIntPtrConstant(0));
12968       }
12969     }
12970
12971     if (BaseShAmt.getNode()) {
12972       if (EltVT.bitsGT(MVT::i32))
12973         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12974       else if (EltVT.bitsLT(MVT::i32))
12975         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12976
12977       switch (Op.getOpcode()) {
12978       default:
12979         llvm_unreachable("Unknown shift opcode!");
12980       case ISD::SHL:
12981         switch (VT.SimpleTy) {
12982         default: return SDValue();
12983         case MVT::v2i64:
12984         case MVT::v4i32:
12985         case MVT::v8i16:
12986         case MVT::v4i64:
12987         case MVT::v8i32:
12988         case MVT::v16i16:
12989         case MVT::v16i32:
12990         case MVT::v8i64:
12991           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12992         }
12993       case ISD::SRA:
12994         switch (VT.SimpleTy) {
12995         default: return SDValue();
12996         case MVT::v4i32:
12997         case MVT::v8i16:
12998         case MVT::v8i32:
12999         case MVT::v16i16:
13000         case MVT::v16i32:
13001         case MVT::v8i64:
13002           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13003         }
13004       case ISD::SRL:
13005         switch (VT.SimpleTy) {
13006         default: return SDValue();
13007         case MVT::v2i64:
13008         case MVT::v4i32:
13009         case MVT::v8i16:
13010         case MVT::v4i64:
13011         case MVT::v8i32:
13012         case MVT::v16i16:
13013         case MVT::v16i32:
13014         case MVT::v8i64:
13015           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13016         }
13017       }
13018     }
13019   }
13020
13021   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13022   if (!Subtarget->is64Bit() &&
13023       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13024       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13025       Amt.getOpcode() == ISD::BITCAST &&
13026       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13027     Amt = Amt.getOperand(0);
13028     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13029                      VT.getVectorNumElements();
13030     std::vector<SDValue> Vals(Ratio);
13031     for (unsigned i = 0; i != Ratio; ++i)
13032       Vals[i] = Amt.getOperand(i);
13033     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13034       for (unsigned j = 0; j != Ratio; ++j)
13035         if (Vals[j] != Amt.getOperand(i + j))
13036           return SDValue();
13037     }
13038     switch (Op.getOpcode()) {
13039     default:
13040       llvm_unreachable("Unknown shift opcode!");
13041     case ISD::SHL:
13042       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13043     case ISD::SRL:
13044       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13045     case ISD::SRA:
13046       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13047     }
13048   }
13049
13050   return SDValue();
13051 }
13052
13053 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13054                           SelectionDAG &DAG) {
13055
13056   MVT VT = Op.getSimpleValueType();
13057   SDLoc dl(Op);
13058   SDValue R = Op.getOperand(0);
13059   SDValue Amt = Op.getOperand(1);
13060   SDValue V;
13061
13062   if (!Subtarget->hasSSE2())
13063     return SDValue();
13064
13065   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13066   if (V.getNode())
13067     return V;
13068
13069   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13070   if (V.getNode())
13071       return V;
13072
13073   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13074     return Op;
13075   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13076   if (Subtarget->hasInt256()) {
13077     if (Op.getOpcode() == ISD::SRL &&
13078         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13079          VT == MVT::v4i64 || VT == MVT::v8i32))
13080       return Op;
13081     if (Op.getOpcode() == ISD::SHL &&
13082         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13083          VT == MVT::v4i64 || VT == MVT::v8i32))
13084       return Op;
13085     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13086       return Op;
13087   }
13088
13089   // Lower SHL with variable shift amount.
13090   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13091     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13092
13093     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13094     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13095     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13096     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13097   }
13098   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13099     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13100
13101     // a = a << 5;
13102     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13103     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13104
13105     // Turn 'a' into a mask suitable for VSELECT
13106     SDValue VSelM = DAG.getConstant(0x80, VT);
13107     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13108     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13109
13110     SDValue CM1 = DAG.getConstant(0x0f, VT);
13111     SDValue CM2 = DAG.getConstant(0x3f, VT);
13112
13113     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13114     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13115     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13116     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13117     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13118
13119     // a += a
13120     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13121     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13122     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13123
13124     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13125     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13126     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13127     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13128     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13129
13130     // a += a
13131     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13132     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13133     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13134
13135     // return VSELECT(r, r+r, a);
13136     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13137                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13138     return R;
13139   }
13140
13141   // Decompose 256-bit shifts into smaller 128-bit shifts.
13142   if (VT.is256BitVector()) {
13143     unsigned NumElems = VT.getVectorNumElements();
13144     MVT EltVT = VT.getVectorElementType();
13145     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13146
13147     // Extract the two vectors
13148     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13149     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13150
13151     // Recreate the shift amount vectors
13152     SDValue Amt1, Amt2;
13153     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13154       // Constant shift amount
13155       SmallVector<SDValue, 4> Amt1Csts;
13156       SmallVector<SDValue, 4> Amt2Csts;
13157       for (unsigned i = 0; i != NumElems/2; ++i)
13158         Amt1Csts.push_back(Amt->getOperand(i));
13159       for (unsigned i = NumElems/2; i != NumElems; ++i)
13160         Amt2Csts.push_back(Amt->getOperand(i));
13161
13162       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13163                                  &Amt1Csts[0], NumElems/2);
13164       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
13165                                  &Amt2Csts[0], NumElems/2);
13166     } else {
13167       // Variable shift amount
13168       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13169       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13170     }
13171
13172     // Issue new vector shifts for the smaller types
13173     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13174     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13175
13176     // Concatenate the result back
13177     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13178   }
13179
13180   return SDValue();
13181 }
13182
13183 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13184   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13185   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13186   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13187   // has only one use.
13188   SDNode *N = Op.getNode();
13189   SDValue LHS = N->getOperand(0);
13190   SDValue RHS = N->getOperand(1);
13191   unsigned BaseOp = 0;
13192   unsigned Cond = 0;
13193   SDLoc DL(Op);
13194   switch (Op.getOpcode()) {
13195   default: llvm_unreachable("Unknown ovf instruction!");
13196   case ISD::SADDO:
13197     // A subtract of one will be selected as a INC. Note that INC doesn't
13198     // set CF, so we can't do this for UADDO.
13199     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13200       if (C->isOne()) {
13201         BaseOp = X86ISD::INC;
13202         Cond = X86::COND_O;
13203         break;
13204       }
13205     BaseOp = X86ISD::ADD;
13206     Cond = X86::COND_O;
13207     break;
13208   case ISD::UADDO:
13209     BaseOp = X86ISD::ADD;
13210     Cond = X86::COND_B;
13211     break;
13212   case ISD::SSUBO:
13213     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13214     // set CF, so we can't do this for USUBO.
13215     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13216       if (C->isOne()) {
13217         BaseOp = X86ISD::DEC;
13218         Cond = X86::COND_O;
13219         break;
13220       }
13221     BaseOp = X86ISD::SUB;
13222     Cond = X86::COND_O;
13223     break;
13224   case ISD::USUBO:
13225     BaseOp = X86ISD::SUB;
13226     Cond = X86::COND_B;
13227     break;
13228   case ISD::SMULO:
13229     BaseOp = X86ISD::SMUL;
13230     Cond = X86::COND_O;
13231     break;
13232   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13233     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13234                                  MVT::i32);
13235     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13236
13237     SDValue SetCC =
13238       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13239                   DAG.getConstant(X86::COND_O, MVT::i32),
13240                   SDValue(Sum.getNode(), 2));
13241
13242     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13243   }
13244   }
13245
13246   // Also sets EFLAGS.
13247   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13248   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13249
13250   SDValue SetCC =
13251     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13252                 DAG.getConstant(Cond, MVT::i32),
13253                 SDValue(Sum.getNode(), 1));
13254
13255   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13256 }
13257
13258 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13259                                                   SelectionDAG &DAG) const {
13260   SDLoc dl(Op);
13261   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13262   MVT VT = Op.getSimpleValueType();
13263
13264   if (!Subtarget->hasSSE2() || !VT.isVector())
13265     return SDValue();
13266
13267   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13268                       ExtraVT.getScalarType().getSizeInBits();
13269
13270   switch (VT.SimpleTy) {
13271     default: return SDValue();
13272     case MVT::v8i32:
13273     case MVT::v16i16:
13274       if (!Subtarget->hasFp256())
13275         return SDValue();
13276       if (!Subtarget->hasInt256()) {
13277         // needs to be split
13278         unsigned NumElems = VT.getVectorNumElements();
13279
13280         // Extract the LHS vectors
13281         SDValue LHS = Op.getOperand(0);
13282         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13283         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13284
13285         MVT EltVT = VT.getVectorElementType();
13286         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13287
13288         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13289         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13290         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13291                                    ExtraNumElems/2);
13292         SDValue Extra = DAG.getValueType(ExtraVT);
13293
13294         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13295         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13296
13297         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13298       }
13299       // fall through
13300     case MVT::v4i32:
13301     case MVT::v8i16: {
13302       SDValue Op0 = Op.getOperand(0);
13303       SDValue Op00 = Op0.getOperand(0);
13304       SDValue Tmp1;
13305       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13306       if (Op0.getOpcode() == ISD::BITCAST &&
13307           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13308         // (sext (vzext x)) -> (vsext x)
13309         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13310         if (Tmp1.getNode()) {
13311           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13312           // This folding is only valid when the in-reg type is a vector of i8,
13313           // i16, or i32.
13314           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13315               ExtraEltVT == MVT::i32) {
13316             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13317             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13318                    "This optimization is invalid without a VZEXT.");
13319             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13320           }
13321           Op0 = Tmp1;
13322         }
13323       }
13324
13325       // If the above didn't work, then just use Shift-Left + Shift-Right.
13326       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13327                                         DAG);
13328       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13329                                         DAG);
13330     }
13331   }
13332 }
13333
13334 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13335                                  SelectionDAG &DAG) {
13336   SDLoc dl(Op);
13337   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13338     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13339   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13340     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13341
13342   // The only fence that needs an instruction is a sequentially-consistent
13343   // cross-thread fence.
13344   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13345     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13346     // no-sse2). There isn't any reason to disable it if the target processor
13347     // supports it.
13348     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13349       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13350
13351     SDValue Chain = Op.getOperand(0);
13352     SDValue Zero = DAG.getConstant(0, MVT::i32);
13353     SDValue Ops[] = {
13354       DAG.getRegister(X86::ESP, MVT::i32), // Base
13355       DAG.getTargetConstant(1, MVT::i8),   // Scale
13356       DAG.getRegister(0, MVT::i32),        // Index
13357       DAG.getTargetConstant(0, MVT::i32),  // Disp
13358       DAG.getRegister(0, MVT::i32),        // Segment.
13359       Zero,
13360       Chain
13361     };
13362     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13363     return SDValue(Res, 0);
13364   }
13365
13366   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13367   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13368 }
13369
13370 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13371                              SelectionDAG &DAG) {
13372   MVT T = Op.getSimpleValueType();
13373   SDLoc DL(Op);
13374   unsigned Reg = 0;
13375   unsigned size = 0;
13376   switch(T.SimpleTy) {
13377   default: llvm_unreachable("Invalid value type!");
13378   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13379   case MVT::i16: Reg = X86::AX;  size = 2; break;
13380   case MVT::i32: Reg = X86::EAX; size = 4; break;
13381   case MVT::i64:
13382     assert(Subtarget->is64Bit() && "Node not type legal!");
13383     Reg = X86::RAX; size = 8;
13384     break;
13385   }
13386   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13387                                     Op.getOperand(2), SDValue());
13388   SDValue Ops[] = { cpIn.getValue(0),
13389                     Op.getOperand(1),
13390                     Op.getOperand(3),
13391                     DAG.getTargetConstant(size, MVT::i8),
13392                     cpIn.getValue(1) };
13393   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13394   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13395   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13396                                            Ops, array_lengthof(Ops), T, MMO);
13397   SDValue cpOut =
13398     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13399   return cpOut;
13400 }
13401
13402 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13403                                      SelectionDAG &DAG) {
13404   assert(Subtarget->is64Bit() && "Result not type legalized?");
13405   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13406   SDValue TheChain = Op.getOperand(0);
13407   SDLoc dl(Op);
13408   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13409   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
13410   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
13411                                    rax.getValue(2));
13412   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
13413                             DAG.getConstant(32, MVT::i8));
13414   SDValue Ops[] = {
13415     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
13416     rdx.getValue(1)
13417   };
13418   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
13419 }
13420
13421 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13422                             SelectionDAG &DAG) {
13423   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13424   MVT DstVT = Op.getSimpleValueType();
13425   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13426          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13427   assert((DstVT == MVT::i64 ||
13428           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13429          "Unexpected custom BITCAST");
13430   // i64 <=> MMX conversions are Legal.
13431   if (SrcVT==MVT::i64 && DstVT.isVector())
13432     return Op;
13433   if (DstVT==MVT::i64 && SrcVT.isVector())
13434     return Op;
13435   // MMX <=> MMX conversions are Legal.
13436   if (SrcVT.isVector() && DstVT.isVector())
13437     return Op;
13438   // All other conversions need to be expanded.
13439   return SDValue();
13440 }
13441
13442 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13443   SDNode *Node = Op.getNode();
13444   SDLoc dl(Node);
13445   EVT T = Node->getValueType(0);
13446   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13447                               DAG.getConstant(0, T), Node->getOperand(2));
13448   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13449                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13450                        Node->getOperand(0),
13451                        Node->getOperand(1), negOp,
13452                        cast<AtomicSDNode>(Node)->getSrcValue(),
13453                        cast<AtomicSDNode>(Node)->getAlignment(),
13454                        cast<AtomicSDNode>(Node)->getOrdering(),
13455                        cast<AtomicSDNode>(Node)->getSynchScope());
13456 }
13457
13458 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
13459   SDNode *Node = Op.getNode();
13460   SDLoc dl(Node);
13461   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13462
13463   // Convert seq_cst store -> xchg
13464   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
13465   // FIXME: On 32-bit, store -> fist or movq would be more efficient
13466   //        (The only way to get a 16-byte store is cmpxchg16b)
13467   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
13468   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
13469       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13470     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
13471                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
13472                                  Node->getOperand(0),
13473                                  Node->getOperand(1), Node->getOperand(2),
13474                                  cast<AtomicSDNode>(Node)->getMemOperand(),
13475                                  cast<AtomicSDNode>(Node)->getOrdering(),
13476                                  cast<AtomicSDNode>(Node)->getSynchScope());
13477     return Swap.getValue(1);
13478   }
13479   // Other atomic stores have a simple pattern.
13480   return Op;
13481 }
13482
13483 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
13484   EVT VT = Op.getNode()->getSimpleValueType(0);
13485
13486   // Let legalize expand this if it isn't a legal type yet.
13487   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13488     return SDValue();
13489
13490   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13491
13492   unsigned Opc;
13493   bool ExtraOp = false;
13494   switch (Op.getOpcode()) {
13495   default: llvm_unreachable("Invalid code");
13496   case ISD::ADDC: Opc = X86ISD::ADD; break;
13497   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
13498   case ISD::SUBC: Opc = X86ISD::SUB; break;
13499   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
13500   }
13501
13502   if (!ExtraOp)
13503     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13504                        Op.getOperand(1));
13505   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
13506                      Op.getOperand(1), Op.getOperand(2));
13507 }
13508
13509 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
13510                             SelectionDAG &DAG) {
13511   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
13512
13513   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
13514   // which returns the values as { float, float } (in XMM0) or
13515   // { double, double } (which is returned in XMM0, XMM1).
13516   SDLoc dl(Op);
13517   SDValue Arg = Op.getOperand(0);
13518   EVT ArgVT = Arg.getValueType();
13519   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13520
13521   TargetLowering::ArgListTy Args;
13522   TargetLowering::ArgListEntry Entry;
13523
13524   Entry.Node = Arg;
13525   Entry.Ty = ArgTy;
13526   Entry.isSExt = false;
13527   Entry.isZExt = false;
13528   Args.push_back(Entry);
13529
13530   bool isF64 = ArgVT == MVT::f64;
13531   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
13532   // the small struct {f32, f32} is returned in (eax, edx). For f64,
13533   // the results are returned via SRet in memory.
13534   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
13535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13536   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
13537
13538   Type *RetTy = isF64
13539     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
13540     : (Type*)VectorType::get(ArgTy, 4);
13541   TargetLowering::
13542     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
13543                          false, false, false, false, 0,
13544                          CallingConv::C, /*isTaillCall=*/false,
13545                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
13546                          Callee, Args, DAG, dl);
13547   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
13548
13549   if (isF64)
13550     // Returned in xmm0 and xmm1.
13551     return CallResult.first;
13552
13553   // Returned in bits 0:31 and 32:64 xmm0.
13554   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13555                                CallResult.first, DAG.getIntPtrConstant(0));
13556   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
13557                                CallResult.first, DAG.getIntPtrConstant(1));
13558   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
13559   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
13560 }
13561
13562 /// LowerOperation - Provide custom lowering hooks for some operations.
13563 ///
13564 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
13565   switch (Op.getOpcode()) {
13566   default: llvm_unreachable("Should not custom lower this!");
13567   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
13568   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
13569   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
13570   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
13571   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
13572   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
13573   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
13574   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
13575   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
13576   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
13577   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
13578   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
13579   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
13580   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
13581   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
13582   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
13583   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
13584   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
13585   case ISD::SHL_PARTS:
13586   case ISD::SRA_PARTS:
13587   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
13588   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
13589   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
13590   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
13591   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
13592   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
13593   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
13594   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
13595   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
13596   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
13597   case ISD::FABS:               return LowerFABS(Op, DAG);
13598   case ISD::FNEG:               return LowerFNEG(Op, DAG);
13599   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
13600   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
13601   case ISD::SETCC:              return LowerSETCC(Op, DAG);
13602   case ISD::SELECT:             return LowerSELECT(Op, DAG);
13603   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
13604   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
13605   case ISD::VASTART:            return LowerVASTART(Op, DAG);
13606   case ISD::VAARG:              return LowerVAARG(Op, DAG);
13607   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
13608   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13609   case ISD::INTRINSIC_VOID:
13610   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
13611   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
13612   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
13613   case ISD::FRAME_TO_ARGS_OFFSET:
13614                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
13615   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13616   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
13617   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
13618   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
13619   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
13620   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
13621   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
13622   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
13623   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
13624   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
13625   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
13626   case ISD::SRA:
13627   case ISD::SRL:
13628   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
13629   case ISD::SADDO:
13630   case ISD::UADDO:
13631   case ISD::SSUBO:
13632   case ISD::USUBO:
13633   case ISD::SMULO:
13634   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13635   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13636   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13637   case ISD::ADDC:
13638   case ISD::ADDE:
13639   case ISD::SUBC:
13640   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13641   case ISD::ADD:                return LowerADD(Op, DAG);
13642   case ISD::SUB:                return LowerSUB(Op, DAG);
13643   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13644   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13645   }
13646 }
13647
13648 static void ReplaceATOMIC_LOAD(SDNode *Node,
13649                                   SmallVectorImpl<SDValue> &Results,
13650                                   SelectionDAG &DAG) {
13651   SDLoc dl(Node);
13652   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13653
13654   // Convert wide load -> cmpxchg8b/cmpxchg16b
13655   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13656   //        (The only way to get a 16-byte load is cmpxchg16b)
13657   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13658   SDValue Zero = DAG.getConstant(0, VT);
13659   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13660                                Node->getOperand(0),
13661                                Node->getOperand(1), Zero, Zero,
13662                                cast<AtomicSDNode>(Node)->getMemOperand(),
13663                                cast<AtomicSDNode>(Node)->getOrdering(),
13664                                cast<AtomicSDNode>(Node)->getSynchScope());
13665   Results.push_back(Swap.getValue(0));
13666   Results.push_back(Swap.getValue(1));
13667 }
13668
13669 static void
13670 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13671                         SelectionDAG &DAG, unsigned NewOp) {
13672   SDLoc dl(Node);
13673   assert (Node->getValueType(0) == MVT::i64 &&
13674           "Only know how to expand i64 atomics");
13675
13676   SDValue Chain = Node->getOperand(0);
13677   SDValue In1 = Node->getOperand(1);
13678   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13679                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13680   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13681                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13682   SDValue Ops[] = { Chain, In1, In2L, In2H };
13683   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13684   SDValue Result =
13685     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13686                             cast<MemSDNode>(Node)->getMemOperand());
13687   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13688   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13689   Results.push_back(Result.getValue(2));
13690 }
13691
13692 /// ReplaceNodeResults - Replace a node with an illegal result type
13693 /// with a new node built out of custom code.
13694 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13695                                            SmallVectorImpl<SDValue>&Results,
13696                                            SelectionDAG &DAG) const {
13697   SDLoc dl(N);
13698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13699   switch (N->getOpcode()) {
13700   default:
13701     llvm_unreachable("Do not know how to custom type legalize this operation!");
13702   case ISD::SIGN_EXTEND_INREG:
13703   case ISD::ADDC:
13704   case ISD::ADDE:
13705   case ISD::SUBC:
13706   case ISD::SUBE:
13707     // We don't want to expand or promote these.
13708     return;
13709   case ISD::FP_TO_SINT:
13710   case ISD::FP_TO_UINT: {
13711     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13712
13713     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13714       return;
13715
13716     std::pair<SDValue,SDValue> Vals =
13717         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13718     SDValue FIST = Vals.first, StackSlot = Vals.second;
13719     if (FIST.getNode() != 0) {
13720       EVT VT = N->getValueType(0);
13721       // Return a load from the stack slot.
13722       if (StackSlot.getNode() != 0)
13723         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13724                                       MachinePointerInfo(),
13725                                       false, false, false, 0));
13726       else
13727         Results.push_back(FIST);
13728     }
13729     return;
13730   }
13731   case ISD::UINT_TO_FP: {
13732     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13733     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13734         N->getValueType(0) != MVT::v2f32)
13735       return;
13736     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13737                                  N->getOperand(0));
13738     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13739                                      MVT::f64);
13740     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13741     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13742                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13743     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13744     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13745     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13746     return;
13747   }
13748   case ISD::FP_ROUND: {
13749     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13750         return;
13751     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13752     Results.push_back(V);
13753     return;
13754   }
13755   case ISD::READCYCLECOUNTER: {
13756     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13757     SDValue TheChain = N->getOperand(0);
13758     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13759     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13760                                      rd.getValue(1));
13761     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13762                                      eax.getValue(2));
13763     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13764     SDValue Ops[] = { eax, edx };
13765     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13766                                   array_lengthof(Ops)));
13767     Results.push_back(edx.getValue(1));
13768     return;
13769   }
13770   case ISD::ATOMIC_CMP_SWAP: {
13771     EVT T = N->getValueType(0);
13772     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13773     bool Regs64bit = T == MVT::i128;
13774     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13775     SDValue cpInL, cpInH;
13776     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13777                         DAG.getConstant(0, HalfT));
13778     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13779                         DAG.getConstant(1, HalfT));
13780     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13781                              Regs64bit ? X86::RAX : X86::EAX,
13782                              cpInL, SDValue());
13783     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13784                              Regs64bit ? X86::RDX : X86::EDX,
13785                              cpInH, cpInL.getValue(1));
13786     SDValue swapInL, swapInH;
13787     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13788                           DAG.getConstant(0, HalfT));
13789     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13790                           DAG.getConstant(1, HalfT));
13791     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13792                                Regs64bit ? X86::RBX : X86::EBX,
13793                                swapInL, cpInH.getValue(1));
13794     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13795                                Regs64bit ? X86::RCX : X86::ECX,
13796                                swapInH, swapInL.getValue(1));
13797     SDValue Ops[] = { swapInH.getValue(0),
13798                       N->getOperand(1),
13799                       swapInH.getValue(1) };
13800     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13801     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13802     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13803                                   X86ISD::LCMPXCHG8_DAG;
13804     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13805                                              Ops, array_lengthof(Ops), T, MMO);
13806     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13807                                         Regs64bit ? X86::RAX : X86::EAX,
13808                                         HalfT, Result.getValue(1));
13809     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13810                                         Regs64bit ? X86::RDX : X86::EDX,
13811                                         HalfT, cpOutL.getValue(2));
13812     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13813     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13814     Results.push_back(cpOutH.getValue(1));
13815     return;
13816   }
13817   case ISD::ATOMIC_LOAD_ADD:
13818   case ISD::ATOMIC_LOAD_AND:
13819   case ISD::ATOMIC_LOAD_NAND:
13820   case ISD::ATOMIC_LOAD_OR:
13821   case ISD::ATOMIC_LOAD_SUB:
13822   case ISD::ATOMIC_LOAD_XOR:
13823   case ISD::ATOMIC_LOAD_MAX:
13824   case ISD::ATOMIC_LOAD_MIN:
13825   case ISD::ATOMIC_LOAD_UMAX:
13826   case ISD::ATOMIC_LOAD_UMIN:
13827   case ISD::ATOMIC_SWAP: {
13828     unsigned Opc;
13829     switch (N->getOpcode()) {
13830     default: llvm_unreachable("Unexpected opcode");
13831     case ISD::ATOMIC_LOAD_ADD:
13832       Opc = X86ISD::ATOMADD64_DAG;
13833       break;
13834     case ISD::ATOMIC_LOAD_AND:
13835       Opc = X86ISD::ATOMAND64_DAG;
13836       break;
13837     case ISD::ATOMIC_LOAD_NAND:
13838       Opc = X86ISD::ATOMNAND64_DAG;
13839       break;
13840     case ISD::ATOMIC_LOAD_OR:
13841       Opc = X86ISD::ATOMOR64_DAG;
13842       break;
13843     case ISD::ATOMIC_LOAD_SUB:
13844       Opc = X86ISD::ATOMSUB64_DAG;
13845       break;
13846     case ISD::ATOMIC_LOAD_XOR:
13847       Opc = X86ISD::ATOMXOR64_DAG;
13848       break;
13849     case ISD::ATOMIC_LOAD_MAX:
13850       Opc = X86ISD::ATOMMAX64_DAG;
13851       break;
13852     case ISD::ATOMIC_LOAD_MIN:
13853       Opc = X86ISD::ATOMMIN64_DAG;
13854       break;
13855     case ISD::ATOMIC_LOAD_UMAX:
13856       Opc = X86ISD::ATOMUMAX64_DAG;
13857       break;
13858     case ISD::ATOMIC_LOAD_UMIN:
13859       Opc = X86ISD::ATOMUMIN64_DAG;
13860       break;
13861     case ISD::ATOMIC_SWAP:
13862       Opc = X86ISD::ATOMSWAP64_DAG;
13863       break;
13864     }
13865     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13866     return;
13867   }
13868   case ISD::ATOMIC_LOAD:
13869     ReplaceATOMIC_LOAD(N, Results, DAG);
13870   }
13871 }
13872
13873 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13874   switch (Opcode) {
13875   default: return NULL;
13876   case X86ISD::BSF:                return "X86ISD::BSF";
13877   case X86ISD::BSR:                return "X86ISD::BSR";
13878   case X86ISD::SHLD:               return "X86ISD::SHLD";
13879   case X86ISD::SHRD:               return "X86ISD::SHRD";
13880   case X86ISD::FAND:               return "X86ISD::FAND";
13881   case X86ISD::FANDN:              return "X86ISD::FANDN";
13882   case X86ISD::FOR:                return "X86ISD::FOR";
13883   case X86ISD::FXOR:               return "X86ISD::FXOR";
13884   case X86ISD::FSRL:               return "X86ISD::FSRL";
13885   case X86ISD::FILD:               return "X86ISD::FILD";
13886   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13887   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13888   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13889   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13890   case X86ISD::FLD:                return "X86ISD::FLD";
13891   case X86ISD::FST:                return "X86ISD::FST";
13892   case X86ISD::CALL:               return "X86ISD::CALL";
13893   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13894   case X86ISD::BT:                 return "X86ISD::BT";
13895   case X86ISD::CMP:                return "X86ISD::CMP";
13896   case X86ISD::COMI:               return "X86ISD::COMI";
13897   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13898   case X86ISD::CMPM:               return "X86ISD::CMPM";
13899   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13900   case X86ISD::SETCC:              return "X86ISD::SETCC";
13901   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13902   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
13903   case X86ISD::CMOV:               return "X86ISD::CMOV";
13904   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13905   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13906   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13907   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13908   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13909   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13910   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13911   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13912   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13913   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13914   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13915   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13916   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13917   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13918   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13919   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13920   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13921   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13922   case X86ISD::HADD:               return "X86ISD::HADD";
13923   case X86ISD::HSUB:               return "X86ISD::HSUB";
13924   case X86ISD::FHADD:              return "X86ISD::FHADD";
13925   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13926   case X86ISD::UMAX:               return "X86ISD::UMAX";
13927   case X86ISD::UMIN:               return "X86ISD::UMIN";
13928   case X86ISD::SMAX:               return "X86ISD::SMAX";
13929   case X86ISD::SMIN:               return "X86ISD::SMIN";
13930   case X86ISD::FMAX:               return "X86ISD::FMAX";
13931   case X86ISD::FMIN:               return "X86ISD::FMIN";
13932   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13933   case X86ISD::FMINC:              return "X86ISD::FMINC";
13934   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13935   case X86ISD::FRCP:               return "X86ISD::FRCP";
13936   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13937   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13938   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13939   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13940   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13941   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13942   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13943   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13944   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13945   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13946   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13947   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13948   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13949   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13950   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13951   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13952   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13953   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13954   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13955   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13956   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13957   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13958   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
13959   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
13960   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
13961   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13962   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13963   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13964   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13965   case X86ISD::VSHL:               return "X86ISD::VSHL";
13966   case X86ISD::VSRL:               return "X86ISD::VSRL";
13967   case X86ISD::VSRA:               return "X86ISD::VSRA";
13968   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13969   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13970   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13971   case X86ISD::CMPP:               return "X86ISD::CMPP";
13972   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13973   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13974   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
13975   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
13976   case X86ISD::ADD:                return "X86ISD::ADD";
13977   case X86ISD::SUB:                return "X86ISD::SUB";
13978   case X86ISD::ADC:                return "X86ISD::ADC";
13979   case X86ISD::SBB:                return "X86ISD::SBB";
13980   case X86ISD::SMUL:               return "X86ISD::SMUL";
13981   case X86ISD::UMUL:               return "X86ISD::UMUL";
13982   case X86ISD::INC:                return "X86ISD::INC";
13983   case X86ISD::DEC:                return "X86ISD::DEC";
13984   case X86ISD::OR:                 return "X86ISD::OR";
13985   case X86ISD::XOR:                return "X86ISD::XOR";
13986   case X86ISD::AND:                return "X86ISD::AND";
13987   case X86ISD::BLSI:               return "X86ISD::BLSI";
13988   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13989   case X86ISD::BLSR:               return "X86ISD::BLSR";
13990   case X86ISD::BZHI:               return "X86ISD::BZHI";
13991   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
13992   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13993   case X86ISD::PTEST:              return "X86ISD::PTEST";
13994   case X86ISD::TESTP:              return "X86ISD::TESTP";
13995   case X86ISD::TESTM:              return "X86ISD::TESTM";
13996   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
13997   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13998   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13999   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14000   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14001   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14002   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14003   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14004   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14005   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14006   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14007   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14008   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14009   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14010   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14011   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14012   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14013   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14014   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14015   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14016   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14017   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14018   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14019   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14020   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14021   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14022   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14023   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14024   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14025   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14026   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14027   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14028   case X86ISD::SAHF:               return "X86ISD::SAHF";
14029   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14030   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14031   case X86ISD::FMADD:              return "X86ISD::FMADD";
14032   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14033   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14034   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14035   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14036   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14037   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14038   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14039   case X86ISD::XTEST:              return "X86ISD::XTEST";
14040   }
14041 }
14042
14043 // isLegalAddressingMode - Return true if the addressing mode represented
14044 // by AM is legal for this target, for a load/store of the specified type.
14045 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14046                                               Type *Ty) const {
14047   // X86 supports extremely general addressing modes.
14048   CodeModel::Model M = getTargetMachine().getCodeModel();
14049   Reloc::Model R = getTargetMachine().getRelocationModel();
14050
14051   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14052   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
14053     return false;
14054
14055   if (AM.BaseGV) {
14056     unsigned GVFlags =
14057       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14058
14059     // If a reference to this global requires an extra load, we can't fold it.
14060     if (isGlobalStubReference(GVFlags))
14061       return false;
14062
14063     // If BaseGV requires a register for the PIC base, we cannot also have a
14064     // BaseReg specified.
14065     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14066       return false;
14067
14068     // If lower 4G is not available, then we must use rip-relative addressing.
14069     if ((M != CodeModel::Small || R != Reloc::Static) &&
14070         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14071       return false;
14072   }
14073
14074   switch (AM.Scale) {
14075   case 0:
14076   case 1:
14077   case 2:
14078   case 4:
14079   case 8:
14080     // These scales always work.
14081     break;
14082   case 3:
14083   case 5:
14084   case 9:
14085     // These scales are formed with basereg+scalereg.  Only accept if there is
14086     // no basereg yet.
14087     if (AM.HasBaseReg)
14088       return false;
14089     break;
14090   default:  // Other stuff never works.
14091     return false;
14092   }
14093
14094   return true;
14095 }
14096
14097 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14098   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14099     return false;
14100   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14101   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14102   return NumBits1 > NumBits2;
14103 }
14104
14105 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14106   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14107     return false;
14108
14109   if (!isTypeLegal(EVT::getEVT(Ty1)))
14110     return false;
14111
14112   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14113
14114   // Assuming the caller doesn't have a zeroext or signext return parameter,
14115   // truncation all the way down to i1 is valid.
14116   return true;
14117 }
14118
14119 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14120   return isInt<32>(Imm);
14121 }
14122
14123 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14124   // Can also use sub to handle negated immediates.
14125   return isInt<32>(Imm);
14126 }
14127
14128 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14129   if (!VT1.isInteger() || !VT2.isInteger())
14130     return false;
14131   unsigned NumBits1 = VT1.getSizeInBits();
14132   unsigned NumBits2 = VT2.getSizeInBits();
14133   return NumBits1 > NumBits2;
14134 }
14135
14136 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14137   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14138   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14139 }
14140
14141 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14142   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14143   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14144 }
14145
14146 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14147   EVT VT1 = Val.getValueType();
14148   if (isZExtFree(VT1, VT2))
14149     return true;
14150
14151   if (Val.getOpcode() != ISD::LOAD)
14152     return false;
14153
14154   if (!VT1.isSimple() || !VT1.isInteger() ||
14155       !VT2.isSimple() || !VT2.isInteger())
14156     return false;
14157
14158   switch (VT1.getSimpleVT().SimpleTy) {
14159   default: break;
14160   case MVT::i8:
14161   case MVT::i16:
14162   case MVT::i32:
14163     // X86 has 8, 16, and 32-bit zero-extending loads.
14164     return true;
14165   }
14166
14167   return false;
14168 }
14169
14170 bool
14171 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14172   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14173     return false;
14174
14175   VT = VT.getScalarType();
14176
14177   if (!VT.isSimple())
14178     return false;
14179
14180   switch (VT.getSimpleVT().SimpleTy) {
14181   case MVT::f32:
14182   case MVT::f64:
14183     return true;
14184   default:
14185     break;
14186   }
14187
14188   return false;
14189 }
14190
14191 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14192   // i16 instructions are longer (0x66 prefix) and potentially slower.
14193   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14194 }
14195
14196 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14197 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14198 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14199 /// are assumed to be legal.
14200 bool
14201 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14202                                       EVT VT) const {
14203   if (!VT.isSimple())
14204     return false;
14205
14206   MVT SVT = VT.getSimpleVT();
14207
14208   // Very little shuffling can be done for 64-bit vectors right now.
14209   if (VT.getSizeInBits() == 64)
14210     return false;
14211
14212   // FIXME: pshufb, blends, shifts.
14213   return (SVT.getVectorNumElements() == 2 ||
14214           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14215           isMOVLMask(M, SVT) ||
14216           isSHUFPMask(M, SVT) ||
14217           isPSHUFDMask(M, SVT) ||
14218           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14219           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14220           isPALIGNRMask(M, SVT, Subtarget) ||
14221           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14222           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14223           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14224           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14225 }
14226
14227 bool
14228 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14229                                           EVT VT) const {
14230   if (!VT.isSimple())
14231     return false;
14232
14233   MVT SVT = VT.getSimpleVT();
14234   unsigned NumElts = SVT.getVectorNumElements();
14235   // FIXME: This collection of masks seems suspect.
14236   if (NumElts == 2)
14237     return true;
14238   if (NumElts == 4 && SVT.is128BitVector()) {
14239     return (isMOVLMask(Mask, SVT)  ||
14240             isCommutedMOVLMask(Mask, SVT, true) ||
14241             isSHUFPMask(Mask, SVT) ||
14242             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14243   }
14244   return false;
14245 }
14246
14247 //===----------------------------------------------------------------------===//
14248 //                           X86 Scheduler Hooks
14249 //===----------------------------------------------------------------------===//
14250
14251 /// Utility function to emit xbegin specifying the start of an RTM region.
14252 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14253                                      const TargetInstrInfo *TII) {
14254   DebugLoc DL = MI->getDebugLoc();
14255
14256   const BasicBlock *BB = MBB->getBasicBlock();
14257   MachineFunction::iterator I = MBB;
14258   ++I;
14259
14260   // For the v = xbegin(), we generate
14261   //
14262   // thisMBB:
14263   //  xbegin sinkMBB
14264   //
14265   // mainMBB:
14266   //  eax = -1
14267   //
14268   // sinkMBB:
14269   //  v = eax
14270
14271   MachineBasicBlock *thisMBB = MBB;
14272   MachineFunction *MF = MBB->getParent();
14273   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14274   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14275   MF->insert(I, mainMBB);
14276   MF->insert(I, sinkMBB);
14277
14278   // Transfer the remainder of BB and its successor edges to sinkMBB.
14279   sinkMBB->splice(sinkMBB->begin(), MBB,
14280                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14281   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14282
14283   // thisMBB:
14284   //  xbegin sinkMBB
14285   //  # fallthrough to mainMBB
14286   //  # abortion to sinkMBB
14287   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14288   thisMBB->addSuccessor(mainMBB);
14289   thisMBB->addSuccessor(sinkMBB);
14290
14291   // mainMBB:
14292   //  EAX = -1
14293   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14294   mainMBB->addSuccessor(sinkMBB);
14295
14296   // sinkMBB:
14297   // EAX is live into the sinkMBB
14298   sinkMBB->addLiveIn(X86::EAX);
14299   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14300           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14301     .addReg(X86::EAX);
14302
14303   MI->eraseFromParent();
14304   return sinkMBB;
14305 }
14306
14307 // Get CMPXCHG opcode for the specified data type.
14308 static unsigned getCmpXChgOpcode(EVT VT) {
14309   switch (VT.getSimpleVT().SimpleTy) {
14310   case MVT::i8:  return X86::LCMPXCHG8;
14311   case MVT::i16: return X86::LCMPXCHG16;
14312   case MVT::i32: return X86::LCMPXCHG32;
14313   case MVT::i64: return X86::LCMPXCHG64;
14314   default:
14315     break;
14316   }
14317   llvm_unreachable("Invalid operand size!");
14318 }
14319
14320 // Get LOAD opcode for the specified data type.
14321 static unsigned getLoadOpcode(EVT VT) {
14322   switch (VT.getSimpleVT().SimpleTy) {
14323   case MVT::i8:  return X86::MOV8rm;
14324   case MVT::i16: return X86::MOV16rm;
14325   case MVT::i32: return X86::MOV32rm;
14326   case MVT::i64: return X86::MOV64rm;
14327   default:
14328     break;
14329   }
14330   llvm_unreachable("Invalid operand size!");
14331 }
14332
14333 // Get opcode of the non-atomic one from the specified atomic instruction.
14334 static unsigned getNonAtomicOpcode(unsigned Opc) {
14335   switch (Opc) {
14336   case X86::ATOMAND8:  return X86::AND8rr;
14337   case X86::ATOMAND16: return X86::AND16rr;
14338   case X86::ATOMAND32: return X86::AND32rr;
14339   case X86::ATOMAND64: return X86::AND64rr;
14340   case X86::ATOMOR8:   return X86::OR8rr;
14341   case X86::ATOMOR16:  return X86::OR16rr;
14342   case X86::ATOMOR32:  return X86::OR32rr;
14343   case X86::ATOMOR64:  return X86::OR64rr;
14344   case X86::ATOMXOR8:  return X86::XOR8rr;
14345   case X86::ATOMXOR16: return X86::XOR16rr;
14346   case X86::ATOMXOR32: return X86::XOR32rr;
14347   case X86::ATOMXOR64: return X86::XOR64rr;
14348   }
14349   llvm_unreachable("Unhandled atomic-load-op opcode!");
14350 }
14351
14352 // Get opcode of the non-atomic one from the specified atomic instruction with
14353 // extra opcode.
14354 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14355                                                unsigned &ExtraOpc) {
14356   switch (Opc) {
14357   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14358   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14359   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14360   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14361   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14362   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14363   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14364   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14365   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14366   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14367   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14368   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14369   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14370   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14371   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14372   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14373   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14374   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14375   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14376   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14377   }
14378   llvm_unreachable("Unhandled atomic-load-op opcode!");
14379 }
14380
14381 // Get opcode of the non-atomic one from the specified atomic instruction for
14382 // 64-bit data type on 32-bit target.
14383 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14384   switch (Opc) {
14385   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14386   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14387   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14388   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14389   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14390   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14391   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14392   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14393   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14394   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14395   }
14396   llvm_unreachable("Unhandled atomic-load-op opcode!");
14397 }
14398
14399 // Get opcode of the non-atomic one from the specified atomic instruction for
14400 // 64-bit data type on 32-bit target with extra opcode.
14401 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14402                                                    unsigned &HiOpc,
14403                                                    unsigned &ExtraOpc) {
14404   switch (Opc) {
14405   case X86::ATOMNAND6432:
14406     ExtraOpc = X86::NOT32r;
14407     HiOpc = X86::AND32rr;
14408     return X86::AND32rr;
14409   }
14410   llvm_unreachable("Unhandled atomic-load-op opcode!");
14411 }
14412
14413 // Get pseudo CMOV opcode from the specified data type.
14414 static unsigned getPseudoCMOVOpc(EVT VT) {
14415   switch (VT.getSimpleVT().SimpleTy) {
14416   case MVT::i8:  return X86::CMOV_GR8;
14417   case MVT::i16: return X86::CMOV_GR16;
14418   case MVT::i32: return X86::CMOV_GR32;
14419   default:
14420     break;
14421   }
14422   llvm_unreachable("Unknown CMOV opcode!");
14423 }
14424
14425 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14426 // They will be translated into a spin-loop or compare-exchange loop from
14427 //
14428 //    ...
14429 //    dst = atomic-fetch-op MI.addr, MI.val
14430 //    ...
14431 //
14432 // to
14433 //
14434 //    ...
14435 //    t1 = LOAD MI.addr
14436 // loop:
14437 //    t4 = phi(t1, t3 / loop)
14438 //    t2 = OP MI.val, t4
14439 //    EAX = t4
14440 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
14441 //    t3 = EAX
14442 //    JNE loop
14443 // sink:
14444 //    dst = t3
14445 //    ...
14446 MachineBasicBlock *
14447 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
14448                                        MachineBasicBlock *MBB) const {
14449   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14450   DebugLoc DL = MI->getDebugLoc();
14451
14452   MachineFunction *MF = MBB->getParent();
14453   MachineRegisterInfo &MRI = MF->getRegInfo();
14454
14455   const BasicBlock *BB = MBB->getBasicBlock();
14456   MachineFunction::iterator I = MBB;
14457   ++I;
14458
14459   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
14460          "Unexpected number of operands");
14461
14462   assert(MI->hasOneMemOperand() &&
14463          "Expected atomic-load-op to have one memoperand");
14464
14465   // Memory Reference
14466   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14467   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14468
14469   unsigned DstReg, SrcReg;
14470   unsigned MemOpndSlot;
14471
14472   unsigned CurOp = 0;
14473
14474   DstReg = MI->getOperand(CurOp++).getReg();
14475   MemOpndSlot = CurOp;
14476   CurOp += X86::AddrNumOperands;
14477   SrcReg = MI->getOperand(CurOp++).getReg();
14478
14479   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14480   MVT::SimpleValueType VT = *RC->vt_begin();
14481   unsigned t1 = MRI.createVirtualRegister(RC);
14482   unsigned t2 = MRI.createVirtualRegister(RC);
14483   unsigned t3 = MRI.createVirtualRegister(RC);
14484   unsigned t4 = MRI.createVirtualRegister(RC);
14485   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
14486
14487   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
14488   unsigned LOADOpc = getLoadOpcode(VT);
14489
14490   // For the atomic load-arith operator, we generate
14491   //
14492   //  thisMBB:
14493   //    t1 = LOAD [MI.addr]
14494   //  mainMBB:
14495   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
14496   //    t1 = OP MI.val, EAX
14497   //    EAX = t4
14498   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
14499   //    t3 = EAX
14500   //    JNE mainMBB
14501   //  sinkMBB:
14502   //    dst = t3
14503
14504   MachineBasicBlock *thisMBB = MBB;
14505   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14506   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14507   MF->insert(I, mainMBB);
14508   MF->insert(I, sinkMBB);
14509
14510   MachineInstrBuilder MIB;
14511
14512   // Transfer the remainder of BB and its successor edges to sinkMBB.
14513   sinkMBB->splice(sinkMBB->begin(), MBB,
14514                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14515   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14516
14517   // thisMBB:
14518   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
14519   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14520     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14521     if (NewMO.isReg())
14522       NewMO.setIsKill(false);
14523     MIB.addOperand(NewMO);
14524   }
14525   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14526     unsigned flags = (*MMOI)->getFlags();
14527     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14528     MachineMemOperand *MMO =
14529       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14530                                (*MMOI)->getSize(),
14531                                (*MMOI)->getBaseAlignment(),
14532                                (*MMOI)->getTBAAInfo(),
14533                                (*MMOI)->getRanges());
14534     MIB.addMemOperand(MMO);
14535   }
14536
14537   thisMBB->addSuccessor(mainMBB);
14538
14539   // mainMBB:
14540   MachineBasicBlock *origMainMBB = mainMBB;
14541
14542   // Add a PHI.
14543   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
14544                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14545
14546   unsigned Opc = MI->getOpcode();
14547   switch (Opc) {
14548   default:
14549     llvm_unreachable("Unhandled atomic-load-op opcode!");
14550   case X86::ATOMAND8:
14551   case X86::ATOMAND16:
14552   case X86::ATOMAND32:
14553   case X86::ATOMAND64:
14554   case X86::ATOMOR8:
14555   case X86::ATOMOR16:
14556   case X86::ATOMOR32:
14557   case X86::ATOMOR64:
14558   case X86::ATOMXOR8:
14559   case X86::ATOMXOR16:
14560   case X86::ATOMXOR32:
14561   case X86::ATOMXOR64: {
14562     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
14563     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
14564       .addReg(t4);
14565     break;
14566   }
14567   case X86::ATOMNAND8:
14568   case X86::ATOMNAND16:
14569   case X86::ATOMNAND32:
14570   case X86::ATOMNAND64: {
14571     unsigned Tmp = MRI.createVirtualRegister(RC);
14572     unsigned NOTOpc;
14573     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
14574     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
14575       .addReg(t4);
14576     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
14577     break;
14578   }
14579   case X86::ATOMMAX8:
14580   case X86::ATOMMAX16:
14581   case X86::ATOMMAX32:
14582   case X86::ATOMMAX64:
14583   case X86::ATOMMIN8:
14584   case X86::ATOMMIN16:
14585   case X86::ATOMMIN32:
14586   case X86::ATOMMIN64:
14587   case X86::ATOMUMAX8:
14588   case X86::ATOMUMAX16:
14589   case X86::ATOMUMAX32:
14590   case X86::ATOMUMAX64:
14591   case X86::ATOMUMIN8:
14592   case X86::ATOMUMIN16:
14593   case X86::ATOMUMIN32:
14594   case X86::ATOMUMIN64: {
14595     unsigned CMPOpc;
14596     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
14597
14598     BuildMI(mainMBB, DL, TII->get(CMPOpc))
14599       .addReg(SrcReg)
14600       .addReg(t4);
14601
14602     if (Subtarget->hasCMov()) {
14603       if (VT != MVT::i8) {
14604         // Native support
14605         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
14606           .addReg(SrcReg)
14607           .addReg(t4);
14608       } else {
14609         // Promote i8 to i32 to use CMOV32
14610         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14611         const TargetRegisterClass *RC32 =
14612           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
14613         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
14614         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
14615         unsigned Tmp = MRI.createVirtualRegister(RC32);
14616
14617         unsigned Undef = MRI.createVirtualRegister(RC32);
14618         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
14619
14620         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
14621           .addReg(Undef)
14622           .addReg(SrcReg)
14623           .addImm(X86::sub_8bit);
14624         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
14625           .addReg(Undef)
14626           .addReg(t4)
14627           .addImm(X86::sub_8bit);
14628
14629         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
14630           .addReg(SrcReg32)
14631           .addReg(AccReg32);
14632
14633         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
14634           .addReg(Tmp, 0, X86::sub_8bit);
14635       }
14636     } else {
14637       // Use pseudo select and lower them.
14638       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14639              "Invalid atomic-load-op transformation!");
14640       unsigned SelOpc = getPseudoCMOVOpc(VT);
14641       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14642       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14643       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14644               .addReg(SrcReg).addReg(t4)
14645               .addImm(CC);
14646       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14647       // Replace the original PHI node as mainMBB is changed after CMOV
14648       // lowering.
14649       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14650         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14651       Phi->eraseFromParent();
14652     }
14653     break;
14654   }
14655   }
14656
14657   // Copy PhyReg back from virtual register.
14658   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14659     .addReg(t4);
14660
14661   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14662   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14663     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14664     if (NewMO.isReg())
14665       NewMO.setIsKill(false);
14666     MIB.addOperand(NewMO);
14667   }
14668   MIB.addReg(t2);
14669   MIB.setMemRefs(MMOBegin, MMOEnd);
14670
14671   // Copy PhyReg back to virtual register.
14672   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14673     .addReg(PhyReg);
14674
14675   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14676
14677   mainMBB->addSuccessor(origMainMBB);
14678   mainMBB->addSuccessor(sinkMBB);
14679
14680   // sinkMBB:
14681   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14682           TII->get(TargetOpcode::COPY), DstReg)
14683     .addReg(t3);
14684
14685   MI->eraseFromParent();
14686   return sinkMBB;
14687 }
14688
14689 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14690 // instructions. They will be translated into a spin-loop or compare-exchange
14691 // loop from
14692 //
14693 //    ...
14694 //    dst = atomic-fetch-op MI.addr, MI.val
14695 //    ...
14696 //
14697 // to
14698 //
14699 //    ...
14700 //    t1L = LOAD [MI.addr + 0]
14701 //    t1H = LOAD [MI.addr + 4]
14702 // loop:
14703 //    t4L = phi(t1L, t3L / loop)
14704 //    t4H = phi(t1H, t3H / loop)
14705 //    t2L = OP MI.val.lo, t4L
14706 //    t2H = OP MI.val.hi, t4H
14707 //    EAX = t4L
14708 //    EDX = t4H
14709 //    EBX = t2L
14710 //    ECX = t2H
14711 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14712 //    t3L = EAX
14713 //    t3H = EDX
14714 //    JNE loop
14715 // sink:
14716 //    dstL = t3L
14717 //    dstH = t3H
14718 //    ...
14719 MachineBasicBlock *
14720 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14721                                            MachineBasicBlock *MBB) const {
14722   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14723   DebugLoc DL = MI->getDebugLoc();
14724
14725   MachineFunction *MF = MBB->getParent();
14726   MachineRegisterInfo &MRI = MF->getRegInfo();
14727
14728   const BasicBlock *BB = MBB->getBasicBlock();
14729   MachineFunction::iterator I = MBB;
14730   ++I;
14731
14732   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14733          "Unexpected number of operands");
14734
14735   assert(MI->hasOneMemOperand() &&
14736          "Expected atomic-load-op32 to have one memoperand");
14737
14738   // Memory Reference
14739   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14740   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14741
14742   unsigned DstLoReg, DstHiReg;
14743   unsigned SrcLoReg, SrcHiReg;
14744   unsigned MemOpndSlot;
14745
14746   unsigned CurOp = 0;
14747
14748   DstLoReg = MI->getOperand(CurOp++).getReg();
14749   DstHiReg = MI->getOperand(CurOp++).getReg();
14750   MemOpndSlot = CurOp;
14751   CurOp += X86::AddrNumOperands;
14752   SrcLoReg = MI->getOperand(CurOp++).getReg();
14753   SrcHiReg = MI->getOperand(CurOp++).getReg();
14754
14755   const TargetRegisterClass *RC = &X86::GR32RegClass;
14756   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14757
14758   unsigned t1L = MRI.createVirtualRegister(RC);
14759   unsigned t1H = MRI.createVirtualRegister(RC);
14760   unsigned t2L = MRI.createVirtualRegister(RC);
14761   unsigned t2H = MRI.createVirtualRegister(RC);
14762   unsigned t3L = MRI.createVirtualRegister(RC);
14763   unsigned t3H = MRI.createVirtualRegister(RC);
14764   unsigned t4L = MRI.createVirtualRegister(RC);
14765   unsigned t4H = MRI.createVirtualRegister(RC);
14766
14767   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14768   unsigned LOADOpc = X86::MOV32rm;
14769
14770   // For the atomic load-arith operator, we generate
14771   //
14772   //  thisMBB:
14773   //    t1L = LOAD [MI.addr + 0]
14774   //    t1H = LOAD [MI.addr + 4]
14775   //  mainMBB:
14776   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14777   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14778   //    t2L = OP MI.val.lo, t4L
14779   //    t2H = OP MI.val.hi, t4H
14780   //    EBX = t2L
14781   //    ECX = t2H
14782   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14783   //    t3L = EAX
14784   //    t3H = EDX
14785   //    JNE loop
14786   //  sinkMBB:
14787   //    dstL = t3L
14788   //    dstH = t3H
14789
14790   MachineBasicBlock *thisMBB = MBB;
14791   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14792   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14793   MF->insert(I, mainMBB);
14794   MF->insert(I, sinkMBB);
14795
14796   MachineInstrBuilder MIB;
14797
14798   // Transfer the remainder of BB and its successor edges to sinkMBB.
14799   sinkMBB->splice(sinkMBB->begin(), MBB,
14800                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14801   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14802
14803   // thisMBB:
14804   // Lo
14805   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14806   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14807     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14808     if (NewMO.isReg())
14809       NewMO.setIsKill(false);
14810     MIB.addOperand(NewMO);
14811   }
14812   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14813     unsigned flags = (*MMOI)->getFlags();
14814     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14815     MachineMemOperand *MMO =
14816       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14817                                (*MMOI)->getSize(),
14818                                (*MMOI)->getBaseAlignment(),
14819                                (*MMOI)->getTBAAInfo(),
14820                                (*MMOI)->getRanges());
14821     MIB.addMemOperand(MMO);
14822   };
14823   MachineInstr *LowMI = MIB;
14824
14825   // Hi
14826   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14827   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14828     if (i == X86::AddrDisp) {
14829       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14830     } else {
14831       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14832       if (NewMO.isReg())
14833         NewMO.setIsKill(false);
14834       MIB.addOperand(NewMO);
14835     }
14836   }
14837   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14838
14839   thisMBB->addSuccessor(mainMBB);
14840
14841   // mainMBB:
14842   MachineBasicBlock *origMainMBB = mainMBB;
14843
14844   // Add PHIs.
14845   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14846                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14847   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14848                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14849
14850   unsigned Opc = MI->getOpcode();
14851   switch (Opc) {
14852   default:
14853     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14854   case X86::ATOMAND6432:
14855   case X86::ATOMOR6432:
14856   case X86::ATOMXOR6432:
14857   case X86::ATOMADD6432:
14858   case X86::ATOMSUB6432: {
14859     unsigned HiOpc;
14860     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14861     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14862       .addReg(SrcLoReg);
14863     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14864       .addReg(SrcHiReg);
14865     break;
14866   }
14867   case X86::ATOMNAND6432: {
14868     unsigned HiOpc, NOTOpc;
14869     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14870     unsigned TmpL = MRI.createVirtualRegister(RC);
14871     unsigned TmpH = MRI.createVirtualRegister(RC);
14872     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14873       .addReg(t4L);
14874     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14875       .addReg(t4H);
14876     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14877     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14878     break;
14879   }
14880   case X86::ATOMMAX6432:
14881   case X86::ATOMMIN6432:
14882   case X86::ATOMUMAX6432:
14883   case X86::ATOMUMIN6432: {
14884     unsigned HiOpc;
14885     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14886     unsigned cL = MRI.createVirtualRegister(RC8);
14887     unsigned cH = MRI.createVirtualRegister(RC8);
14888     unsigned cL32 = MRI.createVirtualRegister(RC);
14889     unsigned cH32 = MRI.createVirtualRegister(RC);
14890     unsigned cc = MRI.createVirtualRegister(RC);
14891     // cl := cmp src_lo, lo
14892     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14893       .addReg(SrcLoReg).addReg(t4L);
14894     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14895     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14896     // ch := cmp src_hi, hi
14897     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14898       .addReg(SrcHiReg).addReg(t4H);
14899     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14900     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14901     // cc := if (src_hi == hi) ? cl : ch;
14902     if (Subtarget->hasCMov()) {
14903       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14904         .addReg(cH32).addReg(cL32);
14905     } else {
14906       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14907               .addReg(cH32).addReg(cL32)
14908               .addImm(X86::COND_E);
14909       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14910     }
14911     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14912     if (Subtarget->hasCMov()) {
14913       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14914         .addReg(SrcLoReg).addReg(t4L);
14915       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14916         .addReg(SrcHiReg).addReg(t4H);
14917     } else {
14918       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14919               .addReg(SrcLoReg).addReg(t4L)
14920               .addImm(X86::COND_NE);
14921       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14922       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14923       // 2nd CMOV lowering.
14924       mainMBB->addLiveIn(X86::EFLAGS);
14925       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14926               .addReg(SrcHiReg).addReg(t4H)
14927               .addImm(X86::COND_NE);
14928       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14929       // Replace the original PHI node as mainMBB is changed after CMOV
14930       // lowering.
14931       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14932         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14933       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14934         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14935       PhiL->eraseFromParent();
14936       PhiH->eraseFromParent();
14937     }
14938     break;
14939   }
14940   case X86::ATOMSWAP6432: {
14941     unsigned HiOpc;
14942     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14943     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14944     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14945     break;
14946   }
14947   }
14948
14949   // Copy EDX:EAX back from HiReg:LoReg
14950   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14951   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14952   // Copy ECX:EBX from t1H:t1L
14953   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14954   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14955
14956   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14957   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14958     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14959     if (NewMO.isReg())
14960       NewMO.setIsKill(false);
14961     MIB.addOperand(NewMO);
14962   }
14963   MIB.setMemRefs(MMOBegin, MMOEnd);
14964
14965   // Copy EDX:EAX back to t3H:t3L
14966   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14967   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14968
14969   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14970
14971   mainMBB->addSuccessor(origMainMBB);
14972   mainMBB->addSuccessor(sinkMBB);
14973
14974   // sinkMBB:
14975   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14976           TII->get(TargetOpcode::COPY), DstLoReg)
14977     .addReg(t3L);
14978   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14979           TII->get(TargetOpcode::COPY), DstHiReg)
14980     .addReg(t3H);
14981
14982   MI->eraseFromParent();
14983   return sinkMBB;
14984 }
14985
14986 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14987 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14988 // in the .td file.
14989 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14990                                        const TargetInstrInfo *TII) {
14991   unsigned Opc;
14992   switch (MI->getOpcode()) {
14993   default: llvm_unreachable("illegal opcode!");
14994   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14995   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14996   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14997   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14998   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14999   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15000   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15001   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15002   }
15003
15004   DebugLoc dl = MI->getDebugLoc();
15005   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15006
15007   unsigned NumArgs = MI->getNumOperands();
15008   for (unsigned i = 1; i < NumArgs; ++i) {
15009     MachineOperand &Op = MI->getOperand(i);
15010     if (!(Op.isReg() && Op.isImplicit()))
15011       MIB.addOperand(Op);
15012   }
15013   if (MI->hasOneMemOperand())
15014     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15015
15016   BuildMI(*BB, MI, dl,
15017     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15018     .addReg(X86::XMM0);
15019
15020   MI->eraseFromParent();
15021   return BB;
15022 }
15023
15024 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15025 // defs in an instruction pattern
15026 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15027                                        const TargetInstrInfo *TII) {
15028   unsigned Opc;
15029   switch (MI->getOpcode()) {
15030   default: llvm_unreachable("illegal opcode!");
15031   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15032   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15033   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15034   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15035   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15036   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15037   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15038   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15039   }
15040
15041   DebugLoc dl = MI->getDebugLoc();
15042   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15043
15044   unsigned NumArgs = MI->getNumOperands(); // remove the results
15045   for (unsigned i = 1; i < NumArgs; ++i) {
15046     MachineOperand &Op = MI->getOperand(i);
15047     if (!(Op.isReg() && Op.isImplicit()))
15048       MIB.addOperand(Op);
15049   }
15050   if (MI->hasOneMemOperand())
15051     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15052
15053   BuildMI(*BB, MI, dl,
15054     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15055     .addReg(X86::ECX);
15056
15057   MI->eraseFromParent();
15058   return BB;
15059 }
15060
15061 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15062                                        const TargetInstrInfo *TII,
15063                                        const X86Subtarget* Subtarget) {
15064   DebugLoc dl = MI->getDebugLoc();
15065
15066   // Address into RAX/EAX, other two args into ECX, EDX.
15067   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15068   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15069   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15070   for (int i = 0; i < X86::AddrNumOperands; ++i)
15071     MIB.addOperand(MI->getOperand(i));
15072
15073   unsigned ValOps = X86::AddrNumOperands;
15074   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15075     .addReg(MI->getOperand(ValOps).getReg());
15076   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15077     .addReg(MI->getOperand(ValOps+1).getReg());
15078
15079   // The instruction doesn't actually take any operands though.
15080   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15081
15082   MI->eraseFromParent(); // The pseudo is gone now.
15083   return BB;
15084 }
15085
15086 MachineBasicBlock *
15087 X86TargetLowering::EmitVAARG64WithCustomInserter(
15088                    MachineInstr *MI,
15089                    MachineBasicBlock *MBB) const {
15090   // Emit va_arg instruction on X86-64.
15091
15092   // Operands to this pseudo-instruction:
15093   // 0  ) Output        : destination address (reg)
15094   // 1-5) Input         : va_list address (addr, i64mem)
15095   // 6  ) ArgSize       : Size (in bytes) of vararg type
15096   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15097   // 8  ) Align         : Alignment of type
15098   // 9  ) EFLAGS (implicit-def)
15099
15100   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15101   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15102
15103   unsigned DestReg = MI->getOperand(0).getReg();
15104   MachineOperand &Base = MI->getOperand(1);
15105   MachineOperand &Scale = MI->getOperand(2);
15106   MachineOperand &Index = MI->getOperand(3);
15107   MachineOperand &Disp = MI->getOperand(4);
15108   MachineOperand &Segment = MI->getOperand(5);
15109   unsigned ArgSize = MI->getOperand(6).getImm();
15110   unsigned ArgMode = MI->getOperand(7).getImm();
15111   unsigned Align = MI->getOperand(8).getImm();
15112
15113   // Memory Reference
15114   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15115   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15116   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15117
15118   // Machine Information
15119   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15120   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15121   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15122   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15123   DebugLoc DL = MI->getDebugLoc();
15124
15125   // struct va_list {
15126   //   i32   gp_offset
15127   //   i32   fp_offset
15128   //   i64   overflow_area (address)
15129   //   i64   reg_save_area (address)
15130   // }
15131   // sizeof(va_list) = 24
15132   // alignment(va_list) = 8
15133
15134   unsigned TotalNumIntRegs = 6;
15135   unsigned TotalNumXMMRegs = 8;
15136   bool UseGPOffset = (ArgMode == 1);
15137   bool UseFPOffset = (ArgMode == 2);
15138   unsigned MaxOffset = TotalNumIntRegs * 8 +
15139                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15140
15141   /* Align ArgSize to a multiple of 8 */
15142   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15143   bool NeedsAlign = (Align > 8);
15144
15145   MachineBasicBlock *thisMBB = MBB;
15146   MachineBasicBlock *overflowMBB;
15147   MachineBasicBlock *offsetMBB;
15148   MachineBasicBlock *endMBB;
15149
15150   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15151   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15152   unsigned OffsetReg = 0;
15153
15154   if (!UseGPOffset && !UseFPOffset) {
15155     // If we only pull from the overflow region, we don't create a branch.
15156     // We don't need to alter control flow.
15157     OffsetDestReg = 0; // unused
15158     OverflowDestReg = DestReg;
15159
15160     offsetMBB = NULL;
15161     overflowMBB = thisMBB;
15162     endMBB = thisMBB;
15163   } else {
15164     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15165     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15166     // If not, pull from overflow_area. (branch to overflowMBB)
15167     //
15168     //       thisMBB
15169     //         |     .
15170     //         |        .
15171     //     offsetMBB   overflowMBB
15172     //         |        .
15173     //         |     .
15174     //        endMBB
15175
15176     // Registers for the PHI in endMBB
15177     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15178     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15179
15180     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15181     MachineFunction *MF = MBB->getParent();
15182     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15183     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15184     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15185
15186     MachineFunction::iterator MBBIter = MBB;
15187     ++MBBIter;
15188
15189     // Insert the new basic blocks
15190     MF->insert(MBBIter, offsetMBB);
15191     MF->insert(MBBIter, overflowMBB);
15192     MF->insert(MBBIter, endMBB);
15193
15194     // Transfer the remainder of MBB and its successor edges to endMBB.
15195     endMBB->splice(endMBB->begin(), thisMBB,
15196                     llvm::next(MachineBasicBlock::iterator(MI)),
15197                     thisMBB->end());
15198     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15199
15200     // Make offsetMBB and overflowMBB successors of thisMBB
15201     thisMBB->addSuccessor(offsetMBB);
15202     thisMBB->addSuccessor(overflowMBB);
15203
15204     // endMBB is a successor of both offsetMBB and overflowMBB
15205     offsetMBB->addSuccessor(endMBB);
15206     overflowMBB->addSuccessor(endMBB);
15207
15208     // Load the offset value into a register
15209     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15210     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15211       .addOperand(Base)
15212       .addOperand(Scale)
15213       .addOperand(Index)
15214       .addDisp(Disp, UseFPOffset ? 4 : 0)
15215       .addOperand(Segment)
15216       .setMemRefs(MMOBegin, MMOEnd);
15217
15218     // Check if there is enough room left to pull this argument.
15219     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15220       .addReg(OffsetReg)
15221       .addImm(MaxOffset + 8 - ArgSizeA8);
15222
15223     // Branch to "overflowMBB" if offset >= max
15224     // Fall through to "offsetMBB" otherwise
15225     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15226       .addMBB(overflowMBB);
15227   }
15228
15229   // In offsetMBB, emit code to use the reg_save_area.
15230   if (offsetMBB) {
15231     assert(OffsetReg != 0);
15232
15233     // Read the reg_save_area address.
15234     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15235     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15236       .addOperand(Base)
15237       .addOperand(Scale)
15238       .addOperand(Index)
15239       .addDisp(Disp, 16)
15240       .addOperand(Segment)
15241       .setMemRefs(MMOBegin, MMOEnd);
15242
15243     // Zero-extend the offset
15244     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15245       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15246         .addImm(0)
15247         .addReg(OffsetReg)
15248         .addImm(X86::sub_32bit);
15249
15250     // Add the offset to the reg_save_area to get the final address.
15251     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15252       .addReg(OffsetReg64)
15253       .addReg(RegSaveReg);
15254
15255     // Compute the offset for the next argument
15256     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15257     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15258       .addReg(OffsetReg)
15259       .addImm(UseFPOffset ? 16 : 8);
15260
15261     // Store it back into the va_list.
15262     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15263       .addOperand(Base)
15264       .addOperand(Scale)
15265       .addOperand(Index)
15266       .addDisp(Disp, UseFPOffset ? 4 : 0)
15267       .addOperand(Segment)
15268       .addReg(NextOffsetReg)
15269       .setMemRefs(MMOBegin, MMOEnd);
15270
15271     // Jump to endMBB
15272     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15273       .addMBB(endMBB);
15274   }
15275
15276   //
15277   // Emit code to use overflow area
15278   //
15279
15280   // Load the overflow_area address into a register.
15281   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15282   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15283     .addOperand(Base)
15284     .addOperand(Scale)
15285     .addOperand(Index)
15286     .addDisp(Disp, 8)
15287     .addOperand(Segment)
15288     .setMemRefs(MMOBegin, MMOEnd);
15289
15290   // If we need to align it, do so. Otherwise, just copy the address
15291   // to OverflowDestReg.
15292   if (NeedsAlign) {
15293     // Align the overflow address
15294     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15295     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15296
15297     // aligned_addr = (addr + (align-1)) & ~(align-1)
15298     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15299       .addReg(OverflowAddrReg)
15300       .addImm(Align-1);
15301
15302     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15303       .addReg(TmpReg)
15304       .addImm(~(uint64_t)(Align-1));
15305   } else {
15306     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15307       .addReg(OverflowAddrReg);
15308   }
15309
15310   // Compute the next overflow address after this argument.
15311   // (the overflow address should be kept 8-byte aligned)
15312   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15313   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15314     .addReg(OverflowDestReg)
15315     .addImm(ArgSizeA8);
15316
15317   // Store the new overflow address.
15318   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15319     .addOperand(Base)
15320     .addOperand(Scale)
15321     .addOperand(Index)
15322     .addDisp(Disp, 8)
15323     .addOperand(Segment)
15324     .addReg(NextAddrReg)
15325     .setMemRefs(MMOBegin, MMOEnd);
15326
15327   // If we branched, emit the PHI to the front of endMBB.
15328   if (offsetMBB) {
15329     BuildMI(*endMBB, endMBB->begin(), DL,
15330             TII->get(X86::PHI), DestReg)
15331       .addReg(OffsetDestReg).addMBB(offsetMBB)
15332       .addReg(OverflowDestReg).addMBB(overflowMBB);
15333   }
15334
15335   // Erase the pseudo instruction
15336   MI->eraseFromParent();
15337
15338   return endMBB;
15339 }
15340
15341 MachineBasicBlock *
15342 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15343                                                  MachineInstr *MI,
15344                                                  MachineBasicBlock *MBB) const {
15345   // Emit code to save XMM registers to the stack. The ABI says that the
15346   // number of registers to save is given in %al, so it's theoretically
15347   // possible to do an indirect jump trick to avoid saving all of them,
15348   // however this code takes a simpler approach and just executes all
15349   // of the stores if %al is non-zero. It's less code, and it's probably
15350   // easier on the hardware branch predictor, and stores aren't all that
15351   // expensive anyway.
15352
15353   // Create the new basic blocks. One block contains all the XMM stores,
15354   // and one block is the final destination regardless of whether any
15355   // stores were performed.
15356   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15357   MachineFunction *F = MBB->getParent();
15358   MachineFunction::iterator MBBIter = MBB;
15359   ++MBBIter;
15360   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15361   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15362   F->insert(MBBIter, XMMSaveMBB);
15363   F->insert(MBBIter, EndMBB);
15364
15365   // Transfer the remainder of MBB and its successor edges to EndMBB.
15366   EndMBB->splice(EndMBB->begin(), MBB,
15367                  llvm::next(MachineBasicBlock::iterator(MI)),
15368                  MBB->end());
15369   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15370
15371   // The original block will now fall through to the XMM save block.
15372   MBB->addSuccessor(XMMSaveMBB);
15373   // The XMMSaveMBB will fall through to the end block.
15374   XMMSaveMBB->addSuccessor(EndMBB);
15375
15376   // Now add the instructions.
15377   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15378   DebugLoc DL = MI->getDebugLoc();
15379
15380   unsigned CountReg = MI->getOperand(0).getReg();
15381   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15382   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15383
15384   if (!Subtarget->isTargetWin64()) {
15385     // If %al is 0, branch around the XMM save block.
15386     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15387     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15388     MBB->addSuccessor(EndMBB);
15389   }
15390
15391   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15392   // that was just emitted, but clearly shouldn't be "saved".
15393   assert((MI->getNumOperands() <= 3 ||
15394           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15395           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15396          && "Expected last argument to be EFLAGS");
15397   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15398   // In the XMM save block, save all the XMM argument registers.
15399   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15400     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15401     MachineMemOperand *MMO =
15402       F->getMachineMemOperand(
15403           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15404         MachineMemOperand::MOStore,
15405         /*Size=*/16, /*Align=*/16);
15406     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15407       .addFrameIndex(RegSaveFrameIndex)
15408       .addImm(/*Scale=*/1)
15409       .addReg(/*IndexReg=*/0)
15410       .addImm(/*Disp=*/Offset)
15411       .addReg(/*Segment=*/0)
15412       .addReg(MI->getOperand(i).getReg())
15413       .addMemOperand(MMO);
15414   }
15415
15416   MI->eraseFromParent();   // The pseudo instruction is gone now.
15417
15418   return EndMBB;
15419 }
15420
15421 // The EFLAGS operand of SelectItr might be missing a kill marker
15422 // because there were multiple uses of EFLAGS, and ISel didn't know
15423 // which to mark. Figure out whether SelectItr should have had a
15424 // kill marker, and set it if it should. Returns the correct kill
15425 // marker value.
15426 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15427                                      MachineBasicBlock* BB,
15428                                      const TargetRegisterInfo* TRI) {
15429   // Scan forward through BB for a use/def of EFLAGS.
15430   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
15431   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15432     const MachineInstr& mi = *miI;
15433     if (mi.readsRegister(X86::EFLAGS))
15434       return false;
15435     if (mi.definesRegister(X86::EFLAGS))
15436       break; // Should have kill-flag - update below.
15437   }
15438
15439   // If we hit the end of the block, check whether EFLAGS is live into a
15440   // successor.
15441   if (miI == BB->end()) {
15442     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
15443                                           sEnd = BB->succ_end();
15444          sItr != sEnd; ++sItr) {
15445       MachineBasicBlock* succ = *sItr;
15446       if (succ->isLiveIn(X86::EFLAGS))
15447         return false;
15448     }
15449   }
15450
15451   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
15452   // out. SelectMI should have a kill flag on EFLAGS.
15453   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
15454   return true;
15455 }
15456
15457 MachineBasicBlock *
15458 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
15459                                      MachineBasicBlock *BB) const {
15460   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15461   DebugLoc DL = MI->getDebugLoc();
15462
15463   // To "insert" a SELECT_CC instruction, we actually have to insert the
15464   // diamond control-flow pattern.  The incoming instruction knows the
15465   // destination vreg to set, the condition code register to branch on, the
15466   // true/false values to select between, and a branch opcode to use.
15467   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15468   MachineFunction::iterator It = BB;
15469   ++It;
15470
15471   //  thisMBB:
15472   //  ...
15473   //   TrueVal = ...
15474   //   cmpTY ccX, r1, r2
15475   //   bCC copy1MBB
15476   //   fallthrough --> copy0MBB
15477   MachineBasicBlock *thisMBB = BB;
15478   MachineFunction *F = BB->getParent();
15479   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
15480   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
15481   F->insert(It, copy0MBB);
15482   F->insert(It, sinkMBB);
15483
15484   // If the EFLAGS register isn't dead in the terminator, then claim that it's
15485   // live into the sink and copy blocks.
15486   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15487   if (!MI->killsRegister(X86::EFLAGS) &&
15488       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
15489     copy0MBB->addLiveIn(X86::EFLAGS);
15490     sinkMBB->addLiveIn(X86::EFLAGS);
15491   }
15492
15493   // Transfer the remainder of BB and its successor edges to sinkMBB.
15494   sinkMBB->splice(sinkMBB->begin(), BB,
15495                   llvm::next(MachineBasicBlock::iterator(MI)),
15496                   BB->end());
15497   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
15498
15499   // Add the true and fallthrough blocks as its successors.
15500   BB->addSuccessor(copy0MBB);
15501   BB->addSuccessor(sinkMBB);
15502
15503   // Create the conditional branch instruction.
15504   unsigned Opc =
15505     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
15506   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
15507
15508   //  copy0MBB:
15509   //   %FalseValue = ...
15510   //   # fallthrough to sinkMBB
15511   copy0MBB->addSuccessor(sinkMBB);
15512
15513   //  sinkMBB:
15514   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
15515   //  ...
15516   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15517           TII->get(X86::PHI), MI->getOperand(0).getReg())
15518     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
15519     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
15520
15521   MI->eraseFromParent();   // The pseudo instruction is gone now.
15522   return sinkMBB;
15523 }
15524
15525 MachineBasicBlock *
15526 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
15527                                         bool Is64Bit) const {
15528   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15529   DebugLoc DL = MI->getDebugLoc();
15530   MachineFunction *MF = BB->getParent();
15531   const BasicBlock *LLVM_BB = BB->getBasicBlock();
15532
15533   assert(getTargetMachine().Options.EnableSegmentedStacks);
15534
15535   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
15536   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
15537
15538   // BB:
15539   //  ... [Till the alloca]
15540   // If stacklet is not large enough, jump to mallocMBB
15541   //
15542   // bumpMBB:
15543   //  Allocate by subtracting from RSP
15544   //  Jump to continueMBB
15545   //
15546   // mallocMBB:
15547   //  Allocate by call to runtime
15548   //
15549   // continueMBB:
15550   //  ...
15551   //  [rest of original BB]
15552   //
15553
15554   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15555   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15556   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15557
15558   MachineRegisterInfo &MRI = MF->getRegInfo();
15559   const TargetRegisterClass *AddrRegClass =
15560     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
15561
15562   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15563     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
15564     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
15565     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
15566     sizeVReg = MI->getOperand(1).getReg(),
15567     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
15568
15569   MachineFunction::iterator MBBIter = BB;
15570   ++MBBIter;
15571
15572   MF->insert(MBBIter, bumpMBB);
15573   MF->insert(MBBIter, mallocMBB);
15574   MF->insert(MBBIter, continueMBB);
15575
15576   continueMBB->splice(continueMBB->begin(), BB, llvm::next
15577                       (MachineBasicBlock::iterator(MI)), BB->end());
15578   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
15579
15580   // Add code to the main basic block to check if the stack limit has been hit,
15581   // and if so, jump to mallocMBB otherwise to bumpMBB.
15582   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
15583   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
15584     .addReg(tmpSPVReg).addReg(sizeVReg);
15585   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
15586     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
15587     .addReg(SPLimitVReg);
15588   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
15589
15590   // bumpMBB simply decreases the stack pointer, since we know the current
15591   // stacklet has enough space.
15592   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
15593     .addReg(SPLimitVReg);
15594   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
15595     .addReg(SPLimitVReg);
15596   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15597
15598   // Calls into a routine in libgcc to allocate more space from the heap.
15599   const uint32_t *RegMask =
15600     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15601   if (Is64Bit) {
15602     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
15603       .addReg(sizeVReg);
15604     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
15605       .addExternalSymbol("__morestack_allocate_stack_space")
15606       .addRegMask(RegMask)
15607       .addReg(X86::RDI, RegState::Implicit)
15608       .addReg(X86::RAX, RegState::ImplicitDefine);
15609   } else {
15610     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
15611       .addImm(12);
15612     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
15613     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
15614       .addExternalSymbol("__morestack_allocate_stack_space")
15615       .addRegMask(RegMask)
15616       .addReg(X86::EAX, RegState::ImplicitDefine);
15617   }
15618
15619   if (!Is64Bit)
15620     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
15621       .addImm(16);
15622
15623   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
15624     .addReg(Is64Bit ? X86::RAX : X86::EAX);
15625   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
15626
15627   // Set up the CFG correctly.
15628   BB->addSuccessor(bumpMBB);
15629   BB->addSuccessor(mallocMBB);
15630   mallocMBB->addSuccessor(continueMBB);
15631   bumpMBB->addSuccessor(continueMBB);
15632
15633   // Take care of the PHI nodes.
15634   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
15635           MI->getOperand(0).getReg())
15636     .addReg(mallocPtrVReg).addMBB(mallocMBB)
15637     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
15638
15639   // Delete the original pseudo instruction.
15640   MI->eraseFromParent();
15641
15642   // And we're done.
15643   return continueMBB;
15644 }
15645
15646 MachineBasicBlock *
15647 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15648                                           MachineBasicBlock *BB) const {
15649   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15650   DebugLoc DL = MI->getDebugLoc();
15651
15652   assert(!Subtarget->isTargetMacho());
15653
15654   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15655   // non-trivial part is impdef of ESP.
15656
15657   if (Subtarget->isTargetWin64()) {
15658     if (Subtarget->isTargetCygMing()) {
15659       // ___chkstk(Mingw64):
15660       // Clobbers R10, R11, RAX and EFLAGS.
15661       // Updates RSP.
15662       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15663         .addExternalSymbol("___chkstk")
15664         .addReg(X86::RAX, RegState::Implicit)
15665         .addReg(X86::RSP, RegState::Implicit)
15666         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15667         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15668         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15669     } else {
15670       // __chkstk(MSVCRT): does not update stack pointer.
15671       // Clobbers R10, R11 and EFLAGS.
15672       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15673         .addExternalSymbol("__chkstk")
15674         .addReg(X86::RAX, RegState::Implicit)
15675         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15676       // RAX has the offset to be subtracted from RSP.
15677       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15678         .addReg(X86::RSP)
15679         .addReg(X86::RAX);
15680     }
15681   } else {
15682     const char *StackProbeSymbol =
15683       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15684
15685     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15686       .addExternalSymbol(StackProbeSymbol)
15687       .addReg(X86::EAX, RegState::Implicit)
15688       .addReg(X86::ESP, RegState::Implicit)
15689       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15690       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15691       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15692   }
15693
15694   MI->eraseFromParent();   // The pseudo instruction is gone now.
15695   return BB;
15696 }
15697
15698 MachineBasicBlock *
15699 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15700                                       MachineBasicBlock *BB) const {
15701   // This is pretty easy.  We're taking the value that we received from
15702   // our load from the relocation, sticking it in either RDI (x86-64)
15703   // or EAX and doing an indirect call.  The return value will then
15704   // be in the normal return register.
15705   const X86InstrInfo *TII
15706     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15707   DebugLoc DL = MI->getDebugLoc();
15708   MachineFunction *F = BB->getParent();
15709
15710   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15711   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15712
15713   // Get a register mask for the lowered call.
15714   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15715   // proper register mask.
15716   const uint32_t *RegMask =
15717     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15718   if (Subtarget->is64Bit()) {
15719     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15720                                       TII->get(X86::MOV64rm), X86::RDI)
15721     .addReg(X86::RIP)
15722     .addImm(0).addReg(0)
15723     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15724                       MI->getOperand(3).getTargetFlags())
15725     .addReg(0);
15726     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15727     addDirectMem(MIB, X86::RDI);
15728     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15729   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15730     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15731                                       TII->get(X86::MOV32rm), X86::EAX)
15732     .addReg(0)
15733     .addImm(0).addReg(0)
15734     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15735                       MI->getOperand(3).getTargetFlags())
15736     .addReg(0);
15737     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15738     addDirectMem(MIB, X86::EAX);
15739     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15740   } else {
15741     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15742                                       TII->get(X86::MOV32rm), X86::EAX)
15743     .addReg(TII->getGlobalBaseReg(F))
15744     .addImm(0).addReg(0)
15745     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15746                       MI->getOperand(3).getTargetFlags())
15747     .addReg(0);
15748     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15749     addDirectMem(MIB, X86::EAX);
15750     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15751   }
15752
15753   MI->eraseFromParent(); // The pseudo instruction is gone now.
15754   return BB;
15755 }
15756
15757 MachineBasicBlock *
15758 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15759                                     MachineBasicBlock *MBB) const {
15760   DebugLoc DL = MI->getDebugLoc();
15761   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15762
15763   MachineFunction *MF = MBB->getParent();
15764   MachineRegisterInfo &MRI = MF->getRegInfo();
15765
15766   const BasicBlock *BB = MBB->getBasicBlock();
15767   MachineFunction::iterator I = MBB;
15768   ++I;
15769
15770   // Memory Reference
15771   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15772   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15773
15774   unsigned DstReg;
15775   unsigned MemOpndSlot = 0;
15776
15777   unsigned CurOp = 0;
15778
15779   DstReg = MI->getOperand(CurOp++).getReg();
15780   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15781   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15782   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15783   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15784
15785   MemOpndSlot = CurOp;
15786
15787   MVT PVT = getPointerTy();
15788   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15789          "Invalid Pointer Size!");
15790
15791   // For v = setjmp(buf), we generate
15792   //
15793   // thisMBB:
15794   //  buf[LabelOffset] = restoreMBB
15795   //  SjLjSetup restoreMBB
15796   //
15797   // mainMBB:
15798   //  v_main = 0
15799   //
15800   // sinkMBB:
15801   //  v = phi(main, restore)
15802   //
15803   // restoreMBB:
15804   //  v_restore = 1
15805
15806   MachineBasicBlock *thisMBB = MBB;
15807   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15808   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15809   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15810   MF->insert(I, mainMBB);
15811   MF->insert(I, sinkMBB);
15812   MF->push_back(restoreMBB);
15813
15814   MachineInstrBuilder MIB;
15815
15816   // Transfer the remainder of BB and its successor edges to sinkMBB.
15817   sinkMBB->splice(sinkMBB->begin(), MBB,
15818                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15819   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15820
15821   // thisMBB:
15822   unsigned PtrStoreOpc = 0;
15823   unsigned LabelReg = 0;
15824   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15825   Reloc::Model RM = getTargetMachine().getRelocationModel();
15826   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15827                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15828
15829   // Prepare IP either in reg or imm.
15830   if (!UseImmLabel) {
15831     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15832     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15833     LabelReg = MRI.createVirtualRegister(PtrRC);
15834     if (Subtarget->is64Bit()) {
15835       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15836               .addReg(X86::RIP)
15837               .addImm(0)
15838               .addReg(0)
15839               .addMBB(restoreMBB)
15840               .addReg(0);
15841     } else {
15842       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15843       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15844               .addReg(XII->getGlobalBaseReg(MF))
15845               .addImm(0)
15846               .addReg(0)
15847               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15848               .addReg(0);
15849     }
15850   } else
15851     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15852   // Store IP
15853   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15854   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15855     if (i == X86::AddrDisp)
15856       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15857     else
15858       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15859   }
15860   if (!UseImmLabel)
15861     MIB.addReg(LabelReg);
15862   else
15863     MIB.addMBB(restoreMBB);
15864   MIB.setMemRefs(MMOBegin, MMOEnd);
15865   // Setup
15866   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15867           .addMBB(restoreMBB);
15868
15869   const X86RegisterInfo *RegInfo =
15870     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15871   MIB.addRegMask(RegInfo->getNoPreservedMask());
15872   thisMBB->addSuccessor(mainMBB);
15873   thisMBB->addSuccessor(restoreMBB);
15874
15875   // mainMBB:
15876   //  EAX = 0
15877   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15878   mainMBB->addSuccessor(sinkMBB);
15879
15880   // sinkMBB:
15881   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15882           TII->get(X86::PHI), DstReg)
15883     .addReg(mainDstReg).addMBB(mainMBB)
15884     .addReg(restoreDstReg).addMBB(restoreMBB);
15885
15886   // restoreMBB:
15887   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15888   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15889   restoreMBB->addSuccessor(sinkMBB);
15890
15891   MI->eraseFromParent();
15892   return sinkMBB;
15893 }
15894
15895 MachineBasicBlock *
15896 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15897                                      MachineBasicBlock *MBB) const {
15898   DebugLoc DL = MI->getDebugLoc();
15899   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15900
15901   MachineFunction *MF = MBB->getParent();
15902   MachineRegisterInfo &MRI = MF->getRegInfo();
15903
15904   // Memory Reference
15905   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15906   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15907
15908   MVT PVT = getPointerTy();
15909   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15910          "Invalid Pointer Size!");
15911
15912   const TargetRegisterClass *RC =
15913     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15914   unsigned Tmp = MRI.createVirtualRegister(RC);
15915   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15916   const X86RegisterInfo *RegInfo =
15917     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15918   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15919   unsigned SP = RegInfo->getStackRegister();
15920
15921   MachineInstrBuilder MIB;
15922
15923   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15924   const int64_t SPOffset = 2 * PVT.getStoreSize();
15925
15926   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15927   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15928
15929   // Reload FP
15930   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15931   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15932     MIB.addOperand(MI->getOperand(i));
15933   MIB.setMemRefs(MMOBegin, MMOEnd);
15934   // Reload IP
15935   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15936   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15937     if (i == X86::AddrDisp)
15938       MIB.addDisp(MI->getOperand(i), LabelOffset);
15939     else
15940       MIB.addOperand(MI->getOperand(i));
15941   }
15942   MIB.setMemRefs(MMOBegin, MMOEnd);
15943   // Reload SP
15944   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15945   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15946     if (i == X86::AddrDisp)
15947       MIB.addDisp(MI->getOperand(i), SPOffset);
15948     else
15949       MIB.addOperand(MI->getOperand(i));
15950   }
15951   MIB.setMemRefs(MMOBegin, MMOEnd);
15952   // Jump
15953   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15954
15955   MI->eraseFromParent();
15956   return MBB;
15957 }
15958
15959 MachineBasicBlock *
15960 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15961                                                MachineBasicBlock *BB) const {
15962   switch (MI->getOpcode()) {
15963   default: llvm_unreachable("Unexpected instr type to insert");
15964   case X86::TAILJMPd64:
15965   case X86::TAILJMPr64:
15966   case X86::TAILJMPm64:
15967     llvm_unreachable("TAILJMP64 would not be touched here.");
15968   case X86::TCRETURNdi64:
15969   case X86::TCRETURNri64:
15970   case X86::TCRETURNmi64:
15971     return BB;
15972   case X86::WIN_ALLOCA:
15973     return EmitLoweredWinAlloca(MI, BB);
15974   case X86::SEG_ALLOCA_32:
15975     return EmitLoweredSegAlloca(MI, BB, false);
15976   case X86::SEG_ALLOCA_64:
15977     return EmitLoweredSegAlloca(MI, BB, true);
15978   case X86::TLSCall_32:
15979   case X86::TLSCall_64:
15980     return EmitLoweredTLSCall(MI, BB);
15981   case X86::CMOV_GR8:
15982   case X86::CMOV_FR32:
15983   case X86::CMOV_FR64:
15984   case X86::CMOV_V4F32:
15985   case X86::CMOV_V2F64:
15986   case X86::CMOV_V2I64:
15987   case X86::CMOV_V8F32:
15988   case X86::CMOV_V4F64:
15989   case X86::CMOV_V4I64:
15990   case X86::CMOV_V16F32:
15991   case X86::CMOV_V8F64:
15992   case X86::CMOV_V8I64:
15993   case X86::CMOV_GR16:
15994   case X86::CMOV_GR32:
15995   case X86::CMOV_RFP32:
15996   case X86::CMOV_RFP64:
15997   case X86::CMOV_RFP80:
15998     return EmitLoweredSelect(MI, BB);
15999
16000   case X86::FP32_TO_INT16_IN_MEM:
16001   case X86::FP32_TO_INT32_IN_MEM:
16002   case X86::FP32_TO_INT64_IN_MEM:
16003   case X86::FP64_TO_INT16_IN_MEM:
16004   case X86::FP64_TO_INT32_IN_MEM:
16005   case X86::FP64_TO_INT64_IN_MEM:
16006   case X86::FP80_TO_INT16_IN_MEM:
16007   case X86::FP80_TO_INT32_IN_MEM:
16008   case X86::FP80_TO_INT64_IN_MEM: {
16009     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16010     DebugLoc DL = MI->getDebugLoc();
16011
16012     // Change the floating point control register to use "round towards zero"
16013     // mode when truncating to an integer value.
16014     MachineFunction *F = BB->getParent();
16015     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16016     addFrameReference(BuildMI(*BB, MI, DL,
16017                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16018
16019     // Load the old value of the high byte of the control word...
16020     unsigned OldCW =
16021       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16022     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16023                       CWFrameIdx);
16024
16025     // Set the high part to be round to zero...
16026     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16027       .addImm(0xC7F);
16028
16029     // Reload the modified control word now...
16030     addFrameReference(BuildMI(*BB, MI, DL,
16031                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16032
16033     // Restore the memory image of control word to original value
16034     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16035       .addReg(OldCW);
16036
16037     // Get the X86 opcode to use.
16038     unsigned Opc;
16039     switch (MI->getOpcode()) {
16040     default: llvm_unreachable("illegal opcode!");
16041     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16042     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16043     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16044     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16045     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16046     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16047     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16048     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16049     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16050     }
16051
16052     X86AddressMode AM;
16053     MachineOperand &Op = MI->getOperand(0);
16054     if (Op.isReg()) {
16055       AM.BaseType = X86AddressMode::RegBase;
16056       AM.Base.Reg = Op.getReg();
16057     } else {
16058       AM.BaseType = X86AddressMode::FrameIndexBase;
16059       AM.Base.FrameIndex = Op.getIndex();
16060     }
16061     Op = MI->getOperand(1);
16062     if (Op.isImm())
16063       AM.Scale = Op.getImm();
16064     Op = MI->getOperand(2);
16065     if (Op.isImm())
16066       AM.IndexReg = Op.getImm();
16067     Op = MI->getOperand(3);
16068     if (Op.isGlobal()) {
16069       AM.GV = Op.getGlobal();
16070     } else {
16071       AM.Disp = Op.getImm();
16072     }
16073     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16074                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16075
16076     // Reload the original control word now.
16077     addFrameReference(BuildMI(*BB, MI, DL,
16078                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16079
16080     MI->eraseFromParent();   // The pseudo instruction is gone now.
16081     return BB;
16082   }
16083     // String/text processing lowering.
16084   case X86::PCMPISTRM128REG:
16085   case X86::VPCMPISTRM128REG:
16086   case X86::PCMPISTRM128MEM:
16087   case X86::VPCMPISTRM128MEM:
16088   case X86::PCMPESTRM128REG:
16089   case X86::VPCMPESTRM128REG:
16090   case X86::PCMPESTRM128MEM:
16091   case X86::VPCMPESTRM128MEM:
16092     assert(Subtarget->hasSSE42() &&
16093            "Target must have SSE4.2 or AVX features enabled");
16094     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16095
16096   // String/text processing lowering.
16097   case X86::PCMPISTRIREG:
16098   case X86::VPCMPISTRIREG:
16099   case X86::PCMPISTRIMEM:
16100   case X86::VPCMPISTRIMEM:
16101   case X86::PCMPESTRIREG:
16102   case X86::VPCMPESTRIREG:
16103   case X86::PCMPESTRIMEM:
16104   case X86::VPCMPESTRIMEM:
16105     assert(Subtarget->hasSSE42() &&
16106            "Target must have SSE4.2 or AVX features enabled");
16107     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16108
16109   // Thread synchronization.
16110   case X86::MONITOR:
16111     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16112
16113   // xbegin
16114   case X86::XBEGIN:
16115     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16116
16117   // Atomic Lowering.
16118   case X86::ATOMAND8:
16119   case X86::ATOMAND16:
16120   case X86::ATOMAND32:
16121   case X86::ATOMAND64:
16122     // Fall through
16123   case X86::ATOMOR8:
16124   case X86::ATOMOR16:
16125   case X86::ATOMOR32:
16126   case X86::ATOMOR64:
16127     // Fall through
16128   case X86::ATOMXOR16:
16129   case X86::ATOMXOR8:
16130   case X86::ATOMXOR32:
16131   case X86::ATOMXOR64:
16132     // Fall through
16133   case X86::ATOMNAND8:
16134   case X86::ATOMNAND16:
16135   case X86::ATOMNAND32:
16136   case X86::ATOMNAND64:
16137     // Fall through
16138   case X86::ATOMMAX8:
16139   case X86::ATOMMAX16:
16140   case X86::ATOMMAX32:
16141   case X86::ATOMMAX64:
16142     // Fall through
16143   case X86::ATOMMIN8:
16144   case X86::ATOMMIN16:
16145   case X86::ATOMMIN32:
16146   case X86::ATOMMIN64:
16147     // Fall through
16148   case X86::ATOMUMAX8:
16149   case X86::ATOMUMAX16:
16150   case X86::ATOMUMAX32:
16151   case X86::ATOMUMAX64:
16152     // Fall through
16153   case X86::ATOMUMIN8:
16154   case X86::ATOMUMIN16:
16155   case X86::ATOMUMIN32:
16156   case X86::ATOMUMIN64:
16157     return EmitAtomicLoadArith(MI, BB);
16158
16159   // This group does 64-bit operations on a 32-bit host.
16160   case X86::ATOMAND6432:
16161   case X86::ATOMOR6432:
16162   case X86::ATOMXOR6432:
16163   case X86::ATOMNAND6432:
16164   case X86::ATOMADD6432:
16165   case X86::ATOMSUB6432:
16166   case X86::ATOMMAX6432:
16167   case X86::ATOMMIN6432:
16168   case X86::ATOMUMAX6432:
16169   case X86::ATOMUMIN6432:
16170   case X86::ATOMSWAP6432:
16171     return EmitAtomicLoadArith6432(MI, BB);
16172
16173   case X86::VASTART_SAVE_XMM_REGS:
16174     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16175
16176   case X86::VAARG_64:
16177     return EmitVAARG64WithCustomInserter(MI, BB);
16178
16179   case X86::EH_SjLj_SetJmp32:
16180   case X86::EH_SjLj_SetJmp64:
16181     return emitEHSjLjSetJmp(MI, BB);
16182
16183   case X86::EH_SjLj_LongJmp32:
16184   case X86::EH_SjLj_LongJmp64:
16185     return emitEHSjLjLongJmp(MI, BB);
16186
16187   case TargetOpcode::STACKMAP:
16188   case TargetOpcode::PATCHPOINT:
16189     return emitPatchPoint(MI, BB);
16190   }
16191 }
16192
16193 //===----------------------------------------------------------------------===//
16194 //                           X86 Optimization Hooks
16195 //===----------------------------------------------------------------------===//
16196
16197 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16198                                                        APInt &KnownZero,
16199                                                        APInt &KnownOne,
16200                                                        const SelectionDAG &DAG,
16201                                                        unsigned Depth) const {
16202   unsigned BitWidth = KnownZero.getBitWidth();
16203   unsigned Opc = Op.getOpcode();
16204   assert((Opc >= ISD::BUILTIN_OP_END ||
16205           Opc == ISD::INTRINSIC_WO_CHAIN ||
16206           Opc == ISD::INTRINSIC_W_CHAIN ||
16207           Opc == ISD::INTRINSIC_VOID) &&
16208          "Should use MaskedValueIsZero if you don't know whether Op"
16209          " is a target node!");
16210
16211   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16212   switch (Opc) {
16213   default: break;
16214   case X86ISD::ADD:
16215   case X86ISD::SUB:
16216   case X86ISD::ADC:
16217   case X86ISD::SBB:
16218   case X86ISD::SMUL:
16219   case X86ISD::UMUL:
16220   case X86ISD::INC:
16221   case X86ISD::DEC:
16222   case X86ISD::OR:
16223   case X86ISD::XOR:
16224   case X86ISD::AND:
16225     // These nodes' second result is a boolean.
16226     if (Op.getResNo() == 0)
16227       break;
16228     // Fallthrough
16229   case X86ISD::SETCC:
16230     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16231     break;
16232   case ISD::INTRINSIC_WO_CHAIN: {
16233     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16234     unsigned NumLoBits = 0;
16235     switch (IntId) {
16236     default: break;
16237     case Intrinsic::x86_sse_movmsk_ps:
16238     case Intrinsic::x86_avx_movmsk_ps_256:
16239     case Intrinsic::x86_sse2_movmsk_pd:
16240     case Intrinsic::x86_avx_movmsk_pd_256:
16241     case Intrinsic::x86_mmx_pmovmskb:
16242     case Intrinsic::x86_sse2_pmovmskb_128:
16243     case Intrinsic::x86_avx2_pmovmskb: {
16244       // High bits of movmskp{s|d}, pmovmskb are known zero.
16245       switch (IntId) {
16246         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16247         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16248         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16249         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16250         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16251         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16252         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16253         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16254       }
16255       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16256       break;
16257     }
16258     }
16259     break;
16260   }
16261   }
16262 }
16263
16264 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
16265                                                          unsigned Depth) const {
16266   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16267   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16268     return Op.getValueType().getScalarType().getSizeInBits();
16269
16270   // Fallback case.
16271   return 1;
16272 }
16273
16274 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16275 /// node is a GlobalAddress + offset.
16276 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16277                                        const GlobalValue* &GA,
16278                                        int64_t &Offset) const {
16279   if (N->getOpcode() == X86ISD::Wrapper) {
16280     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16281       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16282       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16283       return true;
16284     }
16285   }
16286   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16287 }
16288
16289 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16290 /// same as extracting the high 128-bit part of 256-bit vector and then
16291 /// inserting the result into the low part of a new 256-bit vector
16292 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16293   EVT VT = SVOp->getValueType(0);
16294   unsigned NumElems = VT.getVectorNumElements();
16295
16296   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16297   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16298     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16299         SVOp->getMaskElt(j) >= 0)
16300       return false;
16301
16302   return true;
16303 }
16304
16305 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16306 /// same as extracting the low 128-bit part of 256-bit vector and then
16307 /// inserting the result into the high part of a new 256-bit vector
16308 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16309   EVT VT = SVOp->getValueType(0);
16310   unsigned NumElems = VT.getVectorNumElements();
16311
16312   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16313   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16314     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16315         SVOp->getMaskElt(j) >= 0)
16316       return false;
16317
16318   return true;
16319 }
16320
16321 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16322 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16323                                         TargetLowering::DAGCombinerInfo &DCI,
16324                                         const X86Subtarget* Subtarget) {
16325   SDLoc dl(N);
16326   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
16327   SDValue V1 = SVOp->getOperand(0);
16328   SDValue V2 = SVOp->getOperand(1);
16329   EVT VT = SVOp->getValueType(0);
16330   unsigned NumElems = VT.getVectorNumElements();
16331
16332   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
16333       V2.getOpcode() == ISD::CONCAT_VECTORS) {
16334     //
16335     //                   0,0,0,...
16336     //                      |
16337     //    V      UNDEF    BUILD_VECTOR    UNDEF
16338     //     \      /           \           /
16339     //  CONCAT_VECTOR         CONCAT_VECTOR
16340     //         \                  /
16341     //          \                /
16342     //          RESULT: V + zero extended
16343     //
16344     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
16345         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
16346         V1.getOperand(1).getOpcode() != ISD::UNDEF)
16347       return SDValue();
16348
16349     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
16350       return SDValue();
16351
16352     // To match the shuffle mask, the first half of the mask should
16353     // be exactly the first vector, and all the rest a splat with the
16354     // first element of the second one.
16355     for (unsigned i = 0; i != NumElems/2; ++i)
16356       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
16357           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
16358         return SDValue();
16359
16360     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
16361     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
16362       if (Ld->hasNUsesOfValue(1, 0)) {
16363         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
16364         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
16365         SDValue ResNode =
16366           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
16367                                   array_lengthof(Ops),
16368                                   Ld->getMemoryVT(),
16369                                   Ld->getPointerInfo(),
16370                                   Ld->getAlignment(),
16371                                   false/*isVolatile*/, true/*ReadMem*/,
16372                                   false/*WriteMem*/);
16373
16374         // Make sure the newly-created LOAD is in the same position as Ld in
16375         // terms of dependency. We create a TokenFactor for Ld and ResNode,
16376         // and update uses of Ld's output chain to use the TokenFactor.
16377         if (Ld->hasAnyUseOfValue(1)) {
16378           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16379                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
16380           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16381           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
16382                                  SDValue(ResNode.getNode(), 1));
16383         }
16384
16385         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
16386       }
16387     }
16388
16389     // Emit a zeroed vector and insert the desired subvector on its
16390     // first half.
16391     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16392     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
16393     return DCI.CombineTo(N, InsV);
16394   }
16395
16396   //===--------------------------------------------------------------------===//
16397   // Combine some shuffles into subvector extracts and inserts:
16398   //
16399
16400   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16401   if (isShuffleHigh128VectorInsertLow(SVOp)) {
16402     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
16403     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
16404     return DCI.CombineTo(N, InsV);
16405   }
16406
16407   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16408   if (isShuffleLow128VectorInsertHigh(SVOp)) {
16409     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
16410     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
16411     return DCI.CombineTo(N, InsV);
16412   }
16413
16414   return SDValue();
16415 }
16416
16417 /// PerformShuffleCombine - Performs several different shuffle combines.
16418 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
16419                                      TargetLowering::DAGCombinerInfo &DCI,
16420                                      const X86Subtarget *Subtarget) {
16421   SDLoc dl(N);
16422   EVT VT = N->getValueType(0);
16423
16424   // Don't create instructions with illegal types after legalize types has run.
16425   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16426   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
16427     return SDValue();
16428
16429   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
16430   if (Subtarget->hasFp256() && VT.is256BitVector() &&
16431       N->getOpcode() == ISD::VECTOR_SHUFFLE)
16432     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
16433
16434   // Only handle 128 wide vector from here on.
16435   if (!VT.is128BitVector())
16436     return SDValue();
16437
16438   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
16439   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
16440   // consecutive, non-overlapping, and in the right order.
16441   SmallVector<SDValue, 16> Elts;
16442   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
16443     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
16444
16445   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
16446 }
16447
16448 /// PerformTruncateCombine - Converts truncate operation to
16449 /// a sequence of vector shuffle operations.
16450 /// It is possible when we truncate 256-bit vector to 128-bit vector
16451 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
16452                                       TargetLowering::DAGCombinerInfo &DCI,
16453                                       const X86Subtarget *Subtarget)  {
16454   return SDValue();
16455 }
16456
16457 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
16458 /// specific shuffle of a load can be folded into a single element load.
16459 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
16460 /// shuffles have been customed lowered so we need to handle those here.
16461 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
16462                                          TargetLowering::DAGCombinerInfo &DCI) {
16463   if (DCI.isBeforeLegalizeOps())
16464     return SDValue();
16465
16466   SDValue InVec = N->getOperand(0);
16467   SDValue EltNo = N->getOperand(1);
16468
16469   if (!isa<ConstantSDNode>(EltNo))
16470     return SDValue();
16471
16472   EVT VT = InVec.getValueType();
16473
16474   bool HasShuffleIntoBitcast = false;
16475   if (InVec.getOpcode() == ISD::BITCAST) {
16476     // Don't duplicate a load with other uses.
16477     if (!InVec.hasOneUse())
16478       return SDValue();
16479     EVT BCVT = InVec.getOperand(0).getValueType();
16480     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
16481       return SDValue();
16482     InVec = InVec.getOperand(0);
16483     HasShuffleIntoBitcast = true;
16484   }
16485
16486   if (!isTargetShuffle(InVec.getOpcode()))
16487     return SDValue();
16488
16489   // Don't duplicate a load with other uses.
16490   if (!InVec.hasOneUse())
16491     return SDValue();
16492
16493   SmallVector<int, 16> ShuffleMask;
16494   bool UnaryShuffle;
16495   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
16496                             UnaryShuffle))
16497     return SDValue();
16498
16499   // Select the input vector, guarding against out of range extract vector.
16500   unsigned NumElems = VT.getVectorNumElements();
16501   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
16502   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
16503   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
16504                                          : InVec.getOperand(1);
16505
16506   // If inputs to shuffle are the same for both ops, then allow 2 uses
16507   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
16508
16509   if (LdNode.getOpcode() == ISD::BITCAST) {
16510     // Don't duplicate a load with other uses.
16511     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
16512       return SDValue();
16513
16514     AllowedUses = 1; // only allow 1 load use if we have a bitcast
16515     LdNode = LdNode.getOperand(0);
16516   }
16517
16518   if (!ISD::isNormalLoad(LdNode.getNode()))
16519     return SDValue();
16520
16521   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
16522
16523   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
16524     return SDValue();
16525
16526   if (HasShuffleIntoBitcast) {
16527     // If there's a bitcast before the shuffle, check if the load type and
16528     // alignment is valid.
16529     unsigned Align = LN0->getAlignment();
16530     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16531     unsigned NewAlign = TLI.getDataLayout()->
16532       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
16533
16534     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
16535       return SDValue();
16536   }
16537
16538   // All checks match so transform back to vector_shuffle so that DAG combiner
16539   // can finish the job
16540   SDLoc dl(N);
16541
16542   // Create shuffle node taking into account the case that its a unary shuffle
16543   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
16544   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
16545                                  InVec.getOperand(0), Shuffle,
16546                                  &ShuffleMask[0]);
16547   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
16548   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
16549                      EltNo);
16550 }
16551
16552 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
16553 /// generation and convert it from being a bunch of shuffles and extracts
16554 /// to a simple store and scalar loads to extract the elements.
16555 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
16556                                          TargetLowering::DAGCombinerInfo &DCI) {
16557   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
16558   if (NewOp.getNode())
16559     return NewOp;
16560
16561   SDValue InputVector = N->getOperand(0);
16562
16563   // Detect whether we are trying to convert from mmx to i32 and the bitcast
16564   // from mmx to v2i32 has a single usage.
16565   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
16566       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
16567       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
16568     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
16569                        N->getValueType(0),
16570                        InputVector.getNode()->getOperand(0));
16571
16572   // Only operate on vectors of 4 elements, where the alternative shuffling
16573   // gets to be more expensive.
16574   if (InputVector.getValueType() != MVT::v4i32)
16575     return SDValue();
16576
16577   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
16578   // single use which is a sign-extend or zero-extend, and all elements are
16579   // used.
16580   SmallVector<SDNode *, 4> Uses;
16581   unsigned ExtractedElements = 0;
16582   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
16583        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
16584     if (UI.getUse().getResNo() != InputVector.getResNo())
16585       return SDValue();
16586
16587     SDNode *Extract = *UI;
16588     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16589       return SDValue();
16590
16591     if (Extract->getValueType(0) != MVT::i32)
16592       return SDValue();
16593     if (!Extract->hasOneUse())
16594       return SDValue();
16595     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
16596         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
16597       return SDValue();
16598     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
16599       return SDValue();
16600
16601     // Record which element was extracted.
16602     ExtractedElements |=
16603       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
16604
16605     Uses.push_back(Extract);
16606   }
16607
16608   // If not all the elements were used, this may not be worthwhile.
16609   if (ExtractedElements != 15)
16610     return SDValue();
16611
16612   // Ok, we've now decided to do the transformation.
16613   SDLoc dl(InputVector);
16614
16615   // Store the value to a temporary stack slot.
16616   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
16617   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
16618                             MachinePointerInfo(), false, false, 0);
16619
16620   // Replace each use (extract) with a load of the appropriate element.
16621   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
16622        UE = Uses.end(); UI != UE; ++UI) {
16623     SDNode *Extract = *UI;
16624
16625     // cOMpute the element's address.
16626     SDValue Idx = Extract->getOperand(1);
16627     unsigned EltSize =
16628         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
16629     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
16630     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16631     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
16632
16633     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
16634                                      StackPtr, OffsetVal);
16635
16636     // Load the scalar.
16637     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
16638                                      ScalarAddr, MachinePointerInfo(),
16639                                      false, false, false, 0);
16640
16641     // Replace the exact with the load.
16642     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
16643   }
16644
16645   // The replacement was made in place; don't return anything.
16646   return SDValue();
16647 }
16648
16649 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
16650 static std::pair<unsigned, bool>
16651 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
16652                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
16653   if (!VT.isVector())
16654     return std::make_pair(0, false);
16655
16656   bool NeedSplit = false;
16657   switch (VT.getSimpleVT().SimpleTy) {
16658   default: return std::make_pair(0, false);
16659   case MVT::v32i8:
16660   case MVT::v16i16:
16661   case MVT::v8i32:
16662     if (!Subtarget->hasAVX2())
16663       NeedSplit = true;
16664     if (!Subtarget->hasAVX())
16665       return std::make_pair(0, false);
16666     break;
16667   case MVT::v16i8:
16668   case MVT::v8i16:
16669   case MVT::v4i32:
16670     if (!Subtarget->hasSSE2())
16671       return std::make_pair(0, false);
16672   }
16673
16674   // SSE2 has only a small subset of the operations.
16675   bool hasUnsigned = Subtarget->hasSSE41() ||
16676                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16677   bool hasSigned = Subtarget->hasSSE41() ||
16678                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16679
16680   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16681
16682   unsigned Opc = 0;
16683   // Check for x CC y ? x : y.
16684   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16685       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16686     switch (CC) {
16687     default: break;
16688     case ISD::SETULT:
16689     case ISD::SETULE:
16690       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16691     case ISD::SETUGT:
16692     case ISD::SETUGE:
16693       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16694     case ISD::SETLT:
16695     case ISD::SETLE:
16696       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16697     case ISD::SETGT:
16698     case ISD::SETGE:
16699       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16700     }
16701   // Check for x CC y ? y : x -- a min/max with reversed arms.
16702   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16703              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16704     switch (CC) {
16705     default: break;
16706     case ISD::SETULT:
16707     case ISD::SETULE:
16708       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
16709     case ISD::SETUGT:
16710     case ISD::SETUGE:
16711       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
16712     case ISD::SETLT:
16713     case ISD::SETLE:
16714       Opc = hasSigned ? X86ISD::SMAX : 0; break;
16715     case ISD::SETGT:
16716     case ISD::SETGE:
16717       Opc = hasSigned ? X86ISD::SMIN : 0; break;
16718     }
16719   }
16720
16721   return std::make_pair(Opc, NeedSplit);
16722 }
16723
16724 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16725 /// nodes.
16726 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16727                                     TargetLowering::DAGCombinerInfo &DCI,
16728                                     const X86Subtarget *Subtarget) {
16729   SDLoc DL(N);
16730   SDValue Cond = N->getOperand(0);
16731   // Get the LHS/RHS of the select.
16732   SDValue LHS = N->getOperand(1);
16733   SDValue RHS = N->getOperand(2);
16734   EVT VT = LHS.getValueType();
16735   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16736
16737   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16738   // instructions match the semantics of the common C idiom x<y?x:y but not
16739   // x<=y?x:y, because of how they handle negative zero (which can be
16740   // ignored in unsafe-math mode).
16741   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16742       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
16743       (Subtarget->hasSSE2() ||
16744        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16745     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16746
16747     unsigned Opcode = 0;
16748     // Check for x CC y ? x : y.
16749     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16750         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16751       switch (CC) {
16752       default: break;
16753       case ISD::SETULT:
16754         // Converting this to a min would handle NaNs incorrectly, and swapping
16755         // the operands would cause it to handle comparisons between positive
16756         // and negative zero incorrectly.
16757         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16758           if (!DAG.getTarget().Options.UnsafeFPMath &&
16759               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16760             break;
16761           std::swap(LHS, RHS);
16762         }
16763         Opcode = X86ISD::FMIN;
16764         break;
16765       case ISD::SETOLE:
16766         // Converting this to a min would handle comparisons between positive
16767         // and negative zero incorrectly.
16768         if (!DAG.getTarget().Options.UnsafeFPMath &&
16769             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16770           break;
16771         Opcode = X86ISD::FMIN;
16772         break;
16773       case ISD::SETULE:
16774         // Converting this to a min would handle both negative zeros and NaNs
16775         // incorrectly, but we can swap the operands to fix both.
16776         std::swap(LHS, RHS);
16777       case ISD::SETOLT:
16778       case ISD::SETLT:
16779       case ISD::SETLE:
16780         Opcode = X86ISD::FMIN;
16781         break;
16782
16783       case ISD::SETOGE:
16784         // Converting this to a max would handle comparisons between positive
16785         // and negative zero incorrectly.
16786         if (!DAG.getTarget().Options.UnsafeFPMath &&
16787             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16788           break;
16789         Opcode = X86ISD::FMAX;
16790         break;
16791       case ISD::SETUGT:
16792         // Converting this to a max would handle NaNs incorrectly, and swapping
16793         // the operands would cause it to handle comparisons between positive
16794         // and negative zero incorrectly.
16795         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16796           if (!DAG.getTarget().Options.UnsafeFPMath &&
16797               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16798             break;
16799           std::swap(LHS, RHS);
16800         }
16801         Opcode = X86ISD::FMAX;
16802         break;
16803       case ISD::SETUGE:
16804         // Converting this to a max would handle both negative zeros and NaNs
16805         // incorrectly, but we can swap the operands to fix both.
16806         std::swap(LHS, RHS);
16807       case ISD::SETOGT:
16808       case ISD::SETGT:
16809       case ISD::SETGE:
16810         Opcode = X86ISD::FMAX;
16811         break;
16812       }
16813     // Check for x CC y ? y : x -- a min/max with reversed arms.
16814     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16815                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16816       switch (CC) {
16817       default: break;
16818       case ISD::SETOGE:
16819         // Converting this to a min would handle comparisons between positive
16820         // and negative zero incorrectly, and swapping the operands would
16821         // cause it to handle NaNs incorrectly.
16822         if (!DAG.getTarget().Options.UnsafeFPMath &&
16823             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16824           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16825             break;
16826           std::swap(LHS, RHS);
16827         }
16828         Opcode = X86ISD::FMIN;
16829         break;
16830       case ISD::SETUGT:
16831         // Converting this to a min would handle NaNs incorrectly.
16832         if (!DAG.getTarget().Options.UnsafeFPMath &&
16833             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16834           break;
16835         Opcode = X86ISD::FMIN;
16836         break;
16837       case ISD::SETUGE:
16838         // Converting this to a min would handle both negative zeros and NaNs
16839         // incorrectly, but we can swap the operands to fix both.
16840         std::swap(LHS, RHS);
16841       case ISD::SETOGT:
16842       case ISD::SETGT:
16843       case ISD::SETGE:
16844         Opcode = X86ISD::FMIN;
16845         break;
16846
16847       case ISD::SETULT:
16848         // Converting this to a max would handle NaNs incorrectly.
16849         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16850           break;
16851         Opcode = X86ISD::FMAX;
16852         break;
16853       case ISD::SETOLE:
16854         // Converting this to a max would handle comparisons between positive
16855         // and negative zero incorrectly, and swapping the operands would
16856         // cause it to handle NaNs incorrectly.
16857         if (!DAG.getTarget().Options.UnsafeFPMath &&
16858             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16859           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16860             break;
16861           std::swap(LHS, RHS);
16862         }
16863         Opcode = X86ISD::FMAX;
16864         break;
16865       case ISD::SETULE:
16866         // Converting this to a max would handle both negative zeros and NaNs
16867         // incorrectly, but we can swap the operands to fix both.
16868         std::swap(LHS, RHS);
16869       case ISD::SETOLT:
16870       case ISD::SETLT:
16871       case ISD::SETLE:
16872         Opcode = X86ISD::FMAX;
16873         break;
16874       }
16875     }
16876
16877     if (Opcode)
16878       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16879   }
16880
16881   EVT CondVT = Cond.getValueType();
16882   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
16883       CondVT.getVectorElementType() == MVT::i1) {
16884     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
16885     // lowering on AVX-512. In this case we convert it to
16886     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
16887     // The same situation for all 128 and 256-bit vectors of i8 and i16
16888     EVT OpVT = LHS.getValueType();
16889     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
16890         (OpVT.getVectorElementType() == MVT::i8 ||
16891          OpVT.getVectorElementType() == MVT::i16)) {
16892       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
16893       DCI.AddToWorklist(Cond.getNode());
16894       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
16895     }
16896   }
16897   // If this is a select between two integer constants, try to do some
16898   // optimizations.
16899   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16900     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16901       // Don't do this for crazy integer types.
16902       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16903         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16904         // so that TrueC (the true value) is larger than FalseC.
16905         bool NeedsCondInvert = false;
16906
16907         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16908             // Efficiently invertible.
16909             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16910              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16911               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16912           NeedsCondInvert = true;
16913           std::swap(TrueC, FalseC);
16914         }
16915
16916         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16917         if (FalseC->getAPIntValue() == 0 &&
16918             TrueC->getAPIntValue().isPowerOf2()) {
16919           if (NeedsCondInvert) // Invert the condition if needed.
16920             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16921                                DAG.getConstant(1, Cond.getValueType()));
16922
16923           // Zero extend the condition if needed.
16924           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16925
16926           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16927           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16928                              DAG.getConstant(ShAmt, MVT::i8));
16929         }
16930
16931         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16932         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16933           if (NeedsCondInvert) // Invert the condition if needed.
16934             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16935                                DAG.getConstant(1, Cond.getValueType()));
16936
16937           // Zero extend the condition if needed.
16938           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16939                              FalseC->getValueType(0), Cond);
16940           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16941                              SDValue(FalseC, 0));
16942         }
16943
16944         // Optimize cases that will turn into an LEA instruction.  This requires
16945         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16946         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16947           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16948           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16949
16950           bool isFastMultiplier = false;
16951           if (Diff < 10) {
16952             switch ((unsigned char)Diff) {
16953               default: break;
16954               case 1:  // result = add base, cond
16955               case 2:  // result = lea base(    , cond*2)
16956               case 3:  // result = lea base(cond, cond*2)
16957               case 4:  // result = lea base(    , cond*4)
16958               case 5:  // result = lea base(cond, cond*4)
16959               case 8:  // result = lea base(    , cond*8)
16960               case 9:  // result = lea base(cond, cond*8)
16961                 isFastMultiplier = true;
16962                 break;
16963             }
16964           }
16965
16966           if (isFastMultiplier) {
16967             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16968             if (NeedsCondInvert) // Invert the condition if needed.
16969               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16970                                  DAG.getConstant(1, Cond.getValueType()));
16971
16972             // Zero extend the condition if needed.
16973             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16974                                Cond);
16975             // Scale the condition by the difference.
16976             if (Diff != 1)
16977               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16978                                  DAG.getConstant(Diff, Cond.getValueType()));
16979
16980             // Add the base if non-zero.
16981             if (FalseC->getAPIntValue() != 0)
16982               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16983                                  SDValue(FalseC, 0));
16984             return Cond;
16985           }
16986         }
16987       }
16988   }
16989
16990   // Canonicalize max and min:
16991   // (x > y) ? x : y -> (x >= y) ? x : y
16992   // (x < y) ? x : y -> (x <= y) ? x : y
16993   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16994   // the need for an extra compare
16995   // against zero. e.g.
16996   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16997   // subl   %esi, %edi
16998   // testl  %edi, %edi
16999   // movl   $0, %eax
17000   // cmovgl %edi, %eax
17001   // =>
17002   // xorl   %eax, %eax
17003   // subl   %esi, $edi
17004   // cmovsl %eax, %edi
17005   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17006       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17007       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17008     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17009     switch (CC) {
17010     default: break;
17011     case ISD::SETLT:
17012     case ISD::SETGT: {
17013       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17014       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17015                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17016       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17017     }
17018     }
17019   }
17020
17021   // Early exit check
17022   if (!TLI.isTypeLegal(VT))
17023     return SDValue();
17024
17025   // Match VSELECTs into subs with unsigned saturation.
17026   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17027       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17028       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17029        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17030     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17031
17032     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17033     // left side invert the predicate to simplify logic below.
17034     SDValue Other;
17035     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17036       Other = RHS;
17037       CC = ISD::getSetCCInverse(CC, true);
17038     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17039       Other = LHS;
17040     }
17041
17042     if (Other.getNode() && Other->getNumOperands() == 2 &&
17043         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17044       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17045       SDValue CondRHS = Cond->getOperand(1);
17046
17047       // Look for a general sub with unsigned saturation first.
17048       // x >= y ? x-y : 0 --> subus x, y
17049       // x >  y ? x-y : 0 --> subus x, y
17050       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17051           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17052         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17053
17054       // If the RHS is a constant we have to reverse the const canonicalization.
17055       // x > C-1 ? x+-C : 0 --> subus x, C
17056       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17057           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17058         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17059         if (CondRHS.getConstantOperandVal(0) == -A-1)
17060           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17061                              DAG.getConstant(-A, VT));
17062       }
17063
17064       // Another special case: If C was a sign bit, the sub has been
17065       // canonicalized into a xor.
17066       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17067       //        it's safe to decanonicalize the xor?
17068       // x s< 0 ? x^C : 0 --> subus x, C
17069       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17070           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17071           isSplatVector(OpRHS.getNode())) {
17072         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17073         if (A.isSignBit())
17074           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17075       }
17076     }
17077   }
17078
17079   // Try to match a min/max vector operation.
17080   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17081     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17082     unsigned Opc = ret.first;
17083     bool NeedSplit = ret.second;
17084
17085     if (Opc && NeedSplit) {
17086       unsigned NumElems = VT.getVectorNumElements();
17087       // Extract the LHS vectors
17088       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17089       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17090
17091       // Extract the RHS vectors
17092       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17093       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17094
17095       // Create min/max for each subvector
17096       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17097       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17098
17099       // Merge the result
17100       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17101     } else if (Opc)
17102       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17103   }
17104
17105   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17106   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17107       // Check if SETCC has already been promoted
17108       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17109       // Check that condition value type matches vselect operand type
17110       CondVT == VT) { 
17111
17112     assert(Cond.getValueType().isVector() &&
17113            "vector select expects a vector selector!");
17114
17115     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17116     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17117
17118     if (!TValIsAllOnes && !FValIsAllZeros) {
17119       // Try invert the condition if true value is not all 1s and false value
17120       // is not all 0s.
17121       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17122       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17123
17124       if (TValIsAllZeros || FValIsAllOnes) {
17125         SDValue CC = Cond.getOperand(2);
17126         ISD::CondCode NewCC =
17127           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17128                                Cond.getOperand(0).getValueType().isInteger());
17129         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17130         std::swap(LHS, RHS);
17131         TValIsAllOnes = FValIsAllOnes;
17132         FValIsAllZeros = TValIsAllZeros;
17133       }
17134     }
17135
17136     if (TValIsAllOnes || FValIsAllZeros) {
17137       SDValue Ret;
17138
17139       if (TValIsAllOnes && FValIsAllZeros)
17140         Ret = Cond;
17141       else if (TValIsAllOnes)
17142         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17143                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17144       else if (FValIsAllZeros)
17145         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17146                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17147
17148       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17149     }
17150   }
17151
17152   // If we know that this node is legal then we know that it is going to be
17153   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17154   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17155   // to simplify previous instructions.
17156   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17157       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17158     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17159
17160     // Don't optimize vector selects that map to mask-registers.
17161     if (BitWidth == 1)
17162       return SDValue();
17163
17164     // Check all uses of that condition operand to check whether it will be
17165     // consumed by non-BLEND instructions, which may depend on all bits are set
17166     // properly.
17167     for (SDNode::use_iterator I = Cond->use_begin(),
17168                               E = Cond->use_end(); I != E; ++I)
17169       if (I->getOpcode() != ISD::VSELECT)
17170         // TODO: Add other opcodes eventually lowered into BLEND.
17171         return SDValue();
17172
17173     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17174     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17175
17176     APInt KnownZero, KnownOne;
17177     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17178                                           DCI.isBeforeLegalizeOps());
17179     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17180         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17181       DCI.CommitTargetLoweringOpt(TLO);
17182   }
17183
17184   return SDValue();
17185 }
17186
17187 // Check whether a boolean test is testing a boolean value generated by
17188 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17189 // code.
17190 //
17191 // Simplify the following patterns:
17192 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17193 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17194 // to (Op EFLAGS Cond)
17195 //
17196 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17197 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17198 // to (Op EFLAGS !Cond)
17199 //
17200 // where Op could be BRCOND or CMOV.
17201 //
17202 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17203   // Quit if not CMP and SUB with its value result used.
17204   if (Cmp.getOpcode() != X86ISD::CMP &&
17205       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17206       return SDValue();
17207
17208   // Quit if not used as a boolean value.
17209   if (CC != X86::COND_E && CC != X86::COND_NE)
17210     return SDValue();
17211
17212   // Check CMP operands. One of them should be 0 or 1 and the other should be
17213   // an SetCC or extended from it.
17214   SDValue Op1 = Cmp.getOperand(0);
17215   SDValue Op2 = Cmp.getOperand(1);
17216
17217   SDValue SetCC;
17218   const ConstantSDNode* C = 0;
17219   bool needOppositeCond = (CC == X86::COND_E);
17220   bool checkAgainstTrue = false; // Is it a comparison against 1?
17221
17222   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17223     SetCC = Op2;
17224   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17225     SetCC = Op1;
17226   else // Quit if all operands are not constants.
17227     return SDValue();
17228
17229   if (C->getZExtValue() == 1) {
17230     needOppositeCond = !needOppositeCond;
17231     checkAgainstTrue = true;
17232   } else if (C->getZExtValue() != 0)
17233     // Quit if the constant is neither 0 or 1.
17234     return SDValue();
17235
17236   bool truncatedToBoolWithAnd = false;
17237   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17238   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17239          SetCC.getOpcode() == ISD::TRUNCATE ||
17240          SetCC.getOpcode() == ISD::AND) {
17241     if (SetCC.getOpcode() == ISD::AND) {
17242       int OpIdx = -1;
17243       ConstantSDNode *CS;
17244       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17245           CS->getZExtValue() == 1)
17246         OpIdx = 1;
17247       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17248           CS->getZExtValue() == 1)
17249         OpIdx = 0;
17250       if (OpIdx == -1)
17251         break;
17252       SetCC = SetCC.getOperand(OpIdx);
17253       truncatedToBoolWithAnd = true;
17254     } else
17255       SetCC = SetCC.getOperand(0);
17256   }
17257
17258   switch (SetCC.getOpcode()) {
17259   case X86ISD::SETCC_CARRY:
17260     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
17261     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
17262     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
17263     // truncated to i1 using 'and'.
17264     if (checkAgainstTrue && !truncatedToBoolWithAnd)
17265       break;
17266     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
17267            "Invalid use of SETCC_CARRY!");
17268     // FALL THROUGH
17269   case X86ISD::SETCC:
17270     // Set the condition code or opposite one if necessary.
17271     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
17272     if (needOppositeCond)
17273       CC = X86::GetOppositeBranchCondition(CC);
17274     return SetCC.getOperand(1);
17275   case X86ISD::CMOV: {
17276     // Check whether false/true value has canonical one, i.e. 0 or 1.
17277     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
17278     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
17279     // Quit if true value is not a constant.
17280     if (!TVal)
17281       return SDValue();
17282     // Quit if false value is not a constant.
17283     if (!FVal) {
17284       SDValue Op = SetCC.getOperand(0);
17285       // Skip 'zext' or 'trunc' node.
17286       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
17287           Op.getOpcode() == ISD::TRUNCATE)
17288         Op = Op.getOperand(0);
17289       // A special case for rdrand/rdseed, where 0 is set if false cond is
17290       // found.
17291       if ((Op.getOpcode() != X86ISD::RDRAND &&
17292            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
17293         return SDValue();
17294     }
17295     // Quit if false value is not the constant 0 or 1.
17296     bool FValIsFalse = true;
17297     if (FVal && FVal->getZExtValue() != 0) {
17298       if (FVal->getZExtValue() != 1)
17299         return SDValue();
17300       // If FVal is 1, opposite cond is needed.
17301       needOppositeCond = !needOppositeCond;
17302       FValIsFalse = false;
17303     }
17304     // Quit if TVal is not the constant opposite of FVal.
17305     if (FValIsFalse && TVal->getZExtValue() != 1)
17306       return SDValue();
17307     if (!FValIsFalse && TVal->getZExtValue() != 0)
17308       return SDValue();
17309     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
17310     if (needOppositeCond)
17311       CC = X86::GetOppositeBranchCondition(CC);
17312     return SetCC.getOperand(3);
17313   }
17314   }
17315
17316   return SDValue();
17317 }
17318
17319 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
17320 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
17321                                   TargetLowering::DAGCombinerInfo &DCI,
17322                                   const X86Subtarget *Subtarget) {
17323   SDLoc DL(N);
17324
17325   // If the flag operand isn't dead, don't touch this CMOV.
17326   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
17327     return SDValue();
17328
17329   SDValue FalseOp = N->getOperand(0);
17330   SDValue TrueOp = N->getOperand(1);
17331   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
17332   SDValue Cond = N->getOperand(3);
17333
17334   if (CC == X86::COND_E || CC == X86::COND_NE) {
17335     switch (Cond.getOpcode()) {
17336     default: break;
17337     case X86ISD::BSR:
17338     case X86ISD::BSF:
17339       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
17340       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
17341         return (CC == X86::COND_E) ? FalseOp : TrueOp;
17342     }
17343   }
17344
17345   SDValue Flags;
17346
17347   Flags = checkBoolTestSetCCCombine(Cond, CC);
17348   if (Flags.getNode() &&
17349       // Extra check as FCMOV only supports a subset of X86 cond.
17350       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
17351     SDValue Ops[] = { FalseOp, TrueOp,
17352                       DAG.getConstant(CC, MVT::i8), Flags };
17353     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
17354                        Ops, array_lengthof(Ops));
17355   }
17356
17357   // If this is a select between two integer constants, try to do some
17358   // optimizations.  Note that the operands are ordered the opposite of SELECT
17359   // operands.
17360   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
17361     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
17362       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
17363       // larger than FalseC (the false value).
17364       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
17365         CC = X86::GetOppositeBranchCondition(CC);
17366         std::swap(TrueC, FalseC);
17367         std::swap(TrueOp, FalseOp);
17368       }
17369
17370       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
17371       // This is efficient for any integer data type (including i8/i16) and
17372       // shift amount.
17373       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
17374         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17375                            DAG.getConstant(CC, MVT::i8), Cond);
17376
17377         // Zero extend the condition if needed.
17378         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
17379
17380         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17381         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
17382                            DAG.getConstant(ShAmt, MVT::i8));
17383         if (N->getNumValues() == 2)  // Dead flag value?
17384           return DCI.CombineTo(N, Cond, SDValue());
17385         return Cond;
17386       }
17387
17388       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
17389       // for any integer data type, including i8/i16.
17390       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17391         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17392                            DAG.getConstant(CC, MVT::i8), Cond);
17393
17394         // Zero extend the condition if needed.
17395         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17396                            FalseC->getValueType(0), Cond);
17397         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17398                            SDValue(FalseC, 0));
17399
17400         if (N->getNumValues() == 2)  // Dead flag value?
17401           return DCI.CombineTo(N, Cond, SDValue());
17402         return Cond;
17403       }
17404
17405       // Optimize cases that will turn into an LEA instruction.  This requires
17406       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17407       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17408         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17409         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17410
17411         bool isFastMultiplier = false;
17412         if (Diff < 10) {
17413           switch ((unsigned char)Diff) {
17414           default: break;
17415           case 1:  // result = add base, cond
17416           case 2:  // result = lea base(    , cond*2)
17417           case 3:  // result = lea base(cond, cond*2)
17418           case 4:  // result = lea base(    , cond*4)
17419           case 5:  // result = lea base(cond, cond*4)
17420           case 8:  // result = lea base(    , cond*8)
17421           case 9:  // result = lea base(cond, cond*8)
17422             isFastMultiplier = true;
17423             break;
17424           }
17425         }
17426
17427         if (isFastMultiplier) {
17428           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17429           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17430                              DAG.getConstant(CC, MVT::i8), Cond);
17431           // Zero extend the condition if needed.
17432           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17433                              Cond);
17434           // Scale the condition by the difference.
17435           if (Diff != 1)
17436             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17437                                DAG.getConstant(Diff, Cond.getValueType()));
17438
17439           // Add the base if non-zero.
17440           if (FalseC->getAPIntValue() != 0)
17441             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17442                                SDValue(FalseC, 0));
17443           if (N->getNumValues() == 2)  // Dead flag value?
17444             return DCI.CombineTo(N, Cond, SDValue());
17445           return Cond;
17446         }
17447       }
17448     }
17449   }
17450
17451   // Handle these cases:
17452   //   (select (x != c), e, c) -> select (x != c), e, x),
17453   //   (select (x == c), c, e) -> select (x == c), x, e)
17454   // where the c is an integer constant, and the "select" is the combination
17455   // of CMOV and CMP.
17456   //
17457   // The rationale for this change is that the conditional-move from a constant
17458   // needs two instructions, however, conditional-move from a register needs
17459   // only one instruction.
17460   //
17461   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
17462   //  some instruction-combining opportunities. This opt needs to be
17463   //  postponed as late as possible.
17464   //
17465   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
17466     // the DCI.xxxx conditions are provided to postpone the optimization as
17467     // late as possible.
17468
17469     ConstantSDNode *CmpAgainst = 0;
17470     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
17471         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
17472         !isa<ConstantSDNode>(Cond.getOperand(0))) {
17473
17474       if (CC == X86::COND_NE &&
17475           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
17476         CC = X86::GetOppositeBranchCondition(CC);
17477         std::swap(TrueOp, FalseOp);
17478       }
17479
17480       if (CC == X86::COND_E &&
17481           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
17482         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
17483                           DAG.getConstant(CC, MVT::i8), Cond };
17484         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
17485                            array_lengthof(Ops));
17486       }
17487     }
17488   }
17489
17490   return SDValue();
17491 }
17492
17493 /// PerformMulCombine - Optimize a single multiply with constant into two
17494 /// in order to implement it with two cheaper instructions, e.g.
17495 /// LEA + SHL, LEA + LEA.
17496 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
17497                                  TargetLowering::DAGCombinerInfo &DCI) {
17498   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17499     return SDValue();
17500
17501   EVT VT = N->getValueType(0);
17502   if (VT != MVT::i64)
17503     return SDValue();
17504
17505   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
17506   if (!C)
17507     return SDValue();
17508   uint64_t MulAmt = C->getZExtValue();
17509   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
17510     return SDValue();
17511
17512   uint64_t MulAmt1 = 0;
17513   uint64_t MulAmt2 = 0;
17514   if ((MulAmt % 9) == 0) {
17515     MulAmt1 = 9;
17516     MulAmt2 = MulAmt / 9;
17517   } else if ((MulAmt % 5) == 0) {
17518     MulAmt1 = 5;
17519     MulAmt2 = MulAmt / 5;
17520   } else if ((MulAmt % 3) == 0) {
17521     MulAmt1 = 3;
17522     MulAmt2 = MulAmt / 3;
17523   }
17524   if (MulAmt2 &&
17525       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
17526     SDLoc DL(N);
17527
17528     if (isPowerOf2_64(MulAmt2) &&
17529         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
17530       // If second multiplifer is pow2, issue it first. We want the multiply by
17531       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
17532       // is an add.
17533       std::swap(MulAmt1, MulAmt2);
17534
17535     SDValue NewMul;
17536     if (isPowerOf2_64(MulAmt1))
17537       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17538                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
17539     else
17540       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
17541                            DAG.getConstant(MulAmt1, VT));
17542
17543     if (isPowerOf2_64(MulAmt2))
17544       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
17545                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
17546     else
17547       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
17548                            DAG.getConstant(MulAmt2, VT));
17549
17550     // Do not add new nodes to DAG combiner worklist.
17551     DCI.CombineTo(N, NewMul, false);
17552   }
17553   return SDValue();
17554 }
17555
17556 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
17557   SDValue N0 = N->getOperand(0);
17558   SDValue N1 = N->getOperand(1);
17559   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
17560   EVT VT = N0.getValueType();
17561
17562   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
17563   // since the result of setcc_c is all zero's or all ones.
17564   if (VT.isInteger() && !VT.isVector() &&
17565       N1C && N0.getOpcode() == ISD::AND &&
17566       N0.getOperand(1).getOpcode() == ISD::Constant) {
17567     SDValue N00 = N0.getOperand(0);
17568     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
17569         ((N00.getOpcode() == ISD::ANY_EXTEND ||
17570           N00.getOpcode() == ISD::ZERO_EXTEND) &&
17571          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
17572       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
17573       APInt ShAmt = N1C->getAPIntValue();
17574       Mask = Mask.shl(ShAmt);
17575       if (Mask != 0)
17576         return DAG.getNode(ISD::AND, SDLoc(N), VT,
17577                            N00, DAG.getConstant(Mask, VT));
17578     }
17579   }
17580
17581   // Hardware support for vector shifts is sparse which makes us scalarize the
17582   // vector operations in many cases. Also, on sandybridge ADD is faster than
17583   // shl.
17584   // (shl V, 1) -> add V,V
17585   if (isSplatVector(N1.getNode())) {
17586     assert(N0.getValueType().isVector() && "Invalid vector shift type");
17587     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
17588     // We shift all of the values by one. In many cases we do not have
17589     // hardware support for this operation. This is better expressed as an ADD
17590     // of two values.
17591     if (N1C && (1 == N1C->getZExtValue())) {
17592       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
17593     }
17594   }
17595
17596   return SDValue();
17597 }
17598
17599 /// \brief Returns a vector of 0s if the node in input is a vector logical
17600 /// shift by a constant amount which is known to be bigger than or equal
17601 /// to the vector element size in bits.
17602 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
17603                                       const X86Subtarget *Subtarget) {
17604   EVT VT = N->getValueType(0);
17605
17606   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
17607       (!Subtarget->hasInt256() ||
17608        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
17609     return SDValue();
17610
17611   SDValue Amt = N->getOperand(1);
17612   SDLoc DL(N);
17613   if (isSplatVector(Amt.getNode())) {
17614     SDValue SclrAmt = Amt->getOperand(0);
17615     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
17616       APInt ShiftAmt = C->getAPIntValue();
17617       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
17618
17619       // SSE2/AVX2 logical shifts always return a vector of 0s
17620       // if the shift amount is bigger than or equal to
17621       // the element size. The constant shift amount will be
17622       // encoded as a 8-bit immediate.
17623       if (ShiftAmt.trunc(8).uge(MaxAmount))
17624         return getZeroVector(VT, Subtarget, DAG, DL);
17625     }
17626   }
17627
17628   return SDValue();
17629 }
17630
17631 /// PerformShiftCombine - Combine shifts.
17632 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
17633                                    TargetLowering::DAGCombinerInfo &DCI,
17634                                    const X86Subtarget *Subtarget) {
17635   if (N->getOpcode() == ISD::SHL) {
17636     SDValue V = PerformSHLCombine(N, DAG);
17637     if (V.getNode()) return V;
17638   }
17639
17640   if (N->getOpcode() != ISD::SRA) {
17641     // Try to fold this logical shift into a zero vector.
17642     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
17643     if (V.getNode()) return V;
17644   }
17645
17646   return SDValue();
17647 }
17648
17649 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
17650 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
17651 // and friends.  Likewise for OR -> CMPNEQSS.
17652 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
17653                             TargetLowering::DAGCombinerInfo &DCI,
17654                             const X86Subtarget *Subtarget) {
17655   unsigned opcode;
17656
17657   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
17658   // we're requiring SSE2 for both.
17659   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
17660     SDValue N0 = N->getOperand(0);
17661     SDValue N1 = N->getOperand(1);
17662     SDValue CMP0 = N0->getOperand(1);
17663     SDValue CMP1 = N1->getOperand(1);
17664     SDLoc DL(N);
17665
17666     // The SETCCs should both refer to the same CMP.
17667     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
17668       return SDValue();
17669
17670     SDValue CMP00 = CMP0->getOperand(0);
17671     SDValue CMP01 = CMP0->getOperand(1);
17672     EVT     VT    = CMP00.getValueType();
17673
17674     if (VT == MVT::f32 || VT == MVT::f64) {
17675       bool ExpectingFlags = false;
17676       // Check for any users that want flags:
17677       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
17678            !ExpectingFlags && UI != UE; ++UI)
17679         switch (UI->getOpcode()) {
17680         default:
17681         case ISD::BR_CC:
17682         case ISD::BRCOND:
17683         case ISD::SELECT:
17684           ExpectingFlags = true;
17685           break;
17686         case ISD::CopyToReg:
17687         case ISD::SIGN_EXTEND:
17688         case ISD::ZERO_EXTEND:
17689         case ISD::ANY_EXTEND:
17690           break;
17691         }
17692
17693       if (!ExpectingFlags) {
17694         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
17695         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
17696
17697         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
17698           X86::CondCode tmp = cc0;
17699           cc0 = cc1;
17700           cc1 = tmp;
17701         }
17702
17703         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
17704             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
17705           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
17706           // FIXME: need symbolic constants for these magic numbers.
17707           // See X86ATTInstPrinter.cpp:printSSECC().
17708           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17709           if (Subtarget->hasAVX512()) {
17710             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
17711                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
17712             if (N->getValueType(0) != MVT::i1)
17713               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
17714                                  FSetCC);
17715             return FSetCC;
17716           }
17717           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
17718                                               CMP00.getValueType(), CMP00, CMP01,
17719                                               DAG.getConstant(x86cc, MVT::i8));
17720           MVT IntVT = (is64BitFP ? MVT::i64 : MVT::i32); 
17721           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
17722                                               OnesOrZeroesF);
17723           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
17724                                       DAG.getConstant(1, IntVT));
17725           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17726           return OneBitOfTruth;
17727         }
17728       }
17729     }
17730   }
17731   return SDValue();
17732 }
17733
17734 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17735 /// so it can be folded inside ANDNP.
17736 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17737   EVT VT = N->getValueType(0);
17738
17739   // Match direct AllOnes for 128 and 256-bit vectors
17740   if (ISD::isBuildVectorAllOnes(N))
17741     return true;
17742
17743   // Look through a bit convert.
17744   if (N->getOpcode() == ISD::BITCAST)
17745     N = N->getOperand(0).getNode();
17746
17747   // Sometimes the operand may come from a insert_subvector building a 256-bit
17748   // allones vector
17749   if (VT.is256BitVector() &&
17750       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17751     SDValue V1 = N->getOperand(0);
17752     SDValue V2 = N->getOperand(1);
17753
17754     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17755         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17756         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17757         ISD::isBuildVectorAllOnes(V2.getNode()))
17758       return true;
17759   }
17760
17761   return false;
17762 }
17763
17764 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17765 // register. In most cases we actually compare or select YMM-sized registers
17766 // and mixing the two types creates horrible code. This method optimizes
17767 // some of the transition sequences.
17768 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17769                                  TargetLowering::DAGCombinerInfo &DCI,
17770                                  const X86Subtarget *Subtarget) {
17771   EVT VT = N->getValueType(0);
17772   if (!VT.is256BitVector())
17773     return SDValue();
17774
17775   assert((N->getOpcode() == ISD::ANY_EXTEND ||
17776           N->getOpcode() == ISD::ZERO_EXTEND ||
17777           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17778
17779   SDValue Narrow = N->getOperand(0);
17780   EVT NarrowVT = Narrow->getValueType(0);
17781   if (!NarrowVT.is128BitVector())
17782     return SDValue();
17783
17784   if (Narrow->getOpcode() != ISD::XOR &&
17785       Narrow->getOpcode() != ISD::AND &&
17786       Narrow->getOpcode() != ISD::OR)
17787     return SDValue();
17788
17789   SDValue N0  = Narrow->getOperand(0);
17790   SDValue N1  = Narrow->getOperand(1);
17791   SDLoc DL(Narrow);
17792
17793   // The Left side has to be a trunc.
17794   if (N0.getOpcode() != ISD::TRUNCATE)
17795     return SDValue();
17796
17797   // The type of the truncated inputs.
17798   EVT WideVT = N0->getOperand(0)->getValueType(0);
17799   if (WideVT != VT)
17800     return SDValue();
17801
17802   // The right side has to be a 'trunc' or a constant vector.
17803   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17804   bool RHSConst = (isSplatVector(N1.getNode()) &&
17805                    isa<ConstantSDNode>(N1->getOperand(0)));
17806   if (!RHSTrunc && !RHSConst)
17807     return SDValue();
17808
17809   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17810
17811   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17812     return SDValue();
17813
17814   // Set N0 and N1 to hold the inputs to the new wide operation.
17815   N0 = N0->getOperand(0);
17816   if (RHSConst) {
17817     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17818                      N1->getOperand(0));
17819     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17820     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17821   } else if (RHSTrunc) {
17822     N1 = N1->getOperand(0);
17823   }
17824
17825   // Generate the wide operation.
17826   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17827   unsigned Opcode = N->getOpcode();
17828   switch (Opcode) {
17829   case ISD::ANY_EXTEND:
17830     return Op;
17831   case ISD::ZERO_EXTEND: {
17832     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17833     APInt Mask = APInt::getAllOnesValue(InBits);
17834     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17835     return DAG.getNode(ISD::AND, DL, VT,
17836                        Op, DAG.getConstant(Mask, VT));
17837   }
17838   case ISD::SIGN_EXTEND:
17839     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17840                        Op, DAG.getValueType(NarrowVT));
17841   default:
17842     llvm_unreachable("Unexpected opcode");
17843   }
17844 }
17845
17846 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17847                                  TargetLowering::DAGCombinerInfo &DCI,
17848                                  const X86Subtarget *Subtarget) {
17849   EVT VT = N->getValueType(0);
17850   if (DCI.isBeforeLegalizeOps())
17851     return SDValue();
17852
17853   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17854   if (R.getNode())
17855     return R;
17856
17857   // Create BLSI, BLSR, and BZHI instructions
17858   // BLSI is X & (-X)
17859   // BLSR is X & (X-1)
17860   // BZHI is X & ((1 << Y) - 1)
17861   // BEXTR is ((X >> imm) & (2**size-1))
17862   if (VT == MVT::i32 || VT == MVT::i64) {
17863     SDValue N0 = N->getOperand(0);
17864     SDValue N1 = N->getOperand(1);
17865     SDLoc DL(N);
17866
17867     if (Subtarget->hasBMI()) {
17868       // Check LHS for neg
17869       if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17870           isZero(N0.getOperand(0)))
17871         return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17872
17873       // Check RHS for neg
17874       if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17875           isZero(N1.getOperand(0)))
17876         return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17877
17878       // Check LHS for X-1
17879       if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17880           isAllOnes(N0.getOperand(1)))
17881         return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17882
17883       // Check RHS for X-1
17884       if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17885           isAllOnes(N1.getOperand(1)))
17886         return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17887     }
17888
17889     if (Subtarget->hasBMI2()) {
17890       // Check for (and (add (shl 1, Y), -1), X)
17891       if (N0.getOpcode() == ISD::ADD && isAllOnes(N0.getOperand(1))) {
17892         SDValue N00 = N0.getOperand(0);
17893         if (N00.getOpcode() == ISD::SHL) {
17894           SDValue N001 = N00.getOperand(1);
17895           assert(N001.getValueType() == MVT::i8 && "unexpected type");
17896           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N00.getOperand(0));
17897           if (C && C->getZExtValue() == 1)
17898             return DAG.getNode(X86ISD::BZHI, DL, VT, N1, N001);
17899         }
17900       }
17901
17902       // Check for (and X, (add (shl 1, Y), -1))
17903       if (N1.getOpcode() == ISD::ADD && isAllOnes(N1.getOperand(1))) {
17904         SDValue N10 = N1.getOperand(0);
17905         if (N10.getOpcode() == ISD::SHL) {
17906           SDValue N101 = N10.getOperand(1);
17907           assert(N101.getValueType() == MVT::i8 && "unexpected type");
17908           ConstantSDNode *C = dyn_cast<ConstantSDNode>(N10.getOperand(0));
17909           if (C && C->getZExtValue() == 1)
17910             return DAG.getNode(X86ISD::BZHI, DL, VT, N0, N101);
17911         }
17912       }
17913     }
17914
17915     // Check for BEXTR.
17916     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
17917         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
17918       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
17919       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17920       if (MaskNode && ShiftNode) {
17921         uint64_t Mask = MaskNode->getZExtValue();
17922         uint64_t Shift = ShiftNode->getZExtValue();
17923         if (isMask_64(Mask)) {
17924           uint64_t MaskSize = CountPopulation_64(Mask);
17925           if (Shift + MaskSize <= VT.getSizeInBits())
17926             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
17927                                DAG.getConstant(Shift | (MaskSize << 8), VT));
17928         }
17929       }
17930     } // BEXTR
17931
17932     return SDValue();
17933   }
17934
17935   // Want to form ANDNP nodes:
17936   // 1) In the hopes of then easily combining them with OR and AND nodes
17937   //    to form PBLEND/PSIGN.
17938   // 2) To match ANDN packed intrinsics
17939   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17940     return SDValue();
17941
17942   SDValue N0 = N->getOperand(0);
17943   SDValue N1 = N->getOperand(1);
17944   SDLoc DL(N);
17945
17946   // Check LHS for vnot
17947   if (N0.getOpcode() == ISD::XOR &&
17948       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17949       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17950     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17951
17952   // Check RHS for vnot
17953   if (N1.getOpcode() == ISD::XOR &&
17954       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17955       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17956     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17957
17958   return SDValue();
17959 }
17960
17961 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17962                                 TargetLowering::DAGCombinerInfo &DCI,
17963                                 const X86Subtarget *Subtarget) {
17964   EVT VT = N->getValueType(0);
17965   if (DCI.isBeforeLegalizeOps())
17966     return SDValue();
17967
17968   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17969   if (R.getNode())
17970     return R;
17971
17972   SDValue N0 = N->getOperand(0);
17973   SDValue N1 = N->getOperand(1);
17974
17975   // look for psign/blend
17976   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17977     if (!Subtarget->hasSSSE3() ||
17978         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17979       return SDValue();
17980
17981     // Canonicalize pandn to RHS
17982     if (N0.getOpcode() == X86ISD::ANDNP)
17983       std::swap(N0, N1);
17984     // or (and (m, y), (pandn m, x))
17985     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17986       SDValue Mask = N1.getOperand(0);
17987       SDValue X    = N1.getOperand(1);
17988       SDValue Y;
17989       if (N0.getOperand(0) == Mask)
17990         Y = N0.getOperand(1);
17991       if (N0.getOperand(1) == Mask)
17992         Y = N0.getOperand(0);
17993
17994       // Check to see if the mask appeared in both the AND and ANDNP and
17995       if (!Y.getNode())
17996         return SDValue();
17997
17998       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17999       // Look through mask bitcast.
18000       if (Mask.getOpcode() == ISD::BITCAST)
18001         Mask = Mask.getOperand(0);
18002       if (X.getOpcode() == ISD::BITCAST)
18003         X = X.getOperand(0);
18004       if (Y.getOpcode() == ISD::BITCAST)
18005         Y = Y.getOperand(0);
18006
18007       EVT MaskVT = Mask.getValueType();
18008
18009       // Validate that the Mask operand is a vector sra node.
18010       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18011       // there is no psrai.b
18012       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18013       unsigned SraAmt = ~0;
18014       if (Mask.getOpcode() == ISD::SRA) {
18015         SDValue Amt = Mask.getOperand(1);
18016         if (isSplatVector(Amt.getNode())) {
18017           SDValue SclrAmt = Amt->getOperand(0);
18018           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18019             SraAmt = C->getZExtValue();
18020         }
18021       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18022         SDValue SraC = Mask.getOperand(1);
18023         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18024       }
18025       if ((SraAmt + 1) != EltBits)
18026         return SDValue();
18027
18028       SDLoc DL(N);
18029
18030       // Now we know we at least have a plendvb with the mask val.  See if
18031       // we can form a psignb/w/d.
18032       // psign = x.type == y.type == mask.type && y = sub(0, x);
18033       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18034           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18035           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18036         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18037                "Unsupported VT for PSIGN");
18038         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18039         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18040       }
18041       // PBLENDVB only available on SSE 4.1
18042       if (!Subtarget->hasSSE41())
18043         return SDValue();
18044
18045       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18046
18047       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18048       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18049       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18050       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18051       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18052     }
18053   }
18054
18055   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18056     return SDValue();
18057
18058   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18059   MachineFunction &MF = DAG.getMachineFunction();
18060   bool OptForSize = MF.getFunction()->getAttributes().
18061     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18062
18063   // SHLD/SHRD instructions have lower register pressure, but on some
18064   // platforms they have higher latency than the equivalent
18065   // series of shifts/or that would otherwise be generated.
18066   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18067   // have higher latencies and we are not optimizing for size.
18068   if (!OptForSize && Subtarget->isSHLDSlow())
18069     return SDValue();
18070
18071   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18072     std::swap(N0, N1);
18073   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18074     return SDValue();
18075   if (!N0.hasOneUse() || !N1.hasOneUse())
18076     return SDValue();
18077
18078   SDValue ShAmt0 = N0.getOperand(1);
18079   if (ShAmt0.getValueType() != MVT::i8)
18080     return SDValue();
18081   SDValue ShAmt1 = N1.getOperand(1);
18082   if (ShAmt1.getValueType() != MVT::i8)
18083     return SDValue();
18084   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18085     ShAmt0 = ShAmt0.getOperand(0);
18086   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18087     ShAmt1 = ShAmt1.getOperand(0);
18088
18089   SDLoc DL(N);
18090   unsigned Opc = X86ISD::SHLD;
18091   SDValue Op0 = N0.getOperand(0);
18092   SDValue Op1 = N1.getOperand(0);
18093   if (ShAmt0.getOpcode() == ISD::SUB) {
18094     Opc = X86ISD::SHRD;
18095     std::swap(Op0, Op1);
18096     std::swap(ShAmt0, ShAmt1);
18097   }
18098
18099   unsigned Bits = VT.getSizeInBits();
18100   if (ShAmt1.getOpcode() == ISD::SUB) {
18101     SDValue Sum = ShAmt1.getOperand(0);
18102     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18103       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18104       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18105         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18106       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18107         return DAG.getNode(Opc, DL, VT,
18108                            Op0, Op1,
18109                            DAG.getNode(ISD::TRUNCATE, DL,
18110                                        MVT::i8, ShAmt0));
18111     }
18112   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18113     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18114     if (ShAmt0C &&
18115         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18116       return DAG.getNode(Opc, DL, VT,
18117                          N0.getOperand(0), N1.getOperand(0),
18118                          DAG.getNode(ISD::TRUNCATE, DL,
18119                                        MVT::i8, ShAmt0));
18120   }
18121
18122   return SDValue();
18123 }
18124
18125 // Generate NEG and CMOV for integer abs.
18126 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18127   EVT VT = N->getValueType(0);
18128
18129   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18130   // 8-bit integer abs to NEG and CMOV.
18131   if (VT.isInteger() && VT.getSizeInBits() == 8)
18132     return SDValue();
18133
18134   SDValue N0 = N->getOperand(0);
18135   SDValue N1 = N->getOperand(1);
18136   SDLoc DL(N);
18137
18138   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18139   // and change it to SUB and CMOV.
18140   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18141       N0.getOpcode() == ISD::ADD &&
18142       N0.getOperand(1) == N1 &&
18143       N1.getOpcode() == ISD::SRA &&
18144       N1.getOperand(0) == N0.getOperand(0))
18145     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18146       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18147         // Generate SUB & CMOV.
18148         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18149                                   DAG.getConstant(0, VT), N0.getOperand(0));
18150
18151         SDValue Ops[] = { N0.getOperand(0), Neg,
18152                           DAG.getConstant(X86::COND_GE, MVT::i8),
18153                           SDValue(Neg.getNode(), 1) };
18154         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
18155                            Ops, array_lengthof(Ops));
18156       }
18157   return SDValue();
18158 }
18159
18160 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18161 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18162                                  TargetLowering::DAGCombinerInfo &DCI,
18163                                  const X86Subtarget *Subtarget) {
18164   EVT VT = N->getValueType(0);
18165   if (DCI.isBeforeLegalizeOps())
18166     return SDValue();
18167
18168   if (Subtarget->hasCMov()) {
18169     SDValue RV = performIntegerAbsCombine(N, DAG);
18170     if (RV.getNode())
18171       return RV;
18172   }
18173
18174   // Try forming BMI if it is available.
18175   if (!Subtarget->hasBMI())
18176     return SDValue();
18177
18178   if (VT != MVT::i32 && VT != MVT::i64)
18179     return SDValue();
18180
18181   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
18182
18183   // Create BLSMSK instructions by finding X ^ (X-1)
18184   SDValue N0 = N->getOperand(0);
18185   SDValue N1 = N->getOperand(1);
18186   SDLoc DL(N);
18187
18188   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
18189       isAllOnes(N0.getOperand(1)))
18190     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
18191
18192   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
18193       isAllOnes(N1.getOperand(1)))
18194     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
18195
18196   return SDValue();
18197 }
18198
18199 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18200 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18201                                   TargetLowering::DAGCombinerInfo &DCI,
18202                                   const X86Subtarget *Subtarget) {
18203   LoadSDNode *Ld = cast<LoadSDNode>(N);
18204   EVT RegVT = Ld->getValueType(0);
18205   EVT MemVT = Ld->getMemoryVT();
18206   SDLoc dl(Ld);
18207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18208   unsigned RegSz = RegVT.getSizeInBits();
18209
18210   // On Sandybridge unaligned 256bit loads are inefficient.
18211   ISD::LoadExtType Ext = Ld->getExtensionType();
18212   unsigned Alignment = Ld->getAlignment();
18213   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18214   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18215       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18216     unsigned NumElems = RegVT.getVectorNumElements();
18217     if (NumElems < 2)
18218       return SDValue();
18219
18220     SDValue Ptr = Ld->getBasePtr();
18221     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18222
18223     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18224                                   NumElems/2);
18225     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18226                                 Ld->getPointerInfo(), Ld->isVolatile(),
18227                                 Ld->isNonTemporal(), Ld->isInvariant(),
18228                                 Alignment);
18229     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18230     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18231                                 Ld->getPointerInfo(), Ld->isVolatile(),
18232                                 Ld->isNonTemporal(), Ld->isInvariant(),
18233                                 std::min(16U, Alignment));
18234     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18235                              Load1.getValue(1),
18236                              Load2.getValue(1));
18237
18238     SDValue NewVec = DAG.getUNDEF(RegVT);
18239     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18240     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18241     return DCI.CombineTo(N, NewVec, TF, true);
18242   }
18243
18244   // If this is a vector EXT Load then attempt to optimize it using a
18245   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18246   // expansion is still better than scalar code.
18247   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18248   // emit a shuffle and a arithmetic shift.
18249   // TODO: It is possible to support ZExt by zeroing the undef values
18250   // during the shuffle phase or after the shuffle.
18251   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18252       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18253     assert(MemVT != RegVT && "Cannot extend to the same type");
18254     assert(MemVT.isVector() && "Must load a vector from memory");
18255
18256     unsigned NumElems = RegVT.getVectorNumElements();
18257     unsigned MemSz = MemVT.getSizeInBits();
18258     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18259
18260     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18261       return SDValue();
18262
18263     // All sizes must be a power of two.
18264     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18265       return SDValue();
18266
18267     // Attempt to load the original value using scalar loads.
18268     // Find the largest scalar type that divides the total loaded size.
18269     MVT SclrLoadTy = MVT::i8;
18270     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18271          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18272       MVT Tp = (MVT::SimpleValueType)tp;
18273       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18274         SclrLoadTy = Tp;
18275       }
18276     }
18277
18278     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18279     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18280         (64 <= MemSz))
18281       SclrLoadTy = MVT::f64;
18282
18283     // Calculate the number of scalar loads that we need to perform
18284     // in order to load our vector from memory.
18285     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18286     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18287       return SDValue();
18288
18289     unsigned loadRegZize = RegSz;
18290     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18291       loadRegZize /= 2;
18292
18293     // Represent our vector as a sequence of elements which are the
18294     // largest scalar that we can load.
18295     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18296       loadRegZize/SclrLoadTy.getSizeInBits());
18297
18298     // Represent the data using the same element type that is stored in
18299     // memory. In practice, we ''widen'' MemVT.
18300     EVT WideVecVT =
18301           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18302                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18303
18304     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18305       "Invalid vector type");
18306
18307     // We can't shuffle using an illegal type.
18308     if (!TLI.isTypeLegal(WideVecVT))
18309       return SDValue();
18310
18311     SmallVector<SDValue, 8> Chains;
18312     SDValue Ptr = Ld->getBasePtr();
18313     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
18314                                         TLI.getPointerTy());
18315     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
18316
18317     for (unsigned i = 0; i < NumLoads; ++i) {
18318       // Perform a single load.
18319       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
18320                                        Ptr, Ld->getPointerInfo(),
18321                                        Ld->isVolatile(), Ld->isNonTemporal(),
18322                                        Ld->isInvariant(), Ld->getAlignment());
18323       Chains.push_back(ScalarLoad.getValue(1));
18324       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
18325       // another round of DAGCombining.
18326       if (i == 0)
18327         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
18328       else
18329         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
18330                           ScalarLoad, DAG.getIntPtrConstant(i));
18331
18332       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18333     }
18334
18335     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18336                                Chains.size());
18337
18338     // Bitcast the loaded value to a vector of the original element type, in
18339     // the size of the target vector type.
18340     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
18341     unsigned SizeRatio = RegSz/MemSz;
18342
18343     if (Ext == ISD::SEXTLOAD) {
18344       // If we have SSE4.1 we can directly emit a VSEXT node.
18345       if (Subtarget->hasSSE41()) {
18346         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
18347         return DCI.CombineTo(N, Sext, TF, true);
18348       }
18349
18350       // Otherwise we'll shuffle the small elements in the high bits of the
18351       // larger type and perform an arithmetic shift. If the shift is not legal
18352       // it's better to scalarize.
18353       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
18354         return SDValue();
18355
18356       // Redistribute the loaded elements into the different locations.
18357       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18358       for (unsigned i = 0; i != NumElems; ++i)
18359         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
18360
18361       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18362                                            DAG.getUNDEF(WideVecVT),
18363                                            &ShuffleVec[0]);
18364
18365       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18366
18367       // Build the arithmetic shift.
18368       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
18369                      MemVT.getVectorElementType().getSizeInBits();
18370       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
18371                           DAG.getConstant(Amt, RegVT));
18372
18373       return DCI.CombineTo(N, Shuff, TF, true);
18374     }
18375
18376     // Redistribute the loaded elements into the different locations.
18377     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18378     for (unsigned i = 0; i != NumElems; ++i)
18379       ShuffleVec[i*SizeRatio] = i;
18380
18381     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
18382                                          DAG.getUNDEF(WideVecVT),
18383                                          &ShuffleVec[0]);
18384
18385     // Bitcast to the requested type.
18386     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
18387     // Replace the original load with the new sequence
18388     // and return the new chain.
18389     return DCI.CombineTo(N, Shuff, TF, true);
18390   }
18391
18392   return SDValue();
18393 }
18394
18395 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
18396 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
18397                                    const X86Subtarget *Subtarget) {
18398   StoreSDNode *St = cast<StoreSDNode>(N);
18399   EVT VT = St->getValue().getValueType();
18400   EVT StVT = St->getMemoryVT();
18401   SDLoc dl(St);
18402   SDValue StoredVal = St->getOperand(1);
18403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18404
18405   // If we are saving a concatenation of two XMM registers, perform two stores.
18406   // On Sandy Bridge, 256-bit memory operations are executed by two
18407   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
18408   // memory  operation.
18409   unsigned Alignment = St->getAlignment();
18410   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
18411   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
18412       StVT == VT && !IsAligned) {
18413     unsigned NumElems = VT.getVectorNumElements();
18414     if (NumElems < 2)
18415       return SDValue();
18416
18417     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
18418     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
18419
18420     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
18421     SDValue Ptr0 = St->getBasePtr();
18422     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
18423
18424     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
18425                                 St->getPointerInfo(), St->isVolatile(),
18426                                 St->isNonTemporal(), Alignment);
18427     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
18428                                 St->getPointerInfo(), St->isVolatile(),
18429                                 St->isNonTemporal(),
18430                                 std::min(16U, Alignment));
18431     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
18432   }
18433
18434   // Optimize trunc store (of multiple scalars) to shuffle and store.
18435   // First, pack all of the elements in one place. Next, store to memory
18436   // in fewer chunks.
18437   if (St->isTruncatingStore() && VT.isVector()) {
18438     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18439     unsigned NumElems = VT.getVectorNumElements();
18440     assert(StVT != VT && "Cannot truncate to the same type");
18441     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
18442     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
18443
18444     // From, To sizes and ElemCount must be pow of two
18445     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
18446     // We are going to use the original vector elt for storing.
18447     // Accumulated smaller vector elements must be a multiple of the store size.
18448     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
18449
18450     unsigned SizeRatio  = FromSz / ToSz;
18451
18452     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
18453
18454     // Create a type on which we perform the shuffle
18455     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
18456             StVT.getScalarType(), NumElems*SizeRatio);
18457
18458     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
18459
18460     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
18461     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
18462     for (unsigned i = 0; i != NumElems; ++i)
18463       ShuffleVec[i] = i * SizeRatio;
18464
18465     // Can't shuffle using an illegal type.
18466     if (!TLI.isTypeLegal(WideVecVT))
18467       return SDValue();
18468
18469     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
18470                                          DAG.getUNDEF(WideVecVT),
18471                                          &ShuffleVec[0]);
18472     // At this point all of the data is stored at the bottom of the
18473     // register. We now need to save it to mem.
18474
18475     // Find the largest store unit
18476     MVT StoreType = MVT::i8;
18477     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18478          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18479       MVT Tp = (MVT::SimpleValueType)tp;
18480       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
18481         StoreType = Tp;
18482     }
18483
18484     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18485     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
18486         (64 <= NumElems * ToSz))
18487       StoreType = MVT::f64;
18488
18489     // Bitcast the original vector into a vector of store-size units
18490     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
18491             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
18492     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
18493     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
18494     SmallVector<SDValue, 8> Chains;
18495     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
18496                                         TLI.getPointerTy());
18497     SDValue Ptr = St->getBasePtr();
18498
18499     // Perform one or more big stores into memory.
18500     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
18501       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
18502                                    StoreType, ShuffWide,
18503                                    DAG.getIntPtrConstant(i));
18504       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
18505                                 St->getPointerInfo(), St->isVolatile(),
18506                                 St->isNonTemporal(), St->getAlignment());
18507       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18508       Chains.push_back(Ch);
18509     }
18510
18511     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
18512                                Chains.size());
18513   }
18514
18515   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
18516   // the FP state in cases where an emms may be missing.
18517   // A preferable solution to the general problem is to figure out the right
18518   // places to insert EMMS.  This qualifies as a quick hack.
18519
18520   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
18521   if (VT.getSizeInBits() != 64)
18522     return SDValue();
18523
18524   const Function *F = DAG.getMachineFunction().getFunction();
18525   bool NoImplicitFloatOps = F->getAttributes().
18526     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
18527   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
18528                      && Subtarget->hasSSE2();
18529   if ((VT.isVector() ||
18530        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
18531       isa<LoadSDNode>(St->getValue()) &&
18532       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
18533       St->getChain().hasOneUse() && !St->isVolatile()) {
18534     SDNode* LdVal = St->getValue().getNode();
18535     LoadSDNode *Ld = 0;
18536     int TokenFactorIndex = -1;
18537     SmallVector<SDValue, 8> Ops;
18538     SDNode* ChainVal = St->getChain().getNode();
18539     // Must be a store of a load.  We currently handle two cases:  the load
18540     // is a direct child, and it's under an intervening TokenFactor.  It is
18541     // possible to dig deeper under nested TokenFactors.
18542     if (ChainVal == LdVal)
18543       Ld = cast<LoadSDNode>(St->getChain());
18544     else if (St->getValue().hasOneUse() &&
18545              ChainVal->getOpcode() == ISD::TokenFactor) {
18546       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
18547         if (ChainVal->getOperand(i).getNode() == LdVal) {
18548           TokenFactorIndex = i;
18549           Ld = cast<LoadSDNode>(St->getValue());
18550         } else
18551           Ops.push_back(ChainVal->getOperand(i));
18552       }
18553     }
18554
18555     if (!Ld || !ISD::isNormalLoad(Ld))
18556       return SDValue();
18557
18558     // If this is not the MMX case, i.e. we are just turning i64 load/store
18559     // into f64 load/store, avoid the transformation if there are multiple
18560     // uses of the loaded value.
18561     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
18562       return SDValue();
18563
18564     SDLoc LdDL(Ld);
18565     SDLoc StDL(N);
18566     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
18567     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
18568     // pair instead.
18569     if (Subtarget->is64Bit() || F64IsLegal) {
18570       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
18571       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
18572                                   Ld->getPointerInfo(), Ld->isVolatile(),
18573                                   Ld->isNonTemporal(), Ld->isInvariant(),
18574                                   Ld->getAlignment());
18575       SDValue NewChain = NewLd.getValue(1);
18576       if (TokenFactorIndex != -1) {
18577         Ops.push_back(NewChain);
18578         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18579                                Ops.size());
18580       }
18581       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
18582                           St->getPointerInfo(),
18583                           St->isVolatile(), St->isNonTemporal(),
18584                           St->getAlignment());
18585     }
18586
18587     // Otherwise, lower to two pairs of 32-bit loads / stores.
18588     SDValue LoAddr = Ld->getBasePtr();
18589     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
18590                                  DAG.getConstant(4, MVT::i32));
18591
18592     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
18593                                Ld->getPointerInfo(),
18594                                Ld->isVolatile(), Ld->isNonTemporal(),
18595                                Ld->isInvariant(), Ld->getAlignment());
18596     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
18597                                Ld->getPointerInfo().getWithOffset(4),
18598                                Ld->isVolatile(), Ld->isNonTemporal(),
18599                                Ld->isInvariant(),
18600                                MinAlign(Ld->getAlignment(), 4));
18601
18602     SDValue NewChain = LoLd.getValue(1);
18603     if (TokenFactorIndex != -1) {
18604       Ops.push_back(LoLd);
18605       Ops.push_back(HiLd);
18606       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
18607                              Ops.size());
18608     }
18609
18610     LoAddr = St->getBasePtr();
18611     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
18612                          DAG.getConstant(4, MVT::i32));
18613
18614     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
18615                                 St->getPointerInfo(),
18616                                 St->isVolatile(), St->isNonTemporal(),
18617                                 St->getAlignment());
18618     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
18619                                 St->getPointerInfo().getWithOffset(4),
18620                                 St->isVolatile(),
18621                                 St->isNonTemporal(),
18622                                 MinAlign(St->getAlignment(), 4));
18623     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
18624   }
18625   return SDValue();
18626 }
18627
18628 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
18629 /// and return the operands for the horizontal operation in LHS and RHS.  A
18630 /// horizontal operation performs the binary operation on successive elements
18631 /// of its first operand, then on successive elements of its second operand,
18632 /// returning the resulting values in a vector.  For example, if
18633 ///   A = < float a0, float a1, float a2, float a3 >
18634 /// and
18635 ///   B = < float b0, float b1, float b2, float b3 >
18636 /// then the result of doing a horizontal operation on A and B is
18637 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
18638 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
18639 /// A horizontal-op B, for some already available A and B, and if so then LHS is
18640 /// set to A, RHS to B, and the routine returns 'true'.
18641 /// Note that the binary operation should have the property that if one of the
18642 /// operands is UNDEF then the result is UNDEF.
18643 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
18644   // Look for the following pattern: if
18645   //   A = < float a0, float a1, float a2, float a3 >
18646   //   B = < float b0, float b1, float b2, float b3 >
18647   // and
18648   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
18649   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
18650   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
18651   // which is A horizontal-op B.
18652
18653   // At least one of the operands should be a vector shuffle.
18654   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
18655       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
18656     return false;
18657
18658   MVT VT = LHS.getSimpleValueType();
18659
18660   assert((VT.is128BitVector() || VT.is256BitVector()) &&
18661          "Unsupported vector type for horizontal add/sub");
18662
18663   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
18664   // operate independently on 128-bit lanes.
18665   unsigned NumElts = VT.getVectorNumElements();
18666   unsigned NumLanes = VT.getSizeInBits()/128;
18667   unsigned NumLaneElts = NumElts / NumLanes;
18668   assert((NumLaneElts % 2 == 0) &&
18669          "Vector type should have an even number of elements in each lane");
18670   unsigned HalfLaneElts = NumLaneElts/2;
18671
18672   // View LHS in the form
18673   //   LHS = VECTOR_SHUFFLE A, B, LMask
18674   // If LHS is not a shuffle then pretend it is the shuffle
18675   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
18676   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
18677   // type VT.
18678   SDValue A, B;
18679   SmallVector<int, 16> LMask(NumElts);
18680   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18681     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
18682       A = LHS.getOperand(0);
18683     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
18684       B = LHS.getOperand(1);
18685     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
18686     std::copy(Mask.begin(), Mask.end(), LMask.begin());
18687   } else {
18688     if (LHS.getOpcode() != ISD::UNDEF)
18689       A = LHS;
18690     for (unsigned i = 0; i != NumElts; ++i)
18691       LMask[i] = i;
18692   }
18693
18694   // Likewise, view RHS in the form
18695   //   RHS = VECTOR_SHUFFLE C, D, RMask
18696   SDValue C, D;
18697   SmallVector<int, 16> RMask(NumElts);
18698   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
18699     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
18700       C = RHS.getOperand(0);
18701     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
18702       D = RHS.getOperand(1);
18703     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
18704     std::copy(Mask.begin(), Mask.end(), RMask.begin());
18705   } else {
18706     if (RHS.getOpcode() != ISD::UNDEF)
18707       C = RHS;
18708     for (unsigned i = 0; i != NumElts; ++i)
18709       RMask[i] = i;
18710   }
18711
18712   // Check that the shuffles are both shuffling the same vectors.
18713   if (!(A == C && B == D) && !(A == D && B == C))
18714     return false;
18715
18716   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
18717   if (!A.getNode() && !B.getNode())
18718     return false;
18719
18720   // If A and B occur in reverse order in RHS, then "swap" them (which means
18721   // rewriting the mask).
18722   if (A != C)
18723     CommuteVectorShuffleMask(RMask, NumElts);
18724
18725   // At this point LHS and RHS are equivalent to
18726   //   LHS = VECTOR_SHUFFLE A, B, LMask
18727   //   RHS = VECTOR_SHUFFLE A, B, RMask
18728   // Check that the masks correspond to performing a horizontal operation.
18729   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
18730     for (unsigned i = 0; i != NumLaneElts; ++i) {
18731       int LIdx = LMask[i+l], RIdx = RMask[i+l];
18732
18733       // Ignore any UNDEF components.
18734       if (LIdx < 0 || RIdx < 0 ||
18735           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
18736           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
18737         continue;
18738
18739       // Check that successive elements are being operated on.  If not, this is
18740       // not a horizontal operation.
18741       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
18742       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
18743       if (!(LIdx == Index && RIdx == Index + 1) &&
18744           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
18745         return false;
18746     }
18747   }
18748
18749   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
18750   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
18751   return true;
18752 }
18753
18754 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
18755 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
18756                                   const X86Subtarget *Subtarget) {
18757   EVT VT = N->getValueType(0);
18758   SDValue LHS = N->getOperand(0);
18759   SDValue RHS = N->getOperand(1);
18760
18761   // Try to synthesize horizontal adds from adds of shuffles.
18762   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18763        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18764       isHorizontalBinOp(LHS, RHS, true))
18765     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
18766   return SDValue();
18767 }
18768
18769 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
18770 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
18771                                   const X86Subtarget *Subtarget) {
18772   EVT VT = N->getValueType(0);
18773   SDValue LHS = N->getOperand(0);
18774   SDValue RHS = N->getOperand(1);
18775
18776   // Try to synthesize horizontal subs from subs of shuffles.
18777   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18778        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18779       isHorizontalBinOp(LHS, RHS, false))
18780     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18781   return SDValue();
18782 }
18783
18784 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18785 /// X86ISD::FXOR nodes.
18786 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18787   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18788   // F[X]OR(0.0, x) -> x
18789   // F[X]OR(x, 0.0) -> x
18790   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18791     if (C->getValueAPF().isPosZero())
18792       return N->getOperand(1);
18793   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18794     if (C->getValueAPF().isPosZero())
18795       return N->getOperand(0);
18796   return SDValue();
18797 }
18798
18799 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18800 /// X86ISD::FMAX nodes.
18801 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18802   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18803
18804   // Only perform optimizations if UnsafeMath is used.
18805   if (!DAG.getTarget().Options.UnsafeFPMath)
18806     return SDValue();
18807
18808   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18809   // into FMINC and FMAXC, which are Commutative operations.
18810   unsigned NewOp = 0;
18811   switch (N->getOpcode()) {
18812     default: llvm_unreachable("unknown opcode");
18813     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
18814     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
18815   }
18816
18817   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18818                      N->getOperand(0), N->getOperand(1));
18819 }
18820
18821 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18822 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18823   // FAND(0.0, x) -> 0.0
18824   // FAND(x, 0.0) -> 0.0
18825   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18826     if (C->getValueAPF().isPosZero())
18827       return N->getOperand(0);
18828   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18829     if (C->getValueAPF().isPosZero())
18830       return N->getOperand(1);
18831   return SDValue();
18832 }
18833
18834 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18835 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18836   // FANDN(x, 0.0) -> 0.0
18837   // FANDN(0.0, x) -> x
18838   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18839     if (C->getValueAPF().isPosZero())
18840       return N->getOperand(1);
18841   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18842     if (C->getValueAPF().isPosZero())
18843       return N->getOperand(1);
18844   return SDValue();
18845 }
18846
18847 static SDValue PerformBTCombine(SDNode *N,
18848                                 SelectionDAG &DAG,
18849                                 TargetLowering::DAGCombinerInfo &DCI) {
18850   // BT ignores high bits in the bit index operand.
18851   SDValue Op1 = N->getOperand(1);
18852   if (Op1.hasOneUse()) {
18853     unsigned BitWidth = Op1.getValueSizeInBits();
18854     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18855     APInt KnownZero, KnownOne;
18856     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18857                                           !DCI.isBeforeLegalizeOps());
18858     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18859     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18860         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18861       DCI.CommitTargetLoweringOpt(TLO);
18862   }
18863   return SDValue();
18864 }
18865
18866 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18867   SDValue Op = N->getOperand(0);
18868   if (Op.getOpcode() == ISD::BITCAST)
18869     Op = Op.getOperand(0);
18870   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18871   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18872       VT.getVectorElementType().getSizeInBits() ==
18873       OpVT.getVectorElementType().getSizeInBits()) {
18874     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18875   }
18876   return SDValue();
18877 }
18878
18879 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18880                                                const X86Subtarget *Subtarget) {
18881   EVT VT = N->getValueType(0);
18882   if (!VT.isVector())
18883     return SDValue();
18884
18885   SDValue N0 = N->getOperand(0);
18886   SDValue N1 = N->getOperand(1);
18887   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18888   SDLoc dl(N);
18889
18890   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18891   // both SSE and AVX2 since there is no sign-extended shift right
18892   // operation on a vector with 64-bit elements.
18893   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18894   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18895   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18896       N0.getOpcode() == ISD::SIGN_EXTEND)) {
18897     SDValue N00 = N0.getOperand(0);
18898
18899     // EXTLOAD has a better solution on AVX2,
18900     // it may be replaced with X86ISD::VSEXT node.
18901     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18902       if (!ISD::isNormalLoad(N00.getNode()))
18903         return SDValue();
18904
18905     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18906         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18907                                   N00, N1);
18908       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18909     }
18910   }
18911   return SDValue();
18912 }
18913
18914 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18915                                   TargetLowering::DAGCombinerInfo &DCI,
18916                                   const X86Subtarget *Subtarget) {
18917   if (!DCI.isBeforeLegalizeOps())
18918     return SDValue();
18919
18920   if (!Subtarget->hasFp256())
18921     return SDValue();
18922
18923   EVT VT = N->getValueType(0);
18924   if (VT.isVector() && VT.getSizeInBits() == 256) {
18925     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18926     if (R.getNode())
18927       return R;
18928   }
18929
18930   return SDValue();
18931 }
18932
18933 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18934                                  const X86Subtarget* Subtarget) {
18935   SDLoc dl(N);
18936   EVT VT = N->getValueType(0);
18937
18938   // Let legalize expand this if it isn't a legal type yet.
18939   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18940     return SDValue();
18941
18942   EVT ScalarVT = VT.getScalarType();
18943   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18944       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18945     return SDValue();
18946
18947   SDValue A = N->getOperand(0);
18948   SDValue B = N->getOperand(1);
18949   SDValue C = N->getOperand(2);
18950
18951   bool NegA = (A.getOpcode() == ISD::FNEG);
18952   bool NegB = (B.getOpcode() == ISD::FNEG);
18953   bool NegC = (C.getOpcode() == ISD::FNEG);
18954
18955   // Negative multiplication when NegA xor NegB
18956   bool NegMul = (NegA != NegB);
18957   if (NegA)
18958     A = A.getOperand(0);
18959   if (NegB)
18960     B = B.getOperand(0);
18961   if (NegC)
18962     C = C.getOperand(0);
18963
18964   unsigned Opcode;
18965   if (!NegMul)
18966     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18967   else
18968     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18969
18970   return DAG.getNode(Opcode, dl, VT, A, B, C);
18971 }
18972
18973 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18974                                   TargetLowering::DAGCombinerInfo &DCI,
18975                                   const X86Subtarget *Subtarget) {
18976   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18977   //           (and (i32 x86isd::setcc_carry), 1)
18978   // This eliminates the zext. This transformation is necessary because
18979   // ISD::SETCC is always legalized to i8.
18980   SDLoc dl(N);
18981   SDValue N0 = N->getOperand(0);
18982   EVT VT = N->getValueType(0);
18983
18984   if (N0.getOpcode() == ISD::AND &&
18985       N0.hasOneUse() &&
18986       N0.getOperand(0).hasOneUse()) {
18987     SDValue N00 = N0.getOperand(0);
18988     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18989       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18990       if (!C || C->getZExtValue() != 1)
18991         return SDValue();
18992       return DAG.getNode(ISD::AND, dl, VT,
18993                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18994                                      N00.getOperand(0), N00.getOperand(1)),
18995                          DAG.getConstant(1, VT));
18996     }
18997   }
18998
18999   if (N0.getOpcode() == ISD::TRUNCATE &&
19000       N0.hasOneUse() &&
19001       N0.getOperand(0).hasOneUse()) {
19002     SDValue N00 = N0.getOperand(0);
19003     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19004       return DAG.getNode(ISD::AND, dl, VT,
19005                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19006                                      N00.getOperand(0), N00.getOperand(1)),
19007                          DAG.getConstant(1, VT));
19008     }
19009   }
19010   if (VT.is256BitVector()) {
19011     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19012     if (R.getNode())
19013       return R;
19014   }
19015
19016   return SDValue();
19017 }
19018
19019 // Optimize x == -y --> x+y == 0
19020 //          x != -y --> x+y != 0
19021 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
19022   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19023   SDValue LHS = N->getOperand(0);
19024   SDValue RHS = N->getOperand(1);
19025
19026   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19027     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19028       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19029         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19030                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19031         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19032                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19033       }
19034   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19035     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19036       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19037         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19038                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19039         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19040                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19041       }
19042   return SDValue();
19043 }
19044
19045 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19046 // as "sbb reg,reg", since it can be extended without zext and produces
19047 // an all-ones bit which is more useful than 0/1 in some cases.
19048 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19049                                MVT VT) {
19050   if (VT == MVT::i8)
19051     return DAG.getNode(ISD::AND, DL, VT,
19052                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19053                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19054                        DAG.getConstant(1, VT));
19055   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19056   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19057                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19058                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19059 }
19060
19061 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19062 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19063                                    TargetLowering::DAGCombinerInfo &DCI,
19064                                    const X86Subtarget *Subtarget) {
19065   SDLoc DL(N);
19066   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19067   SDValue EFLAGS = N->getOperand(1);
19068
19069   if (CC == X86::COND_A) {
19070     // Try to convert COND_A into COND_B in an attempt to facilitate
19071     // materializing "setb reg".
19072     //
19073     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19074     // cannot take an immediate as its first operand.
19075     //
19076     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19077         EFLAGS.getValueType().isInteger() &&
19078         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19079       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19080                                    EFLAGS.getNode()->getVTList(),
19081                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19082       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19083       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19084     }
19085   }
19086
19087   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19088   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19089   // cases.
19090   if (CC == X86::COND_B)
19091     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19092
19093   SDValue Flags;
19094
19095   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19096   if (Flags.getNode()) {
19097     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19098     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19099   }
19100
19101   return SDValue();
19102 }
19103
19104 // Optimize branch condition evaluation.
19105 //
19106 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19107                                     TargetLowering::DAGCombinerInfo &DCI,
19108                                     const X86Subtarget *Subtarget) {
19109   SDLoc DL(N);
19110   SDValue Chain = N->getOperand(0);
19111   SDValue Dest = N->getOperand(1);
19112   SDValue EFLAGS = N->getOperand(3);
19113   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19114
19115   SDValue Flags;
19116
19117   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19118   if (Flags.getNode()) {
19119     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19120     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19121                        Flags);
19122   }
19123
19124   return SDValue();
19125 }
19126
19127 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19128                                         const X86TargetLowering *XTLI) {
19129   SDValue Op0 = N->getOperand(0);
19130   EVT InVT = Op0->getValueType(0);
19131
19132   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19133   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19134     SDLoc dl(N);
19135     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19136     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19137     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19138   }
19139
19140   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19141   // a 32-bit target where SSE doesn't support i64->FP operations.
19142   if (Op0.getOpcode() == ISD::LOAD) {
19143     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19144     EVT VT = Ld->getValueType(0);
19145     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19146         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19147         !XTLI->getSubtarget()->is64Bit() &&
19148         VT == MVT::i64) {
19149       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19150                                           Ld->getChain(), Op0, DAG);
19151       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19152       return FILDChain;
19153     }
19154   }
19155   return SDValue();
19156 }
19157
19158 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19159 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19160                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19161   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19162   // the result is either zero or one (depending on the input carry bit).
19163   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19164   if (X86::isZeroNode(N->getOperand(0)) &&
19165       X86::isZeroNode(N->getOperand(1)) &&
19166       // We don't have a good way to replace an EFLAGS use, so only do this when
19167       // dead right now.
19168       SDValue(N, 1).use_empty()) {
19169     SDLoc DL(N);
19170     EVT VT = N->getValueType(0);
19171     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19172     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19173                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19174                                            DAG.getConstant(X86::COND_B,MVT::i8),
19175                                            N->getOperand(2)),
19176                                DAG.getConstant(1, VT));
19177     return DCI.CombineTo(N, Res1, CarryOut);
19178   }
19179
19180   return SDValue();
19181 }
19182
19183 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19184 //      (add Y, (setne X, 0)) -> sbb -1, Y
19185 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19186 //      (sub (setne X, 0), Y) -> adc -1, Y
19187 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19188   SDLoc DL(N);
19189
19190   // Look through ZExts.
19191   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19192   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19193     return SDValue();
19194
19195   SDValue SetCC = Ext.getOperand(0);
19196   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19197     return SDValue();
19198
19199   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19200   if (CC != X86::COND_E && CC != X86::COND_NE)
19201     return SDValue();
19202
19203   SDValue Cmp = SetCC.getOperand(1);
19204   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19205       !X86::isZeroNode(Cmp.getOperand(1)) ||
19206       !Cmp.getOperand(0).getValueType().isInteger())
19207     return SDValue();
19208
19209   SDValue CmpOp0 = Cmp.getOperand(0);
19210   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19211                                DAG.getConstant(1, CmpOp0.getValueType()));
19212
19213   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19214   if (CC == X86::COND_NE)
19215     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19216                        DL, OtherVal.getValueType(), OtherVal,
19217                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19218   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19219                      DL, OtherVal.getValueType(), OtherVal,
19220                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19221 }
19222
19223 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19224 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19225                                  const X86Subtarget *Subtarget) {
19226   EVT VT = N->getValueType(0);
19227   SDValue Op0 = N->getOperand(0);
19228   SDValue Op1 = N->getOperand(1);
19229
19230   // Try to synthesize horizontal adds from adds of shuffles.
19231   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19232        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19233       isHorizontalBinOp(Op0, Op1, true))
19234     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19235
19236   return OptimizeConditionalInDecrement(N, DAG);
19237 }
19238
19239 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19240                                  const X86Subtarget *Subtarget) {
19241   SDValue Op0 = N->getOperand(0);
19242   SDValue Op1 = N->getOperand(1);
19243
19244   // X86 can't encode an immediate LHS of a sub. See if we can push the
19245   // negation into a preceding instruction.
19246   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19247     // If the RHS of the sub is a XOR with one use and a constant, invert the
19248     // immediate. Then add one to the LHS of the sub so we can turn
19249     // X-Y -> X+~Y+1, saving one register.
19250     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19251         isa<ConstantSDNode>(Op1.getOperand(1))) {
19252       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19253       EVT VT = Op0.getValueType();
19254       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19255                                    Op1.getOperand(0),
19256                                    DAG.getConstant(~XorC, VT));
19257       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19258                          DAG.getConstant(C->getAPIntValue()+1, VT));
19259     }
19260   }
19261
19262   // Try to synthesize horizontal adds from adds of shuffles.
19263   EVT VT = N->getValueType(0);
19264   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19265        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19266       isHorizontalBinOp(Op0, Op1, true))
19267     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19268
19269   return OptimizeConditionalInDecrement(N, DAG);
19270 }
19271
19272 /// performVZEXTCombine - Performs build vector combines
19273 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19274                                         TargetLowering::DAGCombinerInfo &DCI,
19275                                         const X86Subtarget *Subtarget) {
19276   // (vzext (bitcast (vzext (x)) -> (vzext x)
19277   SDValue In = N->getOperand(0);
19278   while (In.getOpcode() == ISD::BITCAST)
19279     In = In.getOperand(0);
19280
19281   if (In.getOpcode() != X86ISD::VZEXT)
19282     return SDValue();
19283
19284   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19285                      In.getOperand(0));
19286 }
19287
19288 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
19289                                              DAGCombinerInfo &DCI) const {
19290   SelectionDAG &DAG = DCI.DAG;
19291   switch (N->getOpcode()) {
19292   default: break;
19293   case ISD::EXTRACT_VECTOR_ELT:
19294     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
19295   case ISD::VSELECT:
19296   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
19297   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
19298   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
19299   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
19300   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
19301   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
19302   case ISD::SHL:
19303   case ISD::SRA:
19304   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
19305   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
19306   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
19307   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
19308   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
19309   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
19310   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
19311   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
19312   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
19313   case X86ISD::FXOR:
19314   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
19315   case X86ISD::FMIN:
19316   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
19317   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
19318   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
19319   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
19320   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
19321   case ISD::ANY_EXTEND:
19322   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
19323   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
19324   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
19325   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
19326   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
19327   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
19328   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
19329   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
19330   case X86ISD::SHUFP:       // Handle all target specific shuffles
19331   case X86ISD::PALIGNR:
19332   case X86ISD::UNPCKH:
19333   case X86ISD::UNPCKL:
19334   case X86ISD::MOVHLPS:
19335   case X86ISD::MOVLHPS:
19336   case X86ISD::PSHUFD:
19337   case X86ISD::PSHUFHW:
19338   case X86ISD::PSHUFLW:
19339   case X86ISD::MOVSS:
19340   case X86ISD::MOVSD:
19341   case X86ISD::VPERMILP:
19342   case X86ISD::VPERM2X128:
19343   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
19344   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
19345   }
19346
19347   return SDValue();
19348 }
19349
19350 /// isTypeDesirableForOp - Return true if the target has native support for
19351 /// the specified value type and it is 'desirable' to use the type for the
19352 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
19353 /// instruction encodings are longer and some i16 instructions are slow.
19354 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
19355   if (!isTypeLegal(VT))
19356     return false;
19357   if (VT != MVT::i16)
19358     return true;
19359
19360   switch (Opc) {
19361   default:
19362     return true;
19363   case ISD::LOAD:
19364   case ISD::SIGN_EXTEND:
19365   case ISD::ZERO_EXTEND:
19366   case ISD::ANY_EXTEND:
19367   case ISD::SHL:
19368   case ISD::SRL:
19369   case ISD::SUB:
19370   case ISD::ADD:
19371   case ISD::MUL:
19372   case ISD::AND:
19373   case ISD::OR:
19374   case ISD::XOR:
19375     return false;
19376   }
19377 }
19378
19379 /// IsDesirableToPromoteOp - This method query the target whether it is
19380 /// beneficial for dag combiner to promote the specified node. If true, it
19381 /// should return the desired promotion type by reference.
19382 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
19383   EVT VT = Op.getValueType();
19384   if (VT != MVT::i16)
19385     return false;
19386
19387   bool Promote = false;
19388   bool Commute = false;
19389   switch (Op.getOpcode()) {
19390   default: break;
19391   case ISD::LOAD: {
19392     LoadSDNode *LD = cast<LoadSDNode>(Op);
19393     // If the non-extending load has a single use and it's not live out, then it
19394     // might be folded.
19395     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
19396                                                      Op.hasOneUse()*/) {
19397       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19398              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
19399         // The only case where we'd want to promote LOAD (rather then it being
19400         // promoted as an operand is when it's only use is liveout.
19401         if (UI->getOpcode() != ISD::CopyToReg)
19402           return false;
19403       }
19404     }
19405     Promote = true;
19406     break;
19407   }
19408   case ISD::SIGN_EXTEND:
19409   case ISD::ZERO_EXTEND:
19410   case ISD::ANY_EXTEND:
19411     Promote = true;
19412     break;
19413   case ISD::SHL:
19414   case ISD::SRL: {
19415     SDValue N0 = Op.getOperand(0);
19416     // Look out for (store (shl (load), x)).
19417     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
19418       return false;
19419     Promote = true;
19420     break;
19421   }
19422   case ISD::ADD:
19423   case ISD::MUL:
19424   case ISD::AND:
19425   case ISD::OR:
19426   case ISD::XOR:
19427     Commute = true;
19428     // fallthrough
19429   case ISD::SUB: {
19430     SDValue N0 = Op.getOperand(0);
19431     SDValue N1 = Op.getOperand(1);
19432     if (!Commute && MayFoldLoad(N1))
19433       return false;
19434     // Avoid disabling potential load folding opportunities.
19435     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
19436       return false;
19437     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
19438       return false;
19439     Promote = true;
19440   }
19441   }
19442
19443   PVT = MVT::i32;
19444   return Promote;
19445 }
19446
19447 //===----------------------------------------------------------------------===//
19448 //                           X86 Inline Assembly Support
19449 //===----------------------------------------------------------------------===//
19450
19451 namespace {
19452   // Helper to match a string separated by whitespace.
19453   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
19454     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
19455
19456     for (unsigned i = 0, e = args.size(); i != e; ++i) {
19457       StringRef piece(*args[i]);
19458       if (!s.startswith(piece)) // Check if the piece matches.
19459         return false;
19460
19461       s = s.substr(piece.size());
19462       StringRef::size_type pos = s.find_first_not_of(" \t");
19463       if (pos == 0) // We matched a prefix.
19464         return false;
19465
19466       s = s.substr(pos);
19467     }
19468
19469     return s.empty();
19470   }
19471   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
19472 }
19473
19474 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
19475
19476   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
19477     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
19478         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
19479         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
19480
19481       if (AsmPieces.size() == 3)
19482         return true;
19483       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
19484         return true;
19485     }
19486   }
19487   return false;
19488 }
19489
19490 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
19491   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
19492
19493   std::string AsmStr = IA->getAsmString();
19494
19495   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
19496   if (!Ty || Ty->getBitWidth() % 16 != 0)
19497     return false;
19498
19499   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
19500   SmallVector<StringRef, 4> AsmPieces;
19501   SplitString(AsmStr, AsmPieces, ";\n");
19502
19503   switch (AsmPieces.size()) {
19504   default: return false;
19505   case 1:
19506     // FIXME: this should verify that we are targeting a 486 or better.  If not,
19507     // we will turn this bswap into something that will be lowered to logical
19508     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
19509     // lower so don't worry about this.
19510     // bswap $0
19511     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
19512         matchAsm(AsmPieces[0], "bswapl", "$0") ||
19513         matchAsm(AsmPieces[0], "bswapq", "$0") ||
19514         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
19515         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
19516         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
19517       // No need to check constraints, nothing other than the equivalent of
19518       // "=r,0" would be valid here.
19519       return IntrinsicLowering::LowerToByteSwap(CI);
19520     }
19521
19522     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
19523     if (CI->getType()->isIntegerTy(16) &&
19524         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19525         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
19526          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
19527       AsmPieces.clear();
19528       const std::string &ConstraintsStr = IA->getConstraintString();
19529       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19530       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19531       if (clobbersFlagRegisters(AsmPieces))
19532         return IntrinsicLowering::LowerToByteSwap(CI);
19533     }
19534     break;
19535   case 3:
19536     if (CI->getType()->isIntegerTy(32) &&
19537         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
19538         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
19539         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
19540         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
19541       AsmPieces.clear();
19542       const std::string &ConstraintsStr = IA->getConstraintString();
19543       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
19544       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
19545       if (clobbersFlagRegisters(AsmPieces))
19546         return IntrinsicLowering::LowerToByteSwap(CI);
19547     }
19548
19549     if (CI->getType()->isIntegerTy(64)) {
19550       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
19551       if (Constraints.size() >= 2 &&
19552           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
19553           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
19554         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
19555         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
19556             matchAsm(AsmPieces[1], "bswap", "%edx") &&
19557             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
19558           return IntrinsicLowering::LowerToByteSwap(CI);
19559       }
19560     }
19561     break;
19562   }
19563   return false;
19564 }
19565
19566 /// getConstraintType - Given a constraint letter, return the type of
19567 /// constraint it is for this target.
19568 X86TargetLowering::ConstraintType
19569 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
19570   if (Constraint.size() == 1) {
19571     switch (Constraint[0]) {
19572     case 'R':
19573     case 'q':
19574     case 'Q':
19575     case 'f':
19576     case 't':
19577     case 'u':
19578     case 'y':
19579     case 'x':
19580     case 'Y':
19581     case 'l':
19582       return C_RegisterClass;
19583     case 'a':
19584     case 'b':
19585     case 'c':
19586     case 'd':
19587     case 'S':
19588     case 'D':
19589     case 'A':
19590       return C_Register;
19591     case 'I':
19592     case 'J':
19593     case 'K':
19594     case 'L':
19595     case 'M':
19596     case 'N':
19597     case 'G':
19598     case 'C':
19599     case 'e':
19600     case 'Z':
19601       return C_Other;
19602     default:
19603       break;
19604     }
19605   }
19606   return TargetLowering::getConstraintType(Constraint);
19607 }
19608
19609 /// Examine constraint type and operand type and determine a weight value.
19610 /// This object must already have been set up with the operand type
19611 /// and the current alternative constraint selected.
19612 TargetLowering::ConstraintWeight
19613   X86TargetLowering::getSingleConstraintMatchWeight(
19614     AsmOperandInfo &info, const char *constraint) const {
19615   ConstraintWeight weight = CW_Invalid;
19616   Value *CallOperandVal = info.CallOperandVal;
19617     // If we don't have a value, we can't do a match,
19618     // but allow it at the lowest weight.
19619   if (CallOperandVal == NULL)
19620     return CW_Default;
19621   Type *type = CallOperandVal->getType();
19622   // Look at the constraint type.
19623   switch (*constraint) {
19624   default:
19625     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
19626   case 'R':
19627   case 'q':
19628   case 'Q':
19629   case 'a':
19630   case 'b':
19631   case 'c':
19632   case 'd':
19633   case 'S':
19634   case 'D':
19635   case 'A':
19636     if (CallOperandVal->getType()->isIntegerTy())
19637       weight = CW_SpecificReg;
19638     break;
19639   case 'f':
19640   case 't':
19641   case 'u':
19642     if (type->isFloatingPointTy())
19643       weight = CW_SpecificReg;
19644     break;
19645   case 'y':
19646     if (type->isX86_MMXTy() && Subtarget->hasMMX())
19647       weight = CW_SpecificReg;
19648     break;
19649   case 'x':
19650   case 'Y':
19651     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
19652         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
19653       weight = CW_Register;
19654     break;
19655   case 'I':
19656     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
19657       if (C->getZExtValue() <= 31)
19658         weight = CW_Constant;
19659     }
19660     break;
19661   case 'J':
19662     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19663       if (C->getZExtValue() <= 63)
19664         weight = CW_Constant;
19665     }
19666     break;
19667   case 'K':
19668     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19669       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
19670         weight = CW_Constant;
19671     }
19672     break;
19673   case 'L':
19674     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19675       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
19676         weight = CW_Constant;
19677     }
19678     break;
19679   case 'M':
19680     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19681       if (C->getZExtValue() <= 3)
19682         weight = CW_Constant;
19683     }
19684     break;
19685   case 'N':
19686     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19687       if (C->getZExtValue() <= 0xff)
19688         weight = CW_Constant;
19689     }
19690     break;
19691   case 'G':
19692   case 'C':
19693     if (dyn_cast<ConstantFP>(CallOperandVal)) {
19694       weight = CW_Constant;
19695     }
19696     break;
19697   case 'e':
19698     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19699       if ((C->getSExtValue() >= -0x80000000LL) &&
19700           (C->getSExtValue() <= 0x7fffffffLL))
19701         weight = CW_Constant;
19702     }
19703     break;
19704   case 'Z':
19705     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
19706       if (C->getZExtValue() <= 0xffffffff)
19707         weight = CW_Constant;
19708     }
19709     break;
19710   }
19711   return weight;
19712 }
19713
19714 /// LowerXConstraint - try to replace an X constraint, which matches anything,
19715 /// with another that has more specific requirements based on the type of the
19716 /// corresponding operand.
19717 const char *X86TargetLowering::
19718 LowerXConstraint(EVT ConstraintVT) const {
19719   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
19720   // 'f' like normal targets.
19721   if (ConstraintVT.isFloatingPoint()) {
19722     if (Subtarget->hasSSE2())
19723       return "Y";
19724     if (Subtarget->hasSSE1())
19725       return "x";
19726   }
19727
19728   return TargetLowering::LowerXConstraint(ConstraintVT);
19729 }
19730
19731 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19732 /// vector.  If it is invalid, don't add anything to Ops.
19733 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
19734                                                      std::string &Constraint,
19735                                                      std::vector<SDValue>&Ops,
19736                                                      SelectionDAG &DAG) const {
19737   SDValue Result(0, 0);
19738
19739   // Only support length 1 constraints for now.
19740   if (Constraint.length() > 1) return;
19741
19742   char ConstraintLetter = Constraint[0];
19743   switch (ConstraintLetter) {
19744   default: break;
19745   case 'I':
19746     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19747       if (C->getZExtValue() <= 31) {
19748         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19749         break;
19750       }
19751     }
19752     return;
19753   case 'J':
19754     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19755       if (C->getZExtValue() <= 63) {
19756         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19757         break;
19758       }
19759     }
19760     return;
19761   case 'K':
19762     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19763       if (isInt<8>(C->getSExtValue())) {
19764         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19765         break;
19766       }
19767     }
19768     return;
19769   case 'N':
19770     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19771       if (C->getZExtValue() <= 255) {
19772         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19773         break;
19774       }
19775     }
19776     return;
19777   case 'e': {
19778     // 32-bit signed value
19779     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19780       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19781                                            C->getSExtValue())) {
19782         // Widen to 64 bits here to get it sign extended.
19783         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
19784         break;
19785       }
19786     // FIXME gcc accepts some relocatable values here too, but only in certain
19787     // memory models; it's complicated.
19788     }
19789     return;
19790   }
19791   case 'Z': {
19792     // 32-bit unsigned value
19793     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
19794       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
19795                                            C->getZExtValue())) {
19796         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
19797         break;
19798       }
19799     }
19800     // FIXME gcc accepts some relocatable values here too, but only in certain
19801     // memory models; it's complicated.
19802     return;
19803   }
19804   case 'i': {
19805     // Literal immediates are always ok.
19806     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19807       // Widen to 64 bits here to get it sign extended.
19808       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19809       break;
19810     }
19811
19812     // In any sort of PIC mode addresses need to be computed at runtime by
19813     // adding in a register or some sort of table lookup.  These can't
19814     // be used as immediates.
19815     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19816       return;
19817
19818     // If we are in non-pic codegen mode, we allow the address of a global (with
19819     // an optional displacement) to be used with 'i'.
19820     GlobalAddressSDNode *GA = 0;
19821     int64_t Offset = 0;
19822
19823     // Match either (GA), (GA+C), (GA+C1+C2), etc.
19824     while (1) {
19825       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19826         Offset += GA->getOffset();
19827         break;
19828       } else if (Op.getOpcode() == ISD::ADD) {
19829         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19830           Offset += C->getZExtValue();
19831           Op = Op.getOperand(0);
19832           continue;
19833         }
19834       } else if (Op.getOpcode() == ISD::SUB) {
19835         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19836           Offset += -C->getZExtValue();
19837           Op = Op.getOperand(0);
19838           continue;
19839         }
19840       }
19841
19842       // Otherwise, this isn't something we can handle, reject it.
19843       return;
19844     }
19845
19846     const GlobalValue *GV = GA->getGlobal();
19847     // If we require an extra load to get this address, as in PIC mode, we
19848     // can't accept it.
19849     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19850                                                         getTargetMachine())))
19851       return;
19852
19853     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19854                                         GA->getValueType(0), Offset);
19855     break;
19856   }
19857   }
19858
19859   if (Result.getNode()) {
19860     Ops.push_back(Result);
19861     return;
19862   }
19863   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19864 }
19865
19866 std::pair<unsigned, const TargetRegisterClass*>
19867 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19868                                                 MVT VT) const {
19869   // First, see if this is a constraint that directly corresponds to an LLVM
19870   // register class.
19871   if (Constraint.size() == 1) {
19872     // GCC Constraint Letters
19873     switch (Constraint[0]) {
19874     default: break;
19875       // TODO: Slight differences here in allocation order and leaving
19876       // RIP in the class. Do they matter any more here than they do
19877       // in the normal allocation?
19878     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19879       if (Subtarget->is64Bit()) {
19880         if (VT == MVT::i32 || VT == MVT::f32)
19881           return std::make_pair(0U, &X86::GR32RegClass);
19882         if (VT == MVT::i16)
19883           return std::make_pair(0U, &X86::GR16RegClass);
19884         if (VT == MVT::i8 || VT == MVT::i1)
19885           return std::make_pair(0U, &X86::GR8RegClass);
19886         if (VT == MVT::i64 || VT == MVT::f64)
19887           return std::make_pair(0U, &X86::GR64RegClass);
19888         break;
19889       }
19890       // 32-bit fallthrough
19891     case 'Q':   // Q_REGS
19892       if (VT == MVT::i32 || VT == MVT::f32)
19893         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19894       if (VT == MVT::i16)
19895         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19896       if (VT == MVT::i8 || VT == MVT::i1)
19897         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19898       if (VT == MVT::i64)
19899         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19900       break;
19901     case 'r':   // GENERAL_REGS
19902     case 'l':   // INDEX_REGS
19903       if (VT == MVT::i8 || VT == MVT::i1)
19904         return std::make_pair(0U, &X86::GR8RegClass);
19905       if (VT == MVT::i16)
19906         return std::make_pair(0U, &X86::GR16RegClass);
19907       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19908         return std::make_pair(0U, &X86::GR32RegClass);
19909       return std::make_pair(0U, &X86::GR64RegClass);
19910     case 'R':   // LEGACY_REGS
19911       if (VT == MVT::i8 || VT == MVT::i1)
19912         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19913       if (VT == MVT::i16)
19914         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19915       if (VT == MVT::i32 || !Subtarget->is64Bit())
19916         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19917       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19918     case 'f':  // FP Stack registers.
19919       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19920       // value to the correct fpstack register class.
19921       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19922         return std::make_pair(0U, &X86::RFP32RegClass);
19923       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19924         return std::make_pair(0U, &X86::RFP64RegClass);
19925       return std::make_pair(0U, &X86::RFP80RegClass);
19926     case 'y':   // MMX_REGS if MMX allowed.
19927       if (!Subtarget->hasMMX()) break;
19928       return std::make_pair(0U, &X86::VR64RegClass);
19929     case 'Y':   // SSE_REGS if SSE2 allowed
19930       if (!Subtarget->hasSSE2()) break;
19931       // FALL THROUGH.
19932     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19933       if (!Subtarget->hasSSE1()) break;
19934
19935       switch (VT.SimpleTy) {
19936       default: break;
19937       // Scalar SSE types.
19938       case MVT::f32:
19939       case MVT::i32:
19940         return std::make_pair(0U, &X86::FR32RegClass);
19941       case MVT::f64:
19942       case MVT::i64:
19943         return std::make_pair(0U, &X86::FR64RegClass);
19944       // Vector types.
19945       case MVT::v16i8:
19946       case MVT::v8i16:
19947       case MVT::v4i32:
19948       case MVT::v2i64:
19949       case MVT::v4f32:
19950       case MVT::v2f64:
19951         return std::make_pair(0U, &X86::VR128RegClass);
19952       // AVX types.
19953       case MVT::v32i8:
19954       case MVT::v16i16:
19955       case MVT::v8i32:
19956       case MVT::v4i64:
19957       case MVT::v8f32:
19958       case MVT::v4f64:
19959         return std::make_pair(0U, &X86::VR256RegClass);
19960       case MVT::v8f64:
19961       case MVT::v16f32:
19962       case MVT::v16i32:
19963       case MVT::v8i64:
19964         return std::make_pair(0U, &X86::VR512RegClass);
19965       }
19966       break;
19967     }
19968   }
19969
19970   // Use the default implementation in TargetLowering to convert the register
19971   // constraint into a member of a register class.
19972   std::pair<unsigned, const TargetRegisterClass*> Res;
19973   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19974
19975   // Not found as a standard register?
19976   if (Res.second == 0) {
19977     // Map st(0) -> st(7) -> ST0
19978     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19979         tolower(Constraint[1]) == 's' &&
19980         tolower(Constraint[2]) == 't' &&
19981         Constraint[3] == '(' &&
19982         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19983         Constraint[5] == ')' &&
19984         Constraint[6] == '}') {
19985
19986       Res.first = X86::ST0+Constraint[4]-'0';
19987       Res.second = &X86::RFP80RegClass;
19988       return Res;
19989     }
19990
19991     // GCC allows "st(0)" to be called just plain "st".
19992     if (StringRef("{st}").equals_lower(Constraint)) {
19993       Res.first = X86::ST0;
19994       Res.second = &X86::RFP80RegClass;
19995       return Res;
19996     }
19997
19998     // flags -> EFLAGS
19999     if (StringRef("{flags}").equals_lower(Constraint)) {
20000       Res.first = X86::EFLAGS;
20001       Res.second = &X86::CCRRegClass;
20002       return Res;
20003     }
20004
20005     // 'A' means EAX + EDX.
20006     if (Constraint == "A") {
20007       Res.first = X86::EAX;
20008       Res.second = &X86::GR32_ADRegClass;
20009       return Res;
20010     }
20011     return Res;
20012   }
20013
20014   // Otherwise, check to see if this is a register class of the wrong value
20015   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20016   // turn into {ax},{dx}.
20017   if (Res.second->hasType(VT))
20018     return Res;   // Correct type already, nothing to do.
20019
20020   // All of the single-register GCC register classes map their values onto
20021   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20022   // really want an 8-bit or 32-bit register, map to the appropriate register
20023   // class and return the appropriate register.
20024   if (Res.second == &X86::GR16RegClass) {
20025     if (VT == MVT::i8 || VT == MVT::i1) {
20026       unsigned DestReg = 0;
20027       switch (Res.first) {
20028       default: break;
20029       case X86::AX: DestReg = X86::AL; break;
20030       case X86::DX: DestReg = X86::DL; break;
20031       case X86::CX: DestReg = X86::CL; break;
20032       case X86::BX: DestReg = X86::BL; break;
20033       }
20034       if (DestReg) {
20035         Res.first = DestReg;
20036         Res.second = &X86::GR8RegClass;
20037       }
20038     } else if (VT == MVT::i32 || VT == MVT::f32) {
20039       unsigned DestReg = 0;
20040       switch (Res.first) {
20041       default: break;
20042       case X86::AX: DestReg = X86::EAX; break;
20043       case X86::DX: DestReg = X86::EDX; break;
20044       case X86::CX: DestReg = X86::ECX; break;
20045       case X86::BX: DestReg = X86::EBX; break;
20046       case X86::SI: DestReg = X86::ESI; break;
20047       case X86::DI: DestReg = X86::EDI; break;
20048       case X86::BP: DestReg = X86::EBP; break;
20049       case X86::SP: DestReg = X86::ESP; break;
20050       }
20051       if (DestReg) {
20052         Res.first = DestReg;
20053         Res.second = &X86::GR32RegClass;
20054       }
20055     } else if (VT == MVT::i64 || VT == MVT::f64) {
20056       unsigned DestReg = 0;
20057       switch (Res.first) {
20058       default: break;
20059       case X86::AX: DestReg = X86::RAX; break;
20060       case X86::DX: DestReg = X86::RDX; break;
20061       case X86::CX: DestReg = X86::RCX; break;
20062       case X86::BX: DestReg = X86::RBX; break;
20063       case X86::SI: DestReg = X86::RSI; break;
20064       case X86::DI: DestReg = X86::RDI; break;
20065       case X86::BP: DestReg = X86::RBP; break;
20066       case X86::SP: DestReg = X86::RSP; break;
20067       }
20068       if (DestReg) {
20069         Res.first = DestReg;
20070         Res.second = &X86::GR64RegClass;
20071       }
20072     }
20073   } else if (Res.second == &X86::FR32RegClass ||
20074              Res.second == &X86::FR64RegClass ||
20075              Res.second == &X86::VR128RegClass ||
20076              Res.second == &X86::VR256RegClass ||
20077              Res.second == &X86::FR32XRegClass ||
20078              Res.second == &X86::FR64XRegClass ||
20079              Res.second == &X86::VR128XRegClass ||
20080              Res.second == &X86::VR256XRegClass ||
20081              Res.second == &X86::VR512RegClass) {
20082     // Handle references to XMM physical registers that got mapped into the
20083     // wrong class.  This can happen with constraints like {xmm0} where the
20084     // target independent register mapper will just pick the first match it can
20085     // find, ignoring the required type.
20086
20087     if (VT == MVT::f32 || VT == MVT::i32)
20088       Res.second = &X86::FR32RegClass;
20089     else if (VT == MVT::f64 || VT == MVT::i64)
20090       Res.second = &X86::FR64RegClass;
20091     else if (X86::VR128RegClass.hasType(VT))
20092       Res.second = &X86::VR128RegClass;
20093     else if (X86::VR256RegClass.hasType(VT))
20094       Res.second = &X86::VR256RegClass;
20095     else if (X86::VR512RegClass.hasType(VT))
20096       Res.second = &X86::VR512RegClass;
20097   }
20098
20099   return Res;
20100 }