[X86] Improve the lowering of BITCAST from MVT::f64 to MVT::v4i16/MVT::v8i8.
[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 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.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/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.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 #define DEBUG_TYPE "x86-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64                                 SelectionDAG &DAG, SDLoc dl,
65                                 unsigned vectorWidth) {
66   assert((vectorWidth == 128 || vectorWidth == 256) &&
67          "Unsupported vector width");
68   EVT VT = Vec.getValueType();
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/vectorWidth;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
79   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80
81   // This is the index of the first element of the vectorWidth-bit chunk
82   // we want.
83   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84                                * ElemsPerChunk);
85
86   // If the input is a buildvector just emit a smaller one.
87   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
90                                     ElemsPerChunk));
91
92   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94                                VecIdx);
95
96   return Result;
97
98 }
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106                                    SelectionDAG &DAG, SDLoc dl) {
107   assert((Vec.getValueType().is256BitVector() ||
108           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 }
111
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114                                    SelectionDAG &DAG, SDLoc dl) {
115   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 }
118
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120                                unsigned IdxVal, SelectionDAG &DAG,
121                                SDLoc dl, unsigned vectorWidth) {
122   assert((vectorWidth == 128 || vectorWidth == 256) &&
123          "Unsupported vector width");
124   // Inserting UNDEF is Result
125   if (Vec.getOpcode() == ISD::UNDEF)
126     return Result;
127   EVT VT = Vec.getValueType();
128   EVT ElVT = VT.getVectorElementType();
129   EVT ResultVT = Result.getValueType();
130
131   // Insert the relevant vectorWidth bits.
132   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133
134   // This is the index of the first element of the vectorWidth-bit chunk
135   // we want.
136   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137                                * ElemsPerChunk);
138
139   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141                      VecIdx);
142 }
143 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference.  Idx is an index in the 128 bits
147 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150                                   unsigned IdxVal, SelectionDAG &DAG,
151                                   SDLoc dl) {
152   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 }
155
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 }
162
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168                                    unsigned NumElems, SelectionDAG &DAG,
169                                    SDLoc dl) {
170   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 }
173
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
182   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
183   bool is64Bit = Subtarget->is64Bit();
184
185   if (Subtarget->isTargetMacho()) {
186     if (is64Bit)
187       return new X86_64MachoTargetObjectFile();
188     return new TargetLoweringObjectFileMachO();
189   }
190
191   if (Subtarget->isTargetLinux())
192     return new X86LinuxTargetObjectFile();
193   if (Subtarget->isTargetELF())
194     return new TargetLoweringObjectFileELF();
195   if (Subtarget->isTargetKnownWindowsMSVC())
196     return new X86WindowsTargetObjectFile();
197   if (Subtarget->isTargetCOFF())
198     return new TargetLoweringObjectFileCOFF();
199   llvm_unreachable("unknown subtarget type");
200 }
201
202 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
203   : TargetLowering(TM, createTLOF(TM)) {
204   Subtarget = &TM.getSubtarget<X86Subtarget>();
205   X86ScalarSSEf64 = Subtarget->hasSSE2();
206   X86ScalarSSEf32 = Subtarget->hasSSE1();
207   TD = getDataLayout();
208
209   resetOperationActions();
210 }
211
212 void X86TargetLowering::resetOperationActions() {
213   const TargetMachine &TM = getTargetMachine();
214   static bool FirstTimeThrough = true;
215
216   // If none of the target options have changed, then we don't need to reset the
217   // operation actions.
218   if (!FirstTimeThrough && TO == TM.Options) return;
219
220   if (!FirstTimeThrough) {
221     // Reinitialize the actions.
222     initActions();
223     FirstTimeThrough = false;
224   }
225
226   TO = TM.Options;
227
228   // Set up the TargetLowering object.
229   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
230
231   // X86 is weird, it always uses i8 for shift amounts and setcc results.
232   setBooleanContents(ZeroOrOneBooleanContent);
233   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
234   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235
236   // For 64-bit since we have so many registers use the ILP scheduler, for
237   // 32-bit code use the register pressure specific scheduling.
238   // For Atom, always use ILP scheduling.
239   if (Subtarget->isAtom())
240     setSchedulingPreference(Sched::ILP);
241   else if (Subtarget->is64Bit())
242     setSchedulingPreference(Sched::ILP);
243   else
244     setSchedulingPreference(Sched::RegPressure);
245   const X86RegisterInfo *RegInfo =
246     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
247   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
248
249   // Bypass expensive divides on Atom when compiling with O2
250   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
251     addBypassSlowDiv(32, 8);
252     if (Subtarget->is64Bit())
253       addBypassSlowDiv(64, 16);
254   }
255
256   if (Subtarget->isTargetKnownWindowsMSVC()) {
257     // Setup Windows compiler runtime calls.
258     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
259     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
260     setLibcallName(RTLIB::SREM_I64, "_allrem");
261     setLibcallName(RTLIB::UREM_I64, "_aullrem");
262     setLibcallName(RTLIB::MUL_I64, "_allmul");
263     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
266     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
267     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
268
269     // The _ftol2 runtime function has an unusual calling conv, which
270     // is modeled by a special pseudo-instruction.
271     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
273     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
274     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
275   }
276
277   if (Subtarget->isTargetDarwin()) {
278     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
279     setUseUnderscoreSetJmp(false);
280     setUseUnderscoreLongJmp(false);
281   } else if (Subtarget->isTargetWindowsGNU()) {
282     // MS runtime is weird: it exports _setjmp, but longjmp!
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(false);
285   } else {
286     setUseUnderscoreSetJmp(true);
287     setUseUnderscoreLongJmp(true);
288   }
289
290   // Set up the register classes.
291   addRegisterClass(MVT::i8, &X86::GR8RegClass);
292   addRegisterClass(MVT::i16, &X86::GR16RegClass);
293   addRegisterClass(MVT::i32, &X86::GR32RegClass);
294   if (Subtarget->is64Bit())
295     addRegisterClass(MVT::i64, &X86::GR64RegClass);
296
297   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
298
299   // We don't accept any truncstore of integer registers.
300   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
301   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
304   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
305   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
306
307   // SETOEQ and SETUNE require checking two conditions.
308   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314
315   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316   // operation.
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
319   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
320
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324   } else if (!TM.Options.UseSoftFloat) {
325     // We have an algorithm for SSE2->double, and we turn this into a
326     // 64-bit FILD followed by conditional FADD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
328     // We have an algorithm for SSE2, and we turn this into a 64-bit
329     // FILD for other targets.
330     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
331   }
332
333   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
336   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
337
338   if (!TM.Options.UseSoftFloat) {
339     // SSE has no i16 to fp conversion, only i32
340     if (X86ScalarSSEf32) {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
342       // f32 and f64 cases are Legal, f80 case is not
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     } else {
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
346       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
347     }
348   } else {
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
350     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
351   }
352
353   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
354   // are Legal, f80 is custom lowered.
355   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
356   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
357
358   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359   // this operation.
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
361   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
362
363   if (X86ScalarSSEf32) {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
365     // f32 and f64 cases are Legal, f80 case is not
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   } else {
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
369     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
370   }
371
372   // Handle FP_TO_UINT by promoting the destination to a larger signed
373   // conversion.
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
376   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
377
378   if (Subtarget->is64Bit()) {
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
380     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
381   } else if (!TM.Options.UseSoftFloat) {
382     // Since AVX is a superset of SSE3, only check for SSE here.
383     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384       // Expand FP_TO_UINT into a select.
385       // FIXME: We would like to use a Custom expander here eventually to do
386       // the optimal thing for SSE vs. the default expansion in the legalizer.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
388     else
389       // With SSE3 we can use fisttpll to convert to a signed i64; without
390       // SSE, we're stuck with a fistpll.
391       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
392   }
393
394   if (isTargetFTOL()) {
395     // Use the _ftol2 runtime function, which has a pseudo-instruction
396     // to handle its weird calling convention.
397     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
398   }
399
400   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401   if (!X86ScalarSSEf64) {
402     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
403     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
404     if (Subtarget->is64Bit()) {
405       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
406       // Without SSE, i64->f64 goes through memory.
407       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
408     }
409   }
410
411   // Scalar integer divide and remainder are lowered to use operations that
412   // produce two results, to match the available instructions. This exposes
413   // the two-result form to trivial CSE, which is able to combine x/y and x%y
414   // into a single instruction.
415   //
416   // Scalar integer multiply-high is also lowered to use two-result
417   // operations, to match the available instructions. However, plain multiply
418   // (low) operations are left as Legal, as there are single-result
419   // instructions for this in x86. Using the two-result multiply instructions
420   // when both high and low results are needed must be arranged by dagcombine.
421   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422     MVT VT = IntVTs[i];
423     setOperationAction(ISD::MULHS, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::SDIV, VT, Expand);
426     setOperationAction(ISD::UDIV, VT, Expand);
427     setOperationAction(ISD::SREM, VT, Expand);
428     setOperationAction(ISD::UREM, VT, Expand);
429
430     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431     setOperationAction(ISD::ADDC, VT, Custom);
432     setOperationAction(ISD::ADDE, VT, Custom);
433     setOperationAction(ISD::SUBC, VT, Custom);
434     setOperationAction(ISD::SUBE, VT, Custom);
435   }
436
437   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
438   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
439   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
447   if (Subtarget->is64Bit())
448     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
450   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
451   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
452   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
454   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
455   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
456   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
457
458   // Promote the i8 variants and force them on up to i32 which has a shorter
459   // encoding.
460   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
461   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
462   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
463   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
464   if (Subtarget->hasBMI()) {
465     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
466     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
467     if (Subtarget->is64Bit())
468       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
469   } else {
470     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
471     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
472     if (Subtarget->is64Bit())
473       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
474   }
475
476   if (Subtarget->hasLZCNT()) {
477     // When promoting the i8 variants, force them to i32 for a shorter
478     // encoding.
479     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
480     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
482     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
483     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
492     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
493     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
494     if (Subtarget->is64Bit()) {
495       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
496       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497     }
498   }
499
500   if (Subtarget->hasPOPCNT()) {
501     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
502   } else {
503     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
504     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
505     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
506     if (Subtarget->is64Bit())
507       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
508   }
509
510   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
511
512   if (!Subtarget->hasMOVBE())
513     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
514
515   // These should be promoted to a larger select which is supported.
516   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
517   // X86 wants to expand cmov itself.
518   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
519   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
522   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
523   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
525   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
528   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
530   if (Subtarget->is64Bit()) {
531     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
532     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
533   }
534   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
535   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537   // support continuation, user-level threading, and etc.. As a result, no
538   // other SjLj exception interfaces are implemented and please don't build
539   // your own exception handling based on them.
540   // LLVM/Clang supports zero-cost DWARF exception handling.
541   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543
544   // Darwin ABI issue.
545   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
546   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
547   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
548   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
549   if (Subtarget->is64Bit())
550     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
551   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
552   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
553   if (Subtarget->is64Bit()) {
554     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
555     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
556     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
557     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
558     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
559   }
560   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
561   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
562   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
563   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
566     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
567     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
568   }
569
570   if (Subtarget->hasSSE1())
571     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
572
573   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
574
575   // Expand certain atomics
576   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
577     MVT VT = IntVTs[i];
578     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
580     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
581   }
582
583   if (!Subtarget->is64Bit()) {
584     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
594     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
595     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
596   }
597
598   if (Subtarget->hasCmpxchg16b()) {
599     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
600   }
601
602   // FIXME - use subtarget debug flags
603   if (!Subtarget->isTargetDarwin() &&
604       !Subtarget->isTargetELF() &&
605       !Subtarget->isTargetCygMing()) {
606     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
607   }
608
609   if (Subtarget->is64Bit()) {
610     setExceptionPointerRegister(X86::RAX);
611     setExceptionSelectorRegister(X86::RDX);
612   } else {
613     setExceptionPointerRegister(X86::EAX);
614     setExceptionSelectorRegister(X86::EDX);
615   }
616   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
617   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
618
619   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
620   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
621
622   setOperationAction(ISD::TRAP, MVT::Other, Legal);
623   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
624
625   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
626   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
627   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
628   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
629     // TargetInfo::X86_64ABIBuiltinVaList
630     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
631     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
632   } else {
633     // TargetInfo::CharPtrBuiltinVaList
634     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
635     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
636   }
637
638   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
639   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
640
641   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642                      MVT::i64 : MVT::i32, Custom);
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::MULHS, VT, Expand);
832     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833     setOperationAction(ISD::MULHU, VT, Expand);
834     setOperationAction(ISD::SDIVREM, VT, Expand);
835     setOperationAction(ISD::UDIVREM, VT, Expand);
836     setOperationAction(ISD::FPOW, VT, Expand);
837     setOperationAction(ISD::CTPOP, VT, Expand);
838     setOperationAction(ISD::CTTZ, VT, Expand);
839     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::CTLZ, VT, Expand);
841     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842     setOperationAction(ISD::SHL, VT, Expand);
843     setOperationAction(ISD::SRA, VT, Expand);
844     setOperationAction(ISD::SRL, VT, Expand);
845     setOperationAction(ISD::ROTL, VT, Expand);
846     setOperationAction(ISD::ROTR, VT, Expand);
847     setOperationAction(ISD::BSWAP, VT, Expand);
848     setOperationAction(ISD::SETCC, VT, Expand);
849     setOperationAction(ISD::FLOG, VT, Expand);
850     setOperationAction(ISD::FLOG2, VT, Expand);
851     setOperationAction(ISD::FLOG10, VT, Expand);
852     setOperationAction(ISD::FEXP, VT, Expand);
853     setOperationAction(ISD::FEXP2, VT, Expand);
854     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859     setOperationAction(ISD::TRUNCATE, VT, Expand);
860     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863     setOperationAction(ISD::VSELECT, VT, Expand);
864     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866       setTruncStoreAction(VT,
867                           (MVT::SimpleValueType)InnerVT, Expand);
868     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871   }
872
873   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874   // with -msoft-float, disable use of MMX as well.
875   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877     // No operations on x86mmx supported, everything uses intrinsics.
878   }
879
880   // MMX-sized vectors (other than x86mmx) are expected to be expanded
881   // into smaller operations.
882   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
883   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
884   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
885   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
886   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
887   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
888   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
889   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
890   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
891   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
892   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
893   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
894   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
895   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
896   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
897   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
901   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
902   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
904   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
906   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
910   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
911
912   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
914
915     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
919     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
920     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
921     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
922     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
923     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
924     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
925     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
927   }
928
929   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
931
932     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933     // registers cannot be used even for integer operations.
934     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
938
939     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
940     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
941     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
942     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
943     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
944     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
945     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
946     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
947     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
948     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
949     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
950     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
951     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
952     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
953     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
954     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
956     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
957     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
958     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
959     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
960     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
961
962     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
963     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
964     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
965     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
966
967     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
968     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
970     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
971     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
972
973     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
974     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
975       MVT VT = (MVT::SimpleValueType)i;
976       // Do not attempt to custom lower non-power-of-2 vectors
977       if (!isPowerOf2_32(VT.getVectorNumElements()))
978         continue;
979       // Do not attempt to custom lower non-128-bit vectors
980       if (!VT.is128BitVector())
981         continue;
982       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
983       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
984       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
985     }
986
987     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
988     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
989     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
990     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
993
994     if (Subtarget->is64Bit()) {
995       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
996       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
997     }
998
999     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1000     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001       MVT VT = (MVT::SimpleValueType)i;
1002
1003       // Do not attempt to promote non-128-bit vectors
1004       if (!VT.is128BitVector())
1005         continue;
1006
1007       setOperationAction(ISD::AND,    VT, Promote);
1008       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1009       setOperationAction(ISD::OR,     VT, Promote);
1010       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1011       setOperationAction(ISD::XOR,    VT, Promote);
1012       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1013       setOperationAction(ISD::LOAD,   VT, Promote);
1014       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1015       setOperationAction(ISD::SELECT, VT, Promote);
1016       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1017     }
1018
1019     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1020
1021     // Custom lower v2i64 and v2f64 selects.
1022     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1023     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1024     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1025     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1026
1027     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1028     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1029
1030     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1031     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1032     // As there is no 64-bit GPR available, we need build a special custom
1033     // sequence to convert from v2i32 to v2f32.
1034     if (!Subtarget->is64Bit())
1035       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1036
1037     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1038     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1039
1040     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1041
1042     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1043     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1044     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1045   }
1046
1047   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1048     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1051     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1053     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1054     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1055     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1056     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1057     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1058
1059     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1060     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1061     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1062     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1063     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1064     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1065     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1066     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1067     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1068     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1069
1070     // FIXME: Do we need to handle scalar-to-vector here?
1071     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1072
1073     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1074     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1075     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1076     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1077     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1078     // There is no BLENDI for byte vectors. We don't need to custom lower
1079     // some vselects for now.
1080     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1081
1082     // i8 and i16 vectors are custom , because the source register and source
1083     // source memory operand types are not the same width.  f32 vectors are
1084     // custom since the immediate controlling the insert encodes additional
1085     // information.
1086     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1087     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1088     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1089     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1090
1091     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1092     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1093     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1094     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1095
1096     // FIXME: these should be Legal but thats only for the case where
1097     // the index is constant.  For now custom expand to deal with that.
1098     if (Subtarget->is64Bit()) {
1099       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1100       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1101     }
1102   }
1103
1104   if (Subtarget->hasSSE2()) {
1105     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1106     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1107
1108     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1109     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1110
1111     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1112     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1113
1114     // In the customized shift lowering, the legal cases in AVX2 will be
1115     // recognized.
1116     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1117     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1118
1119     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1120     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1121
1122     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1123   }
1124
1125   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1126     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1127     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1128     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1129     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1130     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1131     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1132
1133     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1134     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1135     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1136
1137     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1138     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1139     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1140     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1141     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1142     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1143     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1144     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1145     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1146     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1147     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1148     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1149
1150     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1151     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1152     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1153     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1154     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1155     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1156     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1157     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1158     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1159     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1160     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1161     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1162
1163     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1164     // even though v8i16 is a legal type.
1165     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1166     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1167     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1168
1169     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1170     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1171     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1172
1173     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1174     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1175
1176     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1177
1178     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1179     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1180
1181     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1182     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1183
1184     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1185     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1186
1187     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1188     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1189     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1190     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1191
1192     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1193     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1194     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1195
1196     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1197     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1198     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1199     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1200
1201     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1202     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1203     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1204     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1205     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1206     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1207     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1208     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1209     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1210     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1211     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1212     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1213
1214     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1215       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1216       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1217       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1218       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1219       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1220       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1221     }
1222
1223     if (Subtarget->hasInt256()) {
1224       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1225       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1226       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1227       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1228
1229       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1230       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1231       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1232       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1233
1234       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1235       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1236       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1237       // Don't lower v32i8 because there is no 128-bit byte mul
1238
1239       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1240       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1241       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1242       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1243
1244       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1245       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1246     } else {
1247       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1248       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1249       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1250       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1251
1252       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1253       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1254       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1255       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1256
1257       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1258       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1259       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1260       // Don't lower v32i8 because there is no 128-bit byte mul
1261     }
1262
1263     // In the customized shift lowering, the legal cases in AVX2 will be
1264     // recognized.
1265     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1266     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1267
1268     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1269     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1270
1271     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1272
1273     // Custom lower several nodes for 256-bit types.
1274     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1275              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1276       MVT VT = (MVT::SimpleValueType)i;
1277
1278       // Extract subvector is special because the value type
1279       // (result) is 128-bit but the source is 256-bit wide.
1280       if (VT.is128BitVector())
1281         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1282
1283       // Do not attempt to custom lower other non-256-bit vectors
1284       if (!VT.is256BitVector())
1285         continue;
1286
1287       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1288       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1289       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1290       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1291       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1292       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1293       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1294     }
1295
1296     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1297     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1298       MVT VT = (MVT::SimpleValueType)i;
1299
1300       // Do not attempt to promote non-256-bit vectors
1301       if (!VT.is256BitVector())
1302         continue;
1303
1304       setOperationAction(ISD::AND,    VT, Promote);
1305       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1306       setOperationAction(ISD::OR,     VT, Promote);
1307       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1308       setOperationAction(ISD::XOR,    VT, Promote);
1309       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1310       setOperationAction(ISD::LOAD,   VT, Promote);
1311       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1312       setOperationAction(ISD::SELECT, VT, Promote);
1313       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1314     }
1315   }
1316
1317   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1318     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1319     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1320     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1321     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1322
1323     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1324     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1325     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1326
1327     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1328     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1329     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1330     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1331     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1332     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1333     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1334     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1336     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1337     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1338
1339     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1340     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1341     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1342     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1343     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1344     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1345
1346     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1348     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1349     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1350     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1351     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1352     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1353     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1354
1355     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1356     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1357     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1359     if (Subtarget->is64Bit()) {
1360       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1361       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1362       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1363       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1364     }
1365     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1366     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1367     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1368     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1369     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1371     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1372     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1373     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1374     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1375
1376     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1377     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1378     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1379     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1380     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1381     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1382     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1383     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1384     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1385     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1386     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1387     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1388     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1389
1390     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1391     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1392     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1393     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1394     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1395     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1396
1397     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1398     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1399
1400     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1401
1402     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1403     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1404     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1405     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1406     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1407     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1408     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1409     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1410     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1411
1412     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1413     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1414
1415     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1416     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1417
1418     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1419
1420     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1421     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1422
1423     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1424     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1425
1426     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1427     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1428
1429     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1430     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1431     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1432     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1433     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1434     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1435
1436     // Custom lower several nodes.
1437     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1438              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1439       MVT VT = (MVT::SimpleValueType)i;
1440
1441       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1442       // Extract subvector is special because the value type
1443       // (result) is 256/128-bit but the source is 512-bit wide.
1444       if (VT.is128BitVector() || VT.is256BitVector())
1445         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1446
1447       if (VT.getVectorElementType() == MVT::i1)
1448         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1449
1450       // Do not attempt to custom lower other non-512-bit vectors
1451       if (!VT.is512BitVector())
1452         continue;
1453
1454       if ( EltSize >= 32) {
1455         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1456         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1457         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1458         setOperationAction(ISD::VSELECT,             VT, Legal);
1459         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1460         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1461         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1462       }
1463     }
1464     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1465       MVT VT = (MVT::SimpleValueType)i;
1466
1467       // Do not attempt to promote non-256-bit vectors
1468       if (!VT.is512BitVector())
1469         continue;
1470
1471       setOperationAction(ISD::SELECT, VT, Promote);
1472       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1473     }
1474   }// has  AVX-512
1475
1476   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1477   // of this type with custom code.
1478   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1479            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1480     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1481                        Custom);
1482   }
1483
1484   // We want to custom lower some of our intrinsics.
1485   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1486   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1487   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1488   if (!Subtarget->is64Bit())
1489     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1490
1491   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1492   // handle type legalization for these operations here.
1493   //
1494   // FIXME: We really should do custom legalization for addition and
1495   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1496   // than generic legalization for 64-bit multiplication-with-overflow, though.
1497   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1498     // Add/Sub/Mul with overflow operations are custom lowered.
1499     MVT VT = IntVTs[i];
1500     setOperationAction(ISD::SADDO, VT, Custom);
1501     setOperationAction(ISD::UADDO, VT, Custom);
1502     setOperationAction(ISD::SSUBO, VT, Custom);
1503     setOperationAction(ISD::USUBO, VT, Custom);
1504     setOperationAction(ISD::SMULO, VT, Custom);
1505     setOperationAction(ISD::UMULO, VT, Custom);
1506   }
1507
1508   // There are no 8-bit 3-address imul/mul instructions
1509   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1510   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1511
1512   if (!Subtarget->is64Bit()) {
1513     // These libcalls are not available in 32-bit.
1514     setLibcallName(RTLIB::SHL_I128, nullptr);
1515     setLibcallName(RTLIB::SRL_I128, nullptr);
1516     setLibcallName(RTLIB::SRA_I128, nullptr);
1517   }
1518
1519   // Combine sin / cos into one node or libcall if possible.
1520   if (Subtarget->hasSinCos()) {
1521     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1522     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1523     if (Subtarget->isTargetDarwin()) {
1524       // For MacOSX, we don't want to the normal expansion of a libcall to
1525       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1526       // traffic.
1527       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1528       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1529     }
1530   }
1531
1532   if (Subtarget->isTargetWin64()) {
1533     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1534     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1535     setOperationAction(ISD::SREM, MVT::i128, Custom);
1536     setOperationAction(ISD::UREM, MVT::i128, Custom);
1537     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1538     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1539   }
1540
1541   // We have target-specific dag combine patterns for the following nodes:
1542   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1543   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1544   setTargetDAGCombine(ISD::VSELECT);
1545   setTargetDAGCombine(ISD::SELECT);
1546   setTargetDAGCombine(ISD::SHL);
1547   setTargetDAGCombine(ISD::SRA);
1548   setTargetDAGCombine(ISD::SRL);
1549   setTargetDAGCombine(ISD::OR);
1550   setTargetDAGCombine(ISD::AND);
1551   setTargetDAGCombine(ISD::ADD);
1552   setTargetDAGCombine(ISD::FADD);
1553   setTargetDAGCombine(ISD::FSUB);
1554   setTargetDAGCombine(ISD::FMA);
1555   setTargetDAGCombine(ISD::SUB);
1556   setTargetDAGCombine(ISD::LOAD);
1557   setTargetDAGCombine(ISD::STORE);
1558   setTargetDAGCombine(ISD::ZERO_EXTEND);
1559   setTargetDAGCombine(ISD::ANY_EXTEND);
1560   setTargetDAGCombine(ISD::SIGN_EXTEND);
1561   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1562   setTargetDAGCombine(ISD::TRUNCATE);
1563   setTargetDAGCombine(ISD::SINT_TO_FP);
1564   setTargetDAGCombine(ISD::SETCC);
1565   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1566   if (Subtarget->is64Bit())
1567     setTargetDAGCombine(ISD::MUL);
1568   setTargetDAGCombine(ISD::XOR);
1569
1570   computeRegisterProperties();
1571
1572   // On Darwin, -Os means optimize for size without hurting performance,
1573   // do not reduce the limit.
1574   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1575   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1576   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1577   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1578   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1579   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1580   setPrefLoopAlignment(4); // 2^4 bytes.
1581
1582   // Predictable cmov don't hurt on atom because it's in-order.
1583   PredictableSelectIsExpensive = !Subtarget->isAtom();
1584
1585   setPrefFunctionAlignment(4); // 2^4 bytes.
1586 }
1587
1588 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1589   if (!VT.isVector())
1590     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1591
1592   if (Subtarget->hasAVX512())
1593     switch(VT.getVectorNumElements()) {
1594     case  8: return MVT::v8i1;
1595     case 16: return MVT::v16i1;
1596   }
1597
1598   return VT.changeVectorElementTypeToInteger();
1599 }
1600
1601 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1602 /// the desired ByVal argument alignment.
1603 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1604   if (MaxAlign == 16)
1605     return;
1606   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1607     if (VTy->getBitWidth() == 128)
1608       MaxAlign = 16;
1609   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1610     unsigned EltAlign = 0;
1611     getMaxByValAlign(ATy->getElementType(), EltAlign);
1612     if (EltAlign > MaxAlign)
1613       MaxAlign = EltAlign;
1614   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1615     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1616       unsigned EltAlign = 0;
1617       getMaxByValAlign(STy->getElementType(i), EltAlign);
1618       if (EltAlign > MaxAlign)
1619         MaxAlign = EltAlign;
1620       if (MaxAlign == 16)
1621         break;
1622     }
1623   }
1624 }
1625
1626 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1627 /// function arguments in the caller parameter area. For X86, aggregates
1628 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1629 /// are at 4-byte boundaries.
1630 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1631   if (Subtarget->is64Bit()) {
1632     // Max of 8 and alignment of type.
1633     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1634     if (TyAlign > 8)
1635       return TyAlign;
1636     return 8;
1637   }
1638
1639   unsigned Align = 4;
1640   if (Subtarget->hasSSE1())
1641     getMaxByValAlign(Ty, Align);
1642   return Align;
1643 }
1644
1645 /// getOptimalMemOpType - Returns the target specific optimal type for load
1646 /// and store operations as a result of memset, memcpy, and memmove
1647 /// lowering. If DstAlign is zero that means it's safe to destination
1648 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1649 /// means there isn't a need to check it against alignment requirement,
1650 /// probably because the source does not need to be loaded. If 'IsMemset' is
1651 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1652 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1653 /// source is constant so it does not need to be loaded.
1654 /// It returns EVT::Other if the type should be determined using generic
1655 /// target-independent logic.
1656 EVT
1657 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1658                                        unsigned DstAlign, unsigned SrcAlign,
1659                                        bool IsMemset, bool ZeroMemset,
1660                                        bool MemcpyStrSrc,
1661                                        MachineFunction &MF) const {
1662   const Function *F = MF.getFunction();
1663   if ((!IsMemset || ZeroMemset) &&
1664       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1665                                        Attribute::NoImplicitFloat)) {
1666     if (Size >= 16 &&
1667         (Subtarget->isUnalignedMemAccessFast() ||
1668          ((DstAlign == 0 || DstAlign >= 16) &&
1669           (SrcAlign == 0 || SrcAlign >= 16)))) {
1670       if (Size >= 32) {
1671         if (Subtarget->hasInt256())
1672           return MVT::v8i32;
1673         if (Subtarget->hasFp256())
1674           return MVT::v8f32;
1675       }
1676       if (Subtarget->hasSSE2())
1677         return MVT::v4i32;
1678       if (Subtarget->hasSSE1())
1679         return MVT::v4f32;
1680     } else if (!MemcpyStrSrc && Size >= 8 &&
1681                !Subtarget->is64Bit() &&
1682                Subtarget->hasSSE2()) {
1683       // Do not use f64 to lower memcpy if source is string constant. It's
1684       // better to use i32 to avoid the loads.
1685       return MVT::f64;
1686     }
1687   }
1688   if (Subtarget->is64Bit() && Size >= 8)
1689     return MVT::i64;
1690   return MVT::i32;
1691 }
1692
1693 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1694   if (VT == MVT::f32)
1695     return X86ScalarSSEf32;
1696   else if (VT == MVT::f64)
1697     return X86ScalarSSEf64;
1698   return true;
1699 }
1700
1701 bool
1702 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1703                                                  unsigned,
1704                                                  bool *Fast) const {
1705   if (Fast)
1706     *Fast = Subtarget->isUnalignedMemAccessFast();
1707   return true;
1708 }
1709
1710 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1711 /// current function.  The returned value is a member of the
1712 /// MachineJumpTableInfo::JTEntryKind enum.
1713 unsigned X86TargetLowering::getJumpTableEncoding() const {
1714   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1715   // symbol.
1716   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1717       Subtarget->isPICStyleGOT())
1718     return MachineJumpTableInfo::EK_Custom32;
1719
1720   // Otherwise, use the normal jump table encoding heuristics.
1721   return TargetLowering::getJumpTableEncoding();
1722 }
1723
1724 const MCExpr *
1725 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1726                                              const MachineBasicBlock *MBB,
1727                                              unsigned uid,MCContext &Ctx) const{
1728   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1729          Subtarget->isPICStyleGOT());
1730   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1731   // entries.
1732   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1733                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1734 }
1735
1736 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1737 /// jumptable.
1738 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1739                                                     SelectionDAG &DAG) const {
1740   if (!Subtarget->is64Bit())
1741     // This doesn't have SDLoc associated with it, but is not really the
1742     // same as a Register.
1743     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1744   return Table;
1745 }
1746
1747 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1748 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1749 /// MCExpr.
1750 const MCExpr *X86TargetLowering::
1751 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1752                              MCContext &Ctx) const {
1753   // X86-64 uses RIP relative addressing based on the jump table label.
1754   if (Subtarget->isPICStyleRIPRel())
1755     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1756
1757   // Otherwise, the reference is relative to the PIC base.
1758   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1759 }
1760
1761 // FIXME: Why this routine is here? Move to RegInfo!
1762 std::pair<const TargetRegisterClass*, uint8_t>
1763 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1764   const TargetRegisterClass *RRC = nullptr;
1765   uint8_t Cost = 1;
1766   switch (VT.SimpleTy) {
1767   default:
1768     return TargetLowering::findRepresentativeClass(VT);
1769   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1770     RRC = Subtarget->is64Bit() ?
1771       (const TargetRegisterClass*)&X86::GR64RegClass :
1772       (const TargetRegisterClass*)&X86::GR32RegClass;
1773     break;
1774   case MVT::x86mmx:
1775     RRC = &X86::VR64RegClass;
1776     break;
1777   case MVT::f32: case MVT::f64:
1778   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1779   case MVT::v4f32: case MVT::v2f64:
1780   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1781   case MVT::v4f64:
1782     RRC = &X86::VR128RegClass;
1783     break;
1784   }
1785   return std::make_pair(RRC, Cost);
1786 }
1787
1788 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1789                                                unsigned &Offset) const {
1790   if (!Subtarget->isTargetLinux())
1791     return false;
1792
1793   if (Subtarget->is64Bit()) {
1794     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1795     Offset = 0x28;
1796     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1797       AddressSpace = 256;
1798     else
1799       AddressSpace = 257;
1800   } else {
1801     // %gs:0x14 on i386
1802     Offset = 0x14;
1803     AddressSpace = 256;
1804   }
1805   return true;
1806 }
1807
1808 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1809                                             unsigned DestAS) const {
1810   assert(SrcAS != DestAS && "Expected different address spaces!");
1811
1812   return SrcAS < 256 && DestAS < 256;
1813 }
1814
1815 //===----------------------------------------------------------------------===//
1816 //               Return Value Calling Convention Implementation
1817 //===----------------------------------------------------------------------===//
1818
1819 #include "X86GenCallingConv.inc"
1820
1821 bool
1822 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1823                                   MachineFunction &MF, bool isVarArg,
1824                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1825                         LLVMContext &Context) const {
1826   SmallVector<CCValAssign, 16> RVLocs;
1827   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1828                  RVLocs, Context);
1829   return CCInfo.CheckReturn(Outs, RetCC_X86);
1830 }
1831
1832 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1833   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1834   return ScratchRegs;
1835 }
1836
1837 SDValue
1838 X86TargetLowering::LowerReturn(SDValue Chain,
1839                                CallingConv::ID CallConv, bool isVarArg,
1840                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1841                                const SmallVectorImpl<SDValue> &OutVals,
1842                                SDLoc dl, SelectionDAG &DAG) const {
1843   MachineFunction &MF = DAG.getMachineFunction();
1844   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1845
1846   SmallVector<CCValAssign, 16> RVLocs;
1847   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1848                  RVLocs, *DAG.getContext());
1849   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1850
1851   SDValue Flag;
1852   SmallVector<SDValue, 6> RetOps;
1853   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1854   // Operand #1 = Bytes To Pop
1855   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1856                    MVT::i16));
1857
1858   // Copy the result values into the output registers.
1859   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1860     CCValAssign &VA = RVLocs[i];
1861     assert(VA.isRegLoc() && "Can only return in registers!");
1862     SDValue ValToCopy = OutVals[i];
1863     EVT ValVT = ValToCopy.getValueType();
1864
1865     // Promote values to the appropriate types
1866     if (VA.getLocInfo() == CCValAssign::SExt)
1867       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1868     else if (VA.getLocInfo() == CCValAssign::ZExt)
1869       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1870     else if (VA.getLocInfo() == CCValAssign::AExt)
1871       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1872     else if (VA.getLocInfo() == CCValAssign::BCvt)
1873       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1874
1875     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1876            "Unexpected FP-extend for return value.");  
1877
1878     // If this is x86-64, and we disabled SSE, we can't return FP values,
1879     // or SSE or MMX vectors.
1880     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1881          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1882           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1883       report_fatal_error("SSE register return with SSE disabled");
1884     }
1885     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1886     // llvm-gcc has never done it right and no one has noticed, so this
1887     // should be OK for now.
1888     if (ValVT == MVT::f64 &&
1889         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1890       report_fatal_error("SSE2 register return with SSE2 disabled");
1891
1892     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1893     // the RET instruction and handled by the FP Stackifier.
1894     if (VA.getLocReg() == X86::ST0 ||
1895         VA.getLocReg() == X86::ST1) {
1896       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1897       // change the value to the FP stack register class.
1898       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1899         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1900       RetOps.push_back(ValToCopy);
1901       // Don't emit a copytoreg.
1902       continue;
1903     }
1904
1905     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1906     // which is returned in RAX / RDX.
1907     if (Subtarget->is64Bit()) {
1908       if (ValVT == MVT::x86mmx) {
1909         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1910           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1911           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1912                                   ValToCopy);
1913           // If we don't have SSE2 available, convert to v4f32 so the generated
1914           // register is legal.
1915           if (!Subtarget->hasSSE2())
1916             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1917         }
1918       }
1919     }
1920
1921     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1922     Flag = Chain.getValue(1);
1923     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1924   }
1925
1926   // The x86-64 ABIs require that for returning structs by value we copy
1927   // the sret argument into %rax/%eax (depending on ABI) for the return.
1928   // Win32 requires us to put the sret argument to %eax as well.
1929   // We saved the argument into a virtual register in the entry block,
1930   // so now we copy the value out and into %rax/%eax.
1931   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1932       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1933     MachineFunction &MF = DAG.getMachineFunction();
1934     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1935     unsigned Reg = FuncInfo->getSRetReturnReg();
1936     assert(Reg &&
1937            "SRetReturnReg should have been set in LowerFormalArguments().");
1938     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1939
1940     unsigned RetValReg
1941         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1942           X86::RAX : X86::EAX;
1943     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1944     Flag = Chain.getValue(1);
1945
1946     // RAX/EAX now acts like a return value.
1947     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1948   }
1949
1950   RetOps[0] = Chain;  // Update chain.
1951
1952   // Add the flag if we have it.
1953   if (Flag.getNode())
1954     RetOps.push_back(Flag);
1955
1956   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1957 }
1958
1959 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1960   if (N->getNumValues() != 1)
1961     return false;
1962   if (!N->hasNUsesOfValue(1, 0))
1963     return false;
1964
1965   SDValue TCChain = Chain;
1966   SDNode *Copy = *N->use_begin();
1967   if (Copy->getOpcode() == ISD::CopyToReg) {
1968     // If the copy has a glue operand, we conservatively assume it isn't safe to
1969     // perform a tail call.
1970     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1971       return false;
1972     TCChain = Copy->getOperand(0);
1973   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1974     return false;
1975
1976   bool HasRet = false;
1977   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1978        UI != UE; ++UI) {
1979     if (UI->getOpcode() != X86ISD::RET_FLAG)
1980       return false;
1981     HasRet = true;
1982   }
1983
1984   if (!HasRet)
1985     return false;
1986
1987   Chain = TCChain;
1988   return true;
1989 }
1990
1991 MVT
1992 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1993                                             ISD::NodeType ExtendKind) const {
1994   MVT ReturnMVT;
1995   // TODO: Is this also valid on 32-bit?
1996   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1997     ReturnMVT = MVT::i8;
1998   else
1999     ReturnMVT = MVT::i32;
2000
2001   MVT MinVT = getRegisterType(ReturnMVT);
2002   return VT.bitsLT(MinVT) ? MinVT : VT;
2003 }
2004
2005 /// LowerCallResult - Lower the result values of a call into the
2006 /// appropriate copies out of appropriate physical registers.
2007 ///
2008 SDValue
2009 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2010                                    CallingConv::ID CallConv, bool isVarArg,
2011                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2012                                    SDLoc dl, SelectionDAG &DAG,
2013                                    SmallVectorImpl<SDValue> &InVals) const {
2014
2015   // Assign locations to each value returned by this call.
2016   SmallVector<CCValAssign, 16> RVLocs;
2017   bool Is64Bit = Subtarget->is64Bit();
2018   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2019                  getTargetMachine(), RVLocs, *DAG.getContext());
2020   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2021
2022   // Copy all of the result registers out of their specified physreg.
2023   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2024     CCValAssign &VA = RVLocs[i];
2025     EVT CopyVT = VA.getValVT();
2026
2027     // If this is x86-64, and we disabled SSE, we can't return FP values
2028     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2029         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2030       report_fatal_error("SSE register return with SSE disabled");
2031     }
2032
2033     SDValue Val;
2034
2035     // If this is a call to a function that returns an fp value on the floating
2036     // point stack, we must guarantee the value is popped from the stack, so
2037     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2038     // if the return value is not used. We use the FpPOP_RETVAL instruction
2039     // instead.
2040     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2041       // If we prefer to use the value in xmm registers, copy it out as f80 and
2042       // use a truncate to move it from fp stack reg to xmm reg.
2043       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2044       SDValue Ops[] = { Chain, InFlag };
2045       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2046                                          MVT::Other, MVT::Glue, Ops), 1);
2047       Val = Chain.getValue(0);
2048
2049       // Round the f80 to the right size, which also moves it to the appropriate
2050       // xmm register.
2051       if (CopyVT != VA.getValVT())
2052         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2053                           // This truncation won't change the value.
2054                           DAG.getIntPtrConstant(1));
2055     } else {
2056       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2057                                  CopyVT, InFlag).getValue(1);
2058       Val = Chain.getValue(0);
2059     }
2060     InFlag = Chain.getValue(2);
2061     InVals.push_back(Val);
2062   }
2063
2064   return Chain;
2065 }
2066
2067 //===----------------------------------------------------------------------===//
2068 //                C & StdCall & Fast Calling Convention implementation
2069 //===----------------------------------------------------------------------===//
2070 //  StdCall calling convention seems to be standard for many Windows' API
2071 //  routines and around. It differs from C calling convention just a little:
2072 //  callee should clean up the stack, not caller. Symbols should be also
2073 //  decorated in some fancy way :) It doesn't support any vector arguments.
2074 //  For info on fast calling convention see Fast Calling Convention (tail call)
2075 //  implementation LowerX86_32FastCCCallTo.
2076
2077 /// CallIsStructReturn - Determines whether a call uses struct return
2078 /// semantics.
2079 enum StructReturnType {
2080   NotStructReturn,
2081   RegStructReturn,
2082   StackStructReturn
2083 };
2084 static StructReturnType
2085 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2086   if (Outs.empty())
2087     return NotStructReturn;
2088
2089   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2090   if (!Flags.isSRet())
2091     return NotStructReturn;
2092   if (Flags.isInReg())
2093     return RegStructReturn;
2094   return StackStructReturn;
2095 }
2096
2097 /// ArgsAreStructReturn - Determines whether a function uses struct
2098 /// return semantics.
2099 static StructReturnType
2100 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2101   if (Ins.empty())
2102     return NotStructReturn;
2103
2104   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2105   if (!Flags.isSRet())
2106     return NotStructReturn;
2107   if (Flags.isInReg())
2108     return RegStructReturn;
2109   return StackStructReturn;
2110 }
2111
2112 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2113 /// by "Src" to address "Dst" with size and alignment information specified by
2114 /// the specific parameter attribute. The copy will be passed as a byval
2115 /// function parameter.
2116 static SDValue
2117 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2118                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2119                           SDLoc dl) {
2120   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2121
2122   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2123                        /*isVolatile*/false, /*AlwaysInline=*/true,
2124                        MachinePointerInfo(), MachinePointerInfo());
2125 }
2126
2127 /// IsTailCallConvention - Return true if the calling convention is one that
2128 /// supports tail call optimization.
2129 static bool IsTailCallConvention(CallingConv::ID CC) {
2130   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2131           CC == CallingConv::HiPE);
2132 }
2133
2134 /// \brief Return true if the calling convention is a C calling convention.
2135 static bool IsCCallConvention(CallingConv::ID CC) {
2136   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2137           CC == CallingConv::X86_64_SysV);
2138 }
2139
2140 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2141   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2142     return false;
2143
2144   CallSite CS(CI);
2145   CallingConv::ID CalleeCC = CS.getCallingConv();
2146   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2147     return false;
2148
2149   return true;
2150 }
2151
2152 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2153 /// a tailcall target by changing its ABI.
2154 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2155                                    bool GuaranteedTailCallOpt) {
2156   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2157 }
2158
2159 SDValue
2160 X86TargetLowering::LowerMemArgument(SDValue Chain,
2161                                     CallingConv::ID CallConv,
2162                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2163                                     SDLoc dl, SelectionDAG &DAG,
2164                                     const CCValAssign &VA,
2165                                     MachineFrameInfo *MFI,
2166                                     unsigned i) const {
2167   // Create the nodes corresponding to a load from this parameter slot.
2168   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2169   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2170                               getTargetMachine().Options.GuaranteedTailCallOpt);
2171   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2172   EVT ValVT;
2173
2174   // If value is passed by pointer we have address passed instead of the value
2175   // itself.
2176   if (VA.getLocInfo() == CCValAssign::Indirect)
2177     ValVT = VA.getLocVT();
2178   else
2179     ValVT = VA.getValVT();
2180
2181   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2182   // changed with more analysis.
2183   // In case of tail call optimization mark all arguments mutable. Since they
2184   // could be overwritten by lowering of arguments in case of a tail call.
2185   if (Flags.isByVal()) {
2186     unsigned Bytes = Flags.getByValSize();
2187     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2188     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2189     return DAG.getFrameIndex(FI, getPointerTy());
2190   } else {
2191     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2192                                     VA.getLocMemOffset(), isImmutable);
2193     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2194     return DAG.getLoad(ValVT, dl, Chain, FIN,
2195                        MachinePointerInfo::getFixedStack(FI),
2196                        false, false, false, 0);
2197   }
2198 }
2199
2200 SDValue
2201 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2202                                         CallingConv::ID CallConv,
2203                                         bool isVarArg,
2204                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2205                                         SDLoc dl,
2206                                         SelectionDAG &DAG,
2207                                         SmallVectorImpl<SDValue> &InVals)
2208                                           const {
2209   MachineFunction &MF = DAG.getMachineFunction();
2210   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2211
2212   const Function* Fn = MF.getFunction();
2213   if (Fn->hasExternalLinkage() &&
2214       Subtarget->isTargetCygMing() &&
2215       Fn->getName() == "main")
2216     FuncInfo->setForceFramePointer(true);
2217
2218   MachineFrameInfo *MFI = MF.getFrameInfo();
2219   bool Is64Bit = Subtarget->is64Bit();
2220   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2221
2222   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2223          "Var args not supported with calling convention fastcc, ghc or hipe");
2224
2225   // Assign locations to all of the incoming arguments.
2226   SmallVector<CCValAssign, 16> ArgLocs;
2227   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2228                  ArgLocs, *DAG.getContext());
2229
2230   // Allocate shadow area for Win64
2231   if (IsWin64)
2232     CCInfo.AllocateStack(32, 8);
2233
2234   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2235
2236   unsigned LastVal = ~0U;
2237   SDValue ArgValue;
2238   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2239     CCValAssign &VA = ArgLocs[i];
2240     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2241     // places.
2242     assert(VA.getValNo() != LastVal &&
2243            "Don't support value assigned to multiple locs yet");
2244     (void)LastVal;
2245     LastVal = VA.getValNo();
2246
2247     if (VA.isRegLoc()) {
2248       EVT RegVT = VA.getLocVT();
2249       const TargetRegisterClass *RC;
2250       if (RegVT == MVT::i32)
2251         RC = &X86::GR32RegClass;
2252       else if (Is64Bit && RegVT == MVT::i64)
2253         RC = &X86::GR64RegClass;
2254       else if (RegVT == MVT::f32)
2255         RC = &X86::FR32RegClass;
2256       else if (RegVT == MVT::f64)
2257         RC = &X86::FR64RegClass;
2258       else if (RegVT.is512BitVector())
2259         RC = &X86::VR512RegClass;
2260       else if (RegVT.is256BitVector())
2261         RC = &X86::VR256RegClass;
2262       else if (RegVT.is128BitVector())
2263         RC = &X86::VR128RegClass;
2264       else if (RegVT == MVT::x86mmx)
2265         RC = &X86::VR64RegClass;
2266       else if (RegVT == MVT::i1)
2267         RC = &X86::VK1RegClass;
2268       else if (RegVT == MVT::v8i1)
2269         RC = &X86::VK8RegClass;
2270       else if (RegVT == MVT::v16i1)
2271         RC = &X86::VK16RegClass;
2272       else
2273         llvm_unreachable("Unknown argument type!");
2274
2275       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2276       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2277
2278       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2279       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2280       // right size.
2281       if (VA.getLocInfo() == CCValAssign::SExt)
2282         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2283                                DAG.getValueType(VA.getValVT()));
2284       else if (VA.getLocInfo() == CCValAssign::ZExt)
2285         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2286                                DAG.getValueType(VA.getValVT()));
2287       else if (VA.getLocInfo() == CCValAssign::BCvt)
2288         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2289
2290       if (VA.isExtInLoc()) {
2291         // Handle MMX values passed in XMM regs.
2292         if (RegVT.isVector())
2293           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2294         else
2295           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2296       }
2297     } else {
2298       assert(VA.isMemLoc());
2299       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2300     }
2301
2302     // If value is passed via pointer - do a load.
2303     if (VA.getLocInfo() == CCValAssign::Indirect)
2304       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2305                              MachinePointerInfo(), false, false, false, 0);
2306
2307     InVals.push_back(ArgValue);
2308   }
2309
2310   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2311     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2312       // The x86-64 ABIs require that for returning structs by value we copy
2313       // the sret argument into %rax/%eax (depending on ABI) for the return.
2314       // Win32 requires us to put the sret argument to %eax as well.
2315       // Save the argument into a virtual register so that we can access it
2316       // from the return points.
2317       if (Ins[i].Flags.isSRet()) {
2318         unsigned Reg = FuncInfo->getSRetReturnReg();
2319         if (!Reg) {
2320           MVT PtrTy = getPointerTy();
2321           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2322           FuncInfo->setSRetReturnReg(Reg);
2323         }
2324         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2325         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2326         break;
2327       }
2328     }
2329   }
2330
2331   unsigned StackSize = CCInfo.getNextStackOffset();
2332   // Align stack specially for tail calls.
2333   if (FuncIsMadeTailCallSafe(CallConv,
2334                              MF.getTarget().Options.GuaranteedTailCallOpt))
2335     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2336
2337   // If the function takes variable number of arguments, make a frame index for
2338   // the start of the first vararg value... for expansion of llvm.va_start.
2339   if (isVarArg) {
2340     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2341                     CallConv != CallingConv::X86_ThisCall)) {
2342       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2343     }
2344     if (Is64Bit) {
2345       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2346
2347       // FIXME: We should really autogenerate these arrays
2348       static const MCPhysReg GPR64ArgRegsWin64[] = {
2349         X86::RCX, X86::RDX, X86::R8,  X86::R9
2350       };
2351       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2352         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2353       };
2354       static const MCPhysReg XMMArgRegs64Bit[] = {
2355         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2356         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2357       };
2358       const MCPhysReg *GPR64ArgRegs;
2359       unsigned NumXMMRegs = 0;
2360
2361       if (IsWin64) {
2362         // The XMM registers which might contain var arg parameters are shadowed
2363         // in their paired GPR.  So we only need to save the GPR to their home
2364         // slots.
2365         TotalNumIntRegs = 4;
2366         GPR64ArgRegs = GPR64ArgRegsWin64;
2367       } else {
2368         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2369         GPR64ArgRegs = GPR64ArgRegs64Bit;
2370
2371         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2372                                                 TotalNumXMMRegs);
2373       }
2374       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2375                                                        TotalNumIntRegs);
2376
2377       bool NoImplicitFloatOps = Fn->getAttributes().
2378         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2379       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2380              "SSE register cannot be used when SSE is disabled!");
2381       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2382                NoImplicitFloatOps) &&
2383              "SSE register cannot be used when SSE is disabled!");
2384       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2385           !Subtarget->hasSSE1())
2386         // Kernel mode asks for SSE to be disabled, so don't push them
2387         // on the stack.
2388         TotalNumXMMRegs = 0;
2389
2390       if (IsWin64) {
2391         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2392         // Get to the caller-allocated home save location.  Add 8 to account
2393         // for the return address.
2394         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2395         FuncInfo->setRegSaveFrameIndex(
2396           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2397         // Fixup to set vararg frame on shadow area (4 x i64).
2398         if (NumIntRegs < 4)
2399           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2400       } else {
2401         // For X86-64, if there are vararg parameters that are passed via
2402         // registers, then we must store them to their spots on the stack so
2403         // they may be loaded by deferencing the result of va_next.
2404         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2405         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2406         FuncInfo->setRegSaveFrameIndex(
2407           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2408                                false));
2409       }
2410
2411       // Store the integer parameter registers.
2412       SmallVector<SDValue, 8> MemOps;
2413       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2414                                         getPointerTy());
2415       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2416       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2417         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2418                                   DAG.getIntPtrConstant(Offset));
2419         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2420                                      &X86::GR64RegClass);
2421         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2422         SDValue Store =
2423           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2424                        MachinePointerInfo::getFixedStack(
2425                          FuncInfo->getRegSaveFrameIndex(), Offset),
2426                        false, false, 0);
2427         MemOps.push_back(Store);
2428         Offset += 8;
2429       }
2430
2431       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2432         // Now store the XMM (fp + vector) parameter registers.
2433         SmallVector<SDValue, 11> SaveXMMOps;
2434         SaveXMMOps.push_back(Chain);
2435
2436         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2437         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2438         SaveXMMOps.push_back(ALVal);
2439
2440         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2441                                FuncInfo->getRegSaveFrameIndex()));
2442         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2443                                FuncInfo->getVarArgsFPOffset()));
2444
2445         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2446           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2447                                        &X86::VR128RegClass);
2448           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2449           SaveXMMOps.push_back(Val);
2450         }
2451         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2452                                      MVT::Other, SaveXMMOps));
2453       }
2454
2455       if (!MemOps.empty())
2456         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2457     }
2458   }
2459
2460   // Some CCs need callee pop.
2461   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2462                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2463     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2464   } else {
2465     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2466     // If this is an sret function, the return should pop the hidden pointer.
2467     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2468         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2469         argsAreStructReturn(Ins) == StackStructReturn)
2470       FuncInfo->setBytesToPopOnReturn(4);
2471   }
2472
2473   if (!Is64Bit) {
2474     // RegSaveFrameIndex is X86-64 only.
2475     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2476     if (CallConv == CallingConv::X86_FastCall ||
2477         CallConv == CallingConv::X86_ThisCall)
2478       // fastcc functions can't have varargs.
2479       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2480   }
2481
2482   FuncInfo->setArgumentStackSize(StackSize);
2483
2484   return Chain;
2485 }
2486
2487 SDValue
2488 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2489                                     SDValue StackPtr, SDValue Arg,
2490                                     SDLoc dl, SelectionDAG &DAG,
2491                                     const CCValAssign &VA,
2492                                     ISD::ArgFlagsTy Flags) const {
2493   unsigned LocMemOffset = VA.getLocMemOffset();
2494   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2495   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2496   if (Flags.isByVal())
2497     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2498
2499   return DAG.getStore(Chain, dl, Arg, PtrOff,
2500                       MachinePointerInfo::getStack(LocMemOffset),
2501                       false, false, 0);
2502 }
2503
2504 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2505 /// optimization is performed and it is required.
2506 SDValue
2507 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2508                                            SDValue &OutRetAddr, SDValue Chain,
2509                                            bool IsTailCall, bool Is64Bit,
2510                                            int FPDiff, SDLoc dl) const {
2511   // Adjust the Return address stack slot.
2512   EVT VT = getPointerTy();
2513   OutRetAddr = getReturnAddressFrameIndex(DAG);
2514
2515   // Load the "old" Return address.
2516   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2517                            false, false, false, 0);
2518   return SDValue(OutRetAddr.getNode(), 1);
2519 }
2520
2521 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2522 /// optimization is performed and it is required (FPDiff!=0).
2523 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2524                                         SDValue Chain, SDValue RetAddrFrIdx,
2525                                         EVT PtrVT, unsigned SlotSize,
2526                                         int FPDiff, SDLoc dl) {
2527   // Store the return address to the appropriate stack slot.
2528   if (!FPDiff) return Chain;
2529   // Calculate the new stack slot for the return address.
2530   int NewReturnAddrFI =
2531     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2532                                          false);
2533   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2534   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2535                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2536                        false, false, 0);
2537   return Chain;
2538 }
2539
2540 SDValue
2541 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2542                              SmallVectorImpl<SDValue> &InVals) const {
2543   SelectionDAG &DAG                     = CLI.DAG;
2544   SDLoc &dl                             = CLI.DL;
2545   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2546   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2547   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2548   SDValue Chain                         = CLI.Chain;
2549   SDValue Callee                        = CLI.Callee;
2550   CallingConv::ID CallConv              = CLI.CallConv;
2551   bool &isTailCall                      = CLI.IsTailCall;
2552   bool isVarArg                         = CLI.IsVarArg;
2553
2554   MachineFunction &MF = DAG.getMachineFunction();
2555   bool Is64Bit        = Subtarget->is64Bit();
2556   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2557   StructReturnType SR = callIsStructReturn(Outs);
2558   bool IsSibcall      = false;
2559
2560   if (MF.getTarget().Options.DisableTailCalls)
2561     isTailCall = false;
2562
2563   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2564   if (IsMustTail) {
2565     // Force this to be a tail call.  The verifier rules are enough to ensure
2566     // that we can lower this successfully without moving the return address
2567     // around.
2568     isTailCall = true;
2569   } else if (isTailCall) {
2570     // Check if it's really possible to do a tail call.
2571     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2572                     isVarArg, SR != NotStructReturn,
2573                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2574                     Outs, OutVals, Ins, DAG);
2575
2576     // Sibcalls are automatically detected tailcalls which do not require
2577     // ABI changes.
2578     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2579       IsSibcall = true;
2580
2581     if (isTailCall)
2582       ++NumTailCalls;
2583   }
2584
2585   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2586          "Var args not supported with calling convention fastcc, ghc or hipe");
2587
2588   // Analyze operands of the call, assigning locations to each operand.
2589   SmallVector<CCValAssign, 16> ArgLocs;
2590   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2591                  ArgLocs, *DAG.getContext());
2592
2593   // Allocate shadow area for Win64
2594   if (IsWin64)
2595     CCInfo.AllocateStack(32, 8);
2596
2597   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2598
2599   // Get a count of how many bytes are to be pushed on the stack.
2600   unsigned NumBytes = CCInfo.getNextStackOffset();
2601   if (IsSibcall)
2602     // This is a sibcall. The memory operands are available in caller's
2603     // own caller's stack.
2604     NumBytes = 0;
2605   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2606            IsTailCallConvention(CallConv))
2607     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2608
2609   int FPDiff = 0;
2610   if (isTailCall && !IsSibcall && !IsMustTail) {
2611     // Lower arguments at fp - stackoffset + fpdiff.
2612     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2613     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2614
2615     FPDiff = NumBytesCallerPushed - NumBytes;
2616
2617     // Set the delta of movement of the returnaddr stackslot.
2618     // But only set if delta is greater than previous delta.
2619     if (FPDiff < X86Info->getTCReturnAddrDelta())
2620       X86Info->setTCReturnAddrDelta(FPDiff);
2621   }
2622
2623   unsigned NumBytesToPush = NumBytes;
2624   unsigned NumBytesToPop = NumBytes;
2625
2626   // If we have an inalloca argument, all stack space has already been allocated
2627   // for us and be right at the top of the stack.  We don't support multiple
2628   // arguments passed in memory when using inalloca.
2629   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2630     NumBytesToPush = 0;
2631     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2632            "an inalloca argument must be the only memory argument");
2633   }
2634
2635   if (!IsSibcall)
2636     Chain = DAG.getCALLSEQ_START(
2637         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2638
2639   SDValue RetAddrFrIdx;
2640   // Load return address for tail calls.
2641   if (isTailCall && FPDiff)
2642     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2643                                     Is64Bit, FPDiff, dl);
2644
2645   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2646   SmallVector<SDValue, 8> MemOpChains;
2647   SDValue StackPtr;
2648
2649   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2650   // of tail call optimization arguments are handle later.
2651   const X86RegisterInfo *RegInfo =
2652     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2653   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2654     // Skip inalloca arguments, they have already been written.
2655     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2656     if (Flags.isInAlloca())
2657       continue;
2658
2659     CCValAssign &VA = ArgLocs[i];
2660     EVT RegVT = VA.getLocVT();
2661     SDValue Arg = OutVals[i];
2662     bool isByVal = Flags.isByVal();
2663
2664     // Promote the value if needed.
2665     switch (VA.getLocInfo()) {
2666     default: llvm_unreachable("Unknown loc info!");
2667     case CCValAssign::Full: break;
2668     case CCValAssign::SExt:
2669       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2670       break;
2671     case CCValAssign::ZExt:
2672       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2673       break;
2674     case CCValAssign::AExt:
2675       if (RegVT.is128BitVector()) {
2676         // Special case: passing MMX values in XMM registers.
2677         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2678         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2679         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2680       } else
2681         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2682       break;
2683     case CCValAssign::BCvt:
2684       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2685       break;
2686     case CCValAssign::Indirect: {
2687       // Store the argument.
2688       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2689       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2690       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2691                            MachinePointerInfo::getFixedStack(FI),
2692                            false, false, 0);
2693       Arg = SpillSlot;
2694       break;
2695     }
2696     }
2697
2698     if (VA.isRegLoc()) {
2699       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2700       if (isVarArg && IsWin64) {
2701         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2702         // shadow reg if callee is a varargs function.
2703         unsigned ShadowReg = 0;
2704         switch (VA.getLocReg()) {
2705         case X86::XMM0: ShadowReg = X86::RCX; break;
2706         case X86::XMM1: ShadowReg = X86::RDX; break;
2707         case X86::XMM2: ShadowReg = X86::R8; break;
2708         case X86::XMM3: ShadowReg = X86::R9; break;
2709         }
2710         if (ShadowReg)
2711           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2712       }
2713     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2714       assert(VA.isMemLoc());
2715       if (!StackPtr.getNode())
2716         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2717                                       getPointerTy());
2718       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2719                                              dl, DAG, VA, Flags));
2720     }
2721   }
2722
2723   if (!MemOpChains.empty())
2724     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2725
2726   if (Subtarget->isPICStyleGOT()) {
2727     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2728     // GOT pointer.
2729     if (!isTailCall) {
2730       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2731                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2732     } else {
2733       // If we are tail calling and generating PIC/GOT style code load the
2734       // address of the callee into ECX. The value in ecx is used as target of
2735       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2736       // for tail calls on PIC/GOT architectures. Normally we would just put the
2737       // address of GOT into ebx and then call target@PLT. But for tail calls
2738       // ebx would be restored (since ebx is callee saved) before jumping to the
2739       // target@PLT.
2740
2741       // Note: The actual moving to ECX is done further down.
2742       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2743       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2744           !G->getGlobal()->hasProtectedVisibility())
2745         Callee = LowerGlobalAddress(Callee, DAG);
2746       else if (isa<ExternalSymbolSDNode>(Callee))
2747         Callee = LowerExternalSymbol(Callee, DAG);
2748     }
2749   }
2750
2751   if (Is64Bit && isVarArg && !IsWin64) {
2752     // From AMD64 ABI document:
2753     // For calls that may call functions that use varargs or stdargs
2754     // (prototype-less calls or calls to functions containing ellipsis (...) in
2755     // the declaration) %al is used as hidden argument to specify the number
2756     // of SSE registers used. The contents of %al do not need to match exactly
2757     // the number of registers, but must be an ubound on the number of SSE
2758     // registers used and is in the range 0 - 8 inclusive.
2759
2760     // Count the number of XMM registers allocated.
2761     static const MCPhysReg XMMArgRegs[] = {
2762       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2763       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2764     };
2765     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2766     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2767            && "SSE registers cannot be used when SSE is disabled");
2768
2769     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2770                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2771   }
2772
2773   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2774   // don't need this because the eligibility check rejects calls that require
2775   // shuffling arguments passed in memory.
2776   if (!IsSibcall && isTailCall) {
2777     // Force all the incoming stack arguments to be loaded from the stack
2778     // before any new outgoing arguments are stored to the stack, because the
2779     // outgoing stack slots may alias the incoming argument stack slots, and
2780     // the alias isn't otherwise explicit. This is slightly more conservative
2781     // than necessary, because it means that each store effectively depends
2782     // on every argument instead of just those arguments it would clobber.
2783     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2784
2785     SmallVector<SDValue, 8> MemOpChains2;
2786     SDValue FIN;
2787     int FI = 0;
2788     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2789       CCValAssign &VA = ArgLocs[i];
2790       if (VA.isRegLoc())
2791         continue;
2792       assert(VA.isMemLoc());
2793       SDValue Arg = OutVals[i];
2794       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2795       // Skip inalloca arguments.  They don't require any work.
2796       if (Flags.isInAlloca())
2797         continue;
2798       // Create frame index.
2799       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2800       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2801       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2802       FIN = DAG.getFrameIndex(FI, getPointerTy());
2803
2804       if (Flags.isByVal()) {
2805         // Copy relative to framepointer.
2806         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2807         if (!StackPtr.getNode())
2808           StackPtr = DAG.getCopyFromReg(Chain, dl,
2809                                         RegInfo->getStackRegister(),
2810                                         getPointerTy());
2811         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2812
2813         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2814                                                          ArgChain,
2815                                                          Flags, DAG, dl));
2816       } else {
2817         // Store relative to framepointer.
2818         MemOpChains2.push_back(
2819           DAG.getStore(ArgChain, dl, Arg, FIN,
2820                        MachinePointerInfo::getFixedStack(FI),
2821                        false, false, 0));
2822       }
2823     }
2824
2825     if (!MemOpChains2.empty())
2826       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2827
2828     // Store the return address to the appropriate stack slot.
2829     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2830                                      getPointerTy(), RegInfo->getSlotSize(),
2831                                      FPDiff, dl);
2832   }
2833
2834   // Build a sequence of copy-to-reg nodes chained together with token chain
2835   // and flag operands which copy the outgoing args into registers.
2836   SDValue InFlag;
2837   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2838     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2839                              RegsToPass[i].second, InFlag);
2840     InFlag = Chain.getValue(1);
2841   }
2842
2843   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2844     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2845     // In the 64-bit large code model, we have to make all calls
2846     // through a register, since the call instruction's 32-bit
2847     // pc-relative offset may not be large enough to hold the whole
2848     // address.
2849   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2850     // If the callee is a GlobalAddress node (quite common, every direct call
2851     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2852     // it.
2853
2854     // We should use extra load for direct calls to dllimported functions in
2855     // non-JIT mode.
2856     const GlobalValue *GV = G->getGlobal();
2857     if (!GV->hasDLLImportStorageClass()) {
2858       unsigned char OpFlags = 0;
2859       bool ExtraLoad = false;
2860       unsigned WrapperKind = ISD::DELETED_NODE;
2861
2862       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2863       // external symbols most go through the PLT in PIC mode.  If the symbol
2864       // has hidden or protected visibility, or if it is static or local, then
2865       // we don't need to use the PLT - we can directly call it.
2866       if (Subtarget->isTargetELF() &&
2867           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2868           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2869         OpFlags = X86II::MO_PLT;
2870       } else if (Subtarget->isPICStyleStubAny() &&
2871                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2872                  (!Subtarget->getTargetTriple().isMacOSX() ||
2873                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2874         // PC-relative references to external symbols should go through $stub,
2875         // unless we're building with the leopard linker or later, which
2876         // automatically synthesizes these stubs.
2877         OpFlags = X86II::MO_DARWIN_STUB;
2878       } else if (Subtarget->isPICStyleRIPRel() &&
2879                  isa<Function>(GV) &&
2880                  cast<Function>(GV)->getAttributes().
2881                    hasAttribute(AttributeSet::FunctionIndex,
2882                                 Attribute::NonLazyBind)) {
2883         // If the function is marked as non-lazy, generate an indirect call
2884         // which loads from the GOT directly. This avoids runtime overhead
2885         // at the cost of eager binding (and one extra byte of encoding).
2886         OpFlags = X86II::MO_GOTPCREL;
2887         WrapperKind = X86ISD::WrapperRIP;
2888         ExtraLoad = true;
2889       }
2890
2891       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2892                                           G->getOffset(), OpFlags);
2893
2894       // Add a wrapper if needed.
2895       if (WrapperKind != ISD::DELETED_NODE)
2896         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2897       // Add extra indirection if needed.
2898       if (ExtraLoad)
2899         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2900                              MachinePointerInfo::getGOT(),
2901                              false, false, false, 0);
2902     }
2903   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2904     unsigned char OpFlags = 0;
2905
2906     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2907     // external symbols should go through the PLT.
2908     if (Subtarget->isTargetELF() &&
2909         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2910       OpFlags = X86II::MO_PLT;
2911     } else if (Subtarget->isPICStyleStubAny() &&
2912                (!Subtarget->getTargetTriple().isMacOSX() ||
2913                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2914       // PC-relative references to external symbols should go through $stub,
2915       // unless we're building with the leopard linker or later, which
2916       // automatically synthesizes these stubs.
2917       OpFlags = X86II::MO_DARWIN_STUB;
2918     }
2919
2920     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2921                                          OpFlags);
2922   }
2923
2924   // Returns a chain & a flag for retval copy to use.
2925   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2926   SmallVector<SDValue, 8> Ops;
2927
2928   if (!IsSibcall && isTailCall) {
2929     Chain = DAG.getCALLSEQ_END(Chain,
2930                                DAG.getIntPtrConstant(NumBytesToPop, true),
2931                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2932     InFlag = Chain.getValue(1);
2933   }
2934
2935   Ops.push_back(Chain);
2936   Ops.push_back(Callee);
2937
2938   if (isTailCall)
2939     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2940
2941   // Add argument registers to the end of the list so that they are known live
2942   // into the call.
2943   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2944     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2945                                   RegsToPass[i].second.getValueType()));
2946
2947   // Add a register mask operand representing the call-preserved registers.
2948   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2949   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2950   assert(Mask && "Missing call preserved mask for calling convention");
2951   Ops.push_back(DAG.getRegisterMask(Mask));
2952
2953   if (InFlag.getNode())
2954     Ops.push_back(InFlag);
2955
2956   if (isTailCall) {
2957     // We used to do:
2958     //// If this is the first return lowered for this function, add the regs
2959     //// to the liveout set for the function.
2960     // This isn't right, although it's probably harmless on x86; liveouts
2961     // should be computed from returns not tail calls.  Consider a void
2962     // function making a tail call to a function returning int.
2963     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2964   }
2965
2966   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2967   InFlag = Chain.getValue(1);
2968
2969   // Create the CALLSEQ_END node.
2970   unsigned NumBytesForCalleeToPop;
2971   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2972                        getTargetMachine().Options.GuaranteedTailCallOpt))
2973     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2974   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2975            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2976            SR == StackStructReturn)
2977     // If this is a call to a struct-return function, the callee
2978     // pops the hidden struct pointer, so we have to push it back.
2979     // This is common for Darwin/X86, Linux & Mingw32 targets.
2980     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2981     NumBytesForCalleeToPop = 4;
2982   else
2983     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2984
2985   // Returns a flag for retval copy to use.
2986   if (!IsSibcall) {
2987     Chain = DAG.getCALLSEQ_END(Chain,
2988                                DAG.getIntPtrConstant(NumBytesToPop, true),
2989                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2990                                                      true),
2991                                InFlag, dl);
2992     InFlag = Chain.getValue(1);
2993   }
2994
2995   // Handle result values, copying them out of physregs into vregs that we
2996   // return.
2997   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2998                          Ins, dl, DAG, InVals);
2999 }
3000
3001 //===----------------------------------------------------------------------===//
3002 //                Fast Calling Convention (tail call) implementation
3003 //===----------------------------------------------------------------------===//
3004
3005 //  Like std call, callee cleans arguments, convention except that ECX is
3006 //  reserved for storing the tail called function address. Only 2 registers are
3007 //  free for argument passing (inreg). Tail call optimization is performed
3008 //  provided:
3009 //                * tailcallopt is enabled
3010 //                * caller/callee are fastcc
3011 //  On X86_64 architecture with GOT-style position independent code only local
3012 //  (within module) calls are supported at the moment.
3013 //  To keep the stack aligned according to platform abi the function
3014 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3015 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3016 //  If a tail called function callee has more arguments than the caller the
3017 //  caller needs to make sure that there is room to move the RETADDR to. This is
3018 //  achieved by reserving an area the size of the argument delta right after the
3019 //  original REtADDR, but before the saved framepointer or the spilled registers
3020 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3021 //  stack layout:
3022 //    arg1
3023 //    arg2
3024 //    RETADDR
3025 //    [ new RETADDR
3026 //      move area ]
3027 //    (possible EBP)
3028 //    ESI
3029 //    EDI
3030 //    local1 ..
3031
3032 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3033 /// for a 16 byte align requirement.
3034 unsigned
3035 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3036                                                SelectionDAG& DAG) const {
3037   MachineFunction &MF = DAG.getMachineFunction();
3038   const TargetMachine &TM = MF.getTarget();
3039   const X86RegisterInfo *RegInfo =
3040     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3041   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3042   unsigned StackAlignment = TFI.getStackAlignment();
3043   uint64_t AlignMask = StackAlignment - 1;
3044   int64_t Offset = StackSize;
3045   unsigned SlotSize = RegInfo->getSlotSize();
3046   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3047     // Number smaller than 12 so just add the difference.
3048     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3049   } else {
3050     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3051     Offset = ((~AlignMask) & Offset) + StackAlignment +
3052       (StackAlignment-SlotSize);
3053   }
3054   return Offset;
3055 }
3056
3057 /// MatchingStackOffset - Return true if the given stack call argument is
3058 /// already available in the same position (relatively) of the caller's
3059 /// incoming argument stack.
3060 static
3061 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3062                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3063                          const X86InstrInfo *TII) {
3064   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3065   int FI = INT_MAX;
3066   if (Arg.getOpcode() == ISD::CopyFromReg) {
3067     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3068     if (!TargetRegisterInfo::isVirtualRegister(VR))
3069       return false;
3070     MachineInstr *Def = MRI->getVRegDef(VR);
3071     if (!Def)
3072       return false;
3073     if (!Flags.isByVal()) {
3074       if (!TII->isLoadFromStackSlot(Def, FI))
3075         return false;
3076     } else {
3077       unsigned Opcode = Def->getOpcode();
3078       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3079           Def->getOperand(1).isFI()) {
3080         FI = Def->getOperand(1).getIndex();
3081         Bytes = Flags.getByValSize();
3082       } else
3083         return false;
3084     }
3085   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3086     if (Flags.isByVal())
3087       // ByVal argument is passed in as a pointer but it's now being
3088       // dereferenced. e.g.
3089       // define @foo(%struct.X* %A) {
3090       //   tail call @bar(%struct.X* byval %A)
3091       // }
3092       return false;
3093     SDValue Ptr = Ld->getBasePtr();
3094     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3095     if (!FINode)
3096       return false;
3097     FI = FINode->getIndex();
3098   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3099     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3100     FI = FINode->getIndex();
3101     Bytes = Flags.getByValSize();
3102   } else
3103     return false;
3104
3105   assert(FI != INT_MAX);
3106   if (!MFI->isFixedObjectIndex(FI))
3107     return false;
3108   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3109 }
3110
3111 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3112 /// for tail call optimization. Targets which want to do tail call
3113 /// optimization should implement this function.
3114 bool
3115 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3116                                                      CallingConv::ID CalleeCC,
3117                                                      bool isVarArg,
3118                                                      bool isCalleeStructRet,
3119                                                      bool isCallerStructRet,
3120                                                      Type *RetTy,
3121                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3122                                     const SmallVectorImpl<SDValue> &OutVals,
3123                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3124                                                      SelectionDAG &DAG) const {
3125   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3126     return false;
3127
3128   // If -tailcallopt is specified, make fastcc functions tail-callable.
3129   const MachineFunction &MF = DAG.getMachineFunction();
3130   const Function *CallerF = MF.getFunction();
3131
3132   // If the function return type is x86_fp80 and the callee return type is not,
3133   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3134   // perform a tailcall optimization here.
3135   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3136     return false;
3137
3138   CallingConv::ID CallerCC = CallerF->getCallingConv();
3139   bool CCMatch = CallerCC == CalleeCC;
3140   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3141   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3142
3143   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3144     if (IsTailCallConvention(CalleeCC) && CCMatch)
3145       return true;
3146     return false;
3147   }
3148
3149   // Look for obvious safe cases to perform tail call optimization that do not
3150   // require ABI changes. This is what gcc calls sibcall.
3151
3152   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3153   // emit a special epilogue.
3154   const X86RegisterInfo *RegInfo =
3155     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3156   if (RegInfo->needsStackRealignment(MF))
3157     return false;
3158
3159   // Also avoid sibcall optimization if either caller or callee uses struct
3160   // return semantics.
3161   if (isCalleeStructRet || isCallerStructRet)
3162     return false;
3163
3164   // An stdcall/thiscall caller is expected to clean up its arguments; the
3165   // callee isn't going to do that.
3166   // FIXME: this is more restrictive than needed. We could produce a tailcall
3167   // when the stack adjustment matches. For example, with a thiscall that takes
3168   // only one argument.
3169   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3170                    CallerCC == CallingConv::X86_ThisCall))
3171     return false;
3172
3173   // Do not sibcall optimize vararg calls unless all arguments are passed via
3174   // registers.
3175   if (isVarArg && !Outs.empty()) {
3176
3177     // Optimizing for varargs on Win64 is unlikely to be safe without
3178     // additional testing.
3179     if (IsCalleeWin64 || IsCallerWin64)
3180       return false;
3181
3182     SmallVector<CCValAssign, 16> ArgLocs;
3183     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3184                    getTargetMachine(), ArgLocs, *DAG.getContext());
3185
3186     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3187     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3188       if (!ArgLocs[i].isRegLoc())
3189         return false;
3190   }
3191
3192   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3193   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3194   // this into a sibcall.
3195   bool Unused = false;
3196   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3197     if (!Ins[i].Used) {
3198       Unused = true;
3199       break;
3200     }
3201   }
3202   if (Unused) {
3203     SmallVector<CCValAssign, 16> RVLocs;
3204     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3205                    getTargetMachine(), RVLocs, *DAG.getContext());
3206     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3207     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3208       CCValAssign &VA = RVLocs[i];
3209       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3210         return false;
3211     }
3212   }
3213
3214   // If the calling conventions do not match, then we'd better make sure the
3215   // results are returned in the same way as what the caller expects.
3216   if (!CCMatch) {
3217     SmallVector<CCValAssign, 16> RVLocs1;
3218     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3219                     getTargetMachine(), RVLocs1, *DAG.getContext());
3220     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3221
3222     SmallVector<CCValAssign, 16> RVLocs2;
3223     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3224                     getTargetMachine(), RVLocs2, *DAG.getContext());
3225     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3226
3227     if (RVLocs1.size() != RVLocs2.size())
3228       return false;
3229     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3230       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3231         return false;
3232       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3233         return false;
3234       if (RVLocs1[i].isRegLoc()) {
3235         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3236           return false;
3237       } else {
3238         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3239           return false;
3240       }
3241     }
3242   }
3243
3244   // If the callee takes no arguments then go on to check the results of the
3245   // call.
3246   if (!Outs.empty()) {
3247     // Check if stack adjustment is needed. For now, do not do this if any
3248     // argument is passed on the stack.
3249     SmallVector<CCValAssign, 16> ArgLocs;
3250     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3251                    getTargetMachine(), ArgLocs, *DAG.getContext());
3252
3253     // Allocate shadow area for Win64
3254     if (IsCalleeWin64)
3255       CCInfo.AllocateStack(32, 8);
3256
3257     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3258     if (CCInfo.getNextStackOffset()) {
3259       MachineFunction &MF = DAG.getMachineFunction();
3260       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3261         return false;
3262
3263       // Check if the arguments are already laid out in the right way as
3264       // the caller's fixed stack objects.
3265       MachineFrameInfo *MFI = MF.getFrameInfo();
3266       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3267       const X86InstrInfo *TII =
3268         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3269       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3270         CCValAssign &VA = ArgLocs[i];
3271         SDValue Arg = OutVals[i];
3272         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3273         if (VA.getLocInfo() == CCValAssign::Indirect)
3274           return false;
3275         if (!VA.isRegLoc()) {
3276           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3277                                    MFI, MRI, TII))
3278             return false;
3279         }
3280       }
3281     }
3282
3283     // If the tailcall address may be in a register, then make sure it's
3284     // possible to register allocate for it. In 32-bit, the call address can
3285     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3286     // callee-saved registers are restored. These happen to be the same
3287     // registers used to pass 'inreg' arguments so watch out for those.
3288     if (!Subtarget->is64Bit() &&
3289         ((!isa<GlobalAddressSDNode>(Callee) &&
3290           !isa<ExternalSymbolSDNode>(Callee)) ||
3291          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3292       unsigned NumInRegs = 0;
3293       // In PIC we need an extra register to formulate the address computation
3294       // for the callee.
3295       unsigned MaxInRegs =
3296           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3297
3298       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3299         CCValAssign &VA = ArgLocs[i];
3300         if (!VA.isRegLoc())
3301           continue;
3302         unsigned Reg = VA.getLocReg();
3303         switch (Reg) {
3304         default: break;
3305         case X86::EAX: case X86::EDX: case X86::ECX:
3306           if (++NumInRegs == MaxInRegs)
3307             return false;
3308           break;
3309         }
3310       }
3311     }
3312   }
3313
3314   return true;
3315 }
3316
3317 FastISel *
3318 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3319                                   const TargetLibraryInfo *libInfo) const {
3320   return X86::createFastISel(funcInfo, libInfo);
3321 }
3322
3323 //===----------------------------------------------------------------------===//
3324 //                           Other Lowering Hooks
3325 //===----------------------------------------------------------------------===//
3326
3327 static bool MayFoldLoad(SDValue Op) {
3328   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3329 }
3330
3331 static bool MayFoldIntoStore(SDValue Op) {
3332   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3333 }
3334
3335 static bool isTargetShuffle(unsigned Opcode) {
3336   switch(Opcode) {
3337   default: return false;
3338   case X86ISD::PSHUFD:
3339   case X86ISD::PSHUFHW:
3340   case X86ISD::PSHUFLW:
3341   case X86ISD::SHUFP:
3342   case X86ISD::PALIGNR:
3343   case X86ISD::MOVLHPS:
3344   case X86ISD::MOVLHPD:
3345   case X86ISD::MOVHLPS:
3346   case X86ISD::MOVLPS:
3347   case X86ISD::MOVLPD:
3348   case X86ISD::MOVSHDUP:
3349   case X86ISD::MOVSLDUP:
3350   case X86ISD::MOVDDUP:
3351   case X86ISD::MOVSS:
3352   case X86ISD::MOVSD:
3353   case X86ISD::UNPCKL:
3354   case X86ISD::UNPCKH:
3355   case X86ISD::VPERMILP:
3356   case X86ISD::VPERM2X128:
3357   case X86ISD::VPERMI:
3358     return true;
3359   }
3360 }
3361
3362 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3363                                     SDValue V1, SelectionDAG &DAG) {
3364   switch(Opc) {
3365   default: llvm_unreachable("Unknown x86 shuffle node");
3366   case X86ISD::MOVSHDUP:
3367   case X86ISD::MOVSLDUP:
3368   case X86ISD::MOVDDUP:
3369     return DAG.getNode(Opc, dl, VT, V1);
3370   }
3371 }
3372
3373 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3374                                     SDValue V1, unsigned TargetMask,
3375                                     SelectionDAG &DAG) {
3376   switch(Opc) {
3377   default: llvm_unreachable("Unknown x86 shuffle node");
3378   case X86ISD::PSHUFD:
3379   case X86ISD::PSHUFHW:
3380   case X86ISD::PSHUFLW:
3381   case X86ISD::VPERMILP:
3382   case X86ISD::VPERMI:
3383     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3384   }
3385 }
3386
3387 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3388                                     SDValue V1, SDValue V2, unsigned TargetMask,
3389                                     SelectionDAG &DAG) {
3390   switch(Opc) {
3391   default: llvm_unreachable("Unknown x86 shuffle node");
3392   case X86ISD::PALIGNR:
3393   case X86ISD::SHUFP:
3394   case X86ISD::VPERM2X128:
3395     return DAG.getNode(Opc, dl, VT, V1, V2,
3396                        DAG.getConstant(TargetMask, MVT::i8));
3397   }
3398 }
3399
3400 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3401                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3402   switch(Opc) {
3403   default: llvm_unreachable("Unknown x86 shuffle node");
3404   case X86ISD::MOVLHPS:
3405   case X86ISD::MOVLHPD:
3406   case X86ISD::MOVHLPS:
3407   case X86ISD::MOVLPS:
3408   case X86ISD::MOVLPD:
3409   case X86ISD::MOVSS:
3410   case X86ISD::MOVSD:
3411   case X86ISD::UNPCKL:
3412   case X86ISD::UNPCKH:
3413     return DAG.getNode(Opc, dl, VT, V1, V2);
3414   }
3415 }
3416
3417 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3418   MachineFunction &MF = DAG.getMachineFunction();
3419   const X86RegisterInfo *RegInfo =
3420     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3421   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3422   int ReturnAddrIndex = FuncInfo->getRAIndex();
3423
3424   if (ReturnAddrIndex == 0) {
3425     // Set up a frame object for the return address.
3426     unsigned SlotSize = RegInfo->getSlotSize();
3427     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3428                                                            -(int64_t)SlotSize,
3429                                                            false);
3430     FuncInfo->setRAIndex(ReturnAddrIndex);
3431   }
3432
3433   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3434 }
3435
3436 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3437                                        bool hasSymbolicDisplacement) {
3438   // Offset should fit into 32 bit immediate field.
3439   if (!isInt<32>(Offset))
3440     return false;
3441
3442   // If we don't have a symbolic displacement - we don't have any extra
3443   // restrictions.
3444   if (!hasSymbolicDisplacement)
3445     return true;
3446
3447   // FIXME: Some tweaks might be needed for medium code model.
3448   if (M != CodeModel::Small && M != CodeModel::Kernel)
3449     return false;
3450
3451   // For small code model we assume that latest object is 16MB before end of 31
3452   // bits boundary. We may also accept pretty large negative constants knowing
3453   // that all objects are in the positive half of address space.
3454   if (M == CodeModel::Small && Offset < 16*1024*1024)
3455     return true;
3456
3457   // For kernel code model we know that all object resist in the negative half
3458   // of 32bits address space. We may not accept negative offsets, since they may
3459   // be just off and we may accept pretty large positive ones.
3460   if (M == CodeModel::Kernel && Offset > 0)
3461     return true;
3462
3463   return false;
3464 }
3465
3466 /// isCalleePop - Determines whether the callee is required to pop its
3467 /// own arguments. Callee pop is necessary to support tail calls.
3468 bool X86::isCalleePop(CallingConv::ID CallingConv,
3469                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3470   if (IsVarArg)
3471     return false;
3472
3473   switch (CallingConv) {
3474   default:
3475     return false;
3476   case CallingConv::X86_StdCall:
3477     return !is64Bit;
3478   case CallingConv::X86_FastCall:
3479     return !is64Bit;
3480   case CallingConv::X86_ThisCall:
3481     return !is64Bit;
3482   case CallingConv::Fast:
3483     return TailCallOpt;
3484   case CallingConv::GHC:
3485     return TailCallOpt;
3486   case CallingConv::HiPE:
3487     return TailCallOpt;
3488   }
3489 }
3490
3491 /// \brief Return true if the condition is an unsigned comparison operation.
3492 static bool isX86CCUnsigned(unsigned X86CC) {
3493   switch (X86CC) {
3494   default: llvm_unreachable("Invalid integer condition!");
3495   case X86::COND_E:     return true;
3496   case X86::COND_G:     return false;
3497   case X86::COND_GE:    return false;
3498   case X86::COND_L:     return false;
3499   case X86::COND_LE:    return false;
3500   case X86::COND_NE:    return true;
3501   case X86::COND_B:     return true;
3502   case X86::COND_A:     return true;
3503   case X86::COND_BE:    return true;
3504   case X86::COND_AE:    return true;
3505   }
3506   llvm_unreachable("covered switch fell through?!");
3507 }
3508
3509 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3510 /// specific condition code, returning the condition code and the LHS/RHS of the
3511 /// comparison to make.
3512 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3513                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3514   if (!isFP) {
3515     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3516       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3517         // X > -1   -> X == 0, jump !sign.
3518         RHS = DAG.getConstant(0, RHS.getValueType());
3519         return X86::COND_NS;
3520       }
3521       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3522         // X < 0   -> X == 0, jump on sign.
3523         return X86::COND_S;
3524       }
3525       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3526         // X < 1   -> X <= 0
3527         RHS = DAG.getConstant(0, RHS.getValueType());
3528         return X86::COND_LE;
3529       }
3530     }
3531
3532     switch (SetCCOpcode) {
3533     default: llvm_unreachable("Invalid integer condition!");
3534     case ISD::SETEQ:  return X86::COND_E;
3535     case ISD::SETGT:  return X86::COND_G;
3536     case ISD::SETGE:  return X86::COND_GE;
3537     case ISD::SETLT:  return X86::COND_L;
3538     case ISD::SETLE:  return X86::COND_LE;
3539     case ISD::SETNE:  return X86::COND_NE;
3540     case ISD::SETULT: return X86::COND_B;
3541     case ISD::SETUGT: return X86::COND_A;
3542     case ISD::SETULE: return X86::COND_BE;
3543     case ISD::SETUGE: return X86::COND_AE;
3544     }
3545   }
3546
3547   // First determine if it is required or is profitable to flip the operands.
3548
3549   // If LHS is a foldable load, but RHS is not, flip the condition.
3550   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3551       !ISD::isNON_EXTLoad(RHS.getNode())) {
3552     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3553     std::swap(LHS, RHS);
3554   }
3555
3556   switch (SetCCOpcode) {
3557   default: break;
3558   case ISD::SETOLT:
3559   case ISD::SETOLE:
3560   case ISD::SETUGT:
3561   case ISD::SETUGE:
3562     std::swap(LHS, RHS);
3563     break;
3564   }
3565
3566   // On a floating point condition, the flags are set as follows:
3567   // ZF  PF  CF   op
3568   //  0 | 0 | 0 | X > Y
3569   //  0 | 0 | 1 | X < Y
3570   //  1 | 0 | 0 | X == Y
3571   //  1 | 1 | 1 | unordered
3572   switch (SetCCOpcode) {
3573   default: llvm_unreachable("Condcode should be pre-legalized away");
3574   case ISD::SETUEQ:
3575   case ISD::SETEQ:   return X86::COND_E;
3576   case ISD::SETOLT:              // flipped
3577   case ISD::SETOGT:
3578   case ISD::SETGT:   return X86::COND_A;
3579   case ISD::SETOLE:              // flipped
3580   case ISD::SETOGE:
3581   case ISD::SETGE:   return X86::COND_AE;
3582   case ISD::SETUGT:              // flipped
3583   case ISD::SETULT:
3584   case ISD::SETLT:   return X86::COND_B;
3585   case ISD::SETUGE:              // flipped
3586   case ISD::SETULE:
3587   case ISD::SETLE:   return X86::COND_BE;
3588   case ISD::SETONE:
3589   case ISD::SETNE:   return X86::COND_NE;
3590   case ISD::SETUO:   return X86::COND_P;
3591   case ISD::SETO:    return X86::COND_NP;
3592   case ISD::SETOEQ:
3593   case ISD::SETUNE:  return X86::COND_INVALID;
3594   }
3595 }
3596
3597 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3598 /// code. Current x86 isa includes the following FP cmov instructions:
3599 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3600 static bool hasFPCMov(unsigned X86CC) {
3601   switch (X86CC) {
3602   default:
3603     return false;
3604   case X86::COND_B:
3605   case X86::COND_BE:
3606   case X86::COND_E:
3607   case X86::COND_P:
3608   case X86::COND_A:
3609   case X86::COND_AE:
3610   case X86::COND_NE:
3611   case X86::COND_NP:
3612     return true;
3613   }
3614 }
3615
3616 /// isFPImmLegal - Returns true if the target can instruction select the
3617 /// specified FP immediate natively. If false, the legalizer will
3618 /// materialize the FP immediate as a load from a constant pool.
3619 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3620   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3621     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3622       return true;
3623   }
3624   return false;
3625 }
3626
3627 /// \brief Returns true if it is beneficial to convert a load of a constant
3628 /// to just the constant itself.
3629 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3630                                                           Type *Ty) const {
3631   assert(Ty->isIntegerTy());
3632
3633   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3634   if (BitSize == 0 || BitSize > 64)
3635     return false;
3636   return true;
3637 }
3638
3639 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3640 /// the specified range (L, H].
3641 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3642   return (Val < 0) || (Val >= Low && Val < Hi);
3643 }
3644
3645 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3646 /// specified value.
3647 static bool isUndefOrEqual(int Val, int CmpVal) {
3648   return (Val < 0 || Val == CmpVal);
3649 }
3650
3651 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3652 /// from position Pos and ending in Pos+Size, falls within the specified
3653 /// sequential range (L, L+Pos]. or is undef.
3654 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3655                                        unsigned Pos, unsigned Size, int Low) {
3656   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3657     if (!isUndefOrEqual(Mask[i], Low))
3658       return false;
3659   return true;
3660 }
3661
3662 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3663 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3664 /// the second operand.
3665 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3666   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3667     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3668   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3669     return (Mask[0] < 2 && Mask[1] < 2);
3670   return false;
3671 }
3672
3673 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3674 /// is suitable for input to PSHUFHW.
3675 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3676   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3677     return false;
3678
3679   // Lower quadword copied in order or undef.
3680   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3681     return false;
3682
3683   // Upper quadword shuffled.
3684   for (unsigned i = 4; i != 8; ++i)
3685     if (!isUndefOrInRange(Mask[i], 4, 8))
3686       return false;
3687
3688   if (VT == MVT::v16i16) {
3689     // Lower quadword copied in order or undef.
3690     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3691       return false;
3692
3693     // Upper quadword shuffled.
3694     for (unsigned i = 12; i != 16; ++i)
3695       if (!isUndefOrInRange(Mask[i], 12, 16))
3696         return false;
3697   }
3698
3699   return true;
3700 }
3701
3702 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3703 /// is suitable for input to PSHUFLW.
3704 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3705   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3706     return false;
3707
3708   // Upper quadword copied in order.
3709   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3710     return false;
3711
3712   // Lower quadword shuffled.
3713   for (unsigned i = 0; i != 4; ++i)
3714     if (!isUndefOrInRange(Mask[i], 0, 4))
3715       return false;
3716
3717   if (VT == MVT::v16i16) {
3718     // Upper quadword copied in order.
3719     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3720       return false;
3721
3722     // Lower quadword shuffled.
3723     for (unsigned i = 8; i != 12; ++i)
3724       if (!isUndefOrInRange(Mask[i], 8, 12))
3725         return false;
3726   }
3727
3728   return true;
3729 }
3730
3731 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3732 /// is suitable for input to PALIGNR.
3733 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3734                           const X86Subtarget *Subtarget) {
3735   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3736       (VT.is256BitVector() && !Subtarget->hasInt256()))
3737     return false;
3738
3739   unsigned NumElts = VT.getVectorNumElements();
3740   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3741   unsigned NumLaneElts = NumElts/NumLanes;
3742
3743   // Do not handle 64-bit element shuffles with palignr.
3744   if (NumLaneElts == 2)
3745     return false;
3746
3747   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3748     unsigned i;
3749     for (i = 0; i != NumLaneElts; ++i) {
3750       if (Mask[i+l] >= 0)
3751         break;
3752     }
3753
3754     // Lane is all undef, go to next lane
3755     if (i == NumLaneElts)
3756       continue;
3757
3758     int Start = Mask[i+l];
3759
3760     // Make sure its in this lane in one of the sources
3761     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3762         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3763       return false;
3764
3765     // If not lane 0, then we must match lane 0
3766     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3767       return false;
3768
3769     // Correct second source to be contiguous with first source
3770     if (Start >= (int)NumElts)
3771       Start -= NumElts - NumLaneElts;
3772
3773     // Make sure we're shifting in the right direction.
3774     if (Start <= (int)(i+l))
3775       return false;
3776
3777     Start -= i;
3778
3779     // Check the rest of the elements to see if they are consecutive.
3780     for (++i; i != NumLaneElts; ++i) {
3781       int Idx = Mask[i+l];
3782
3783       // Make sure its in this lane
3784       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3785           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3786         return false;
3787
3788       // If not lane 0, then we must match lane 0
3789       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3790         return false;
3791
3792       if (Idx >= (int)NumElts)
3793         Idx -= NumElts - NumLaneElts;
3794
3795       if (!isUndefOrEqual(Idx, Start+i))
3796         return false;
3797
3798     }
3799   }
3800
3801   return true;
3802 }
3803
3804 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3805 /// the two vector operands have swapped position.
3806 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3807                                      unsigned NumElems) {
3808   for (unsigned i = 0; i != NumElems; ++i) {
3809     int idx = Mask[i];
3810     if (idx < 0)
3811       continue;
3812     else if (idx < (int)NumElems)
3813       Mask[i] = idx + NumElems;
3814     else
3815       Mask[i] = idx - NumElems;
3816   }
3817 }
3818
3819 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3820 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3821 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3822 /// reverse of what x86 shuffles want.
3823 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3824
3825   unsigned NumElems = VT.getVectorNumElements();
3826   unsigned NumLanes = VT.getSizeInBits()/128;
3827   unsigned NumLaneElems = NumElems/NumLanes;
3828
3829   if (NumLaneElems != 2 && NumLaneElems != 4)
3830     return false;
3831
3832   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3833   bool symetricMaskRequired =
3834     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3835
3836   // VSHUFPSY divides the resulting vector into 4 chunks.
3837   // The sources are also splitted into 4 chunks, and each destination
3838   // chunk must come from a different source chunk.
3839   //
3840   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3841   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3842   //
3843   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3844   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3845   //
3846   // VSHUFPDY divides the resulting vector into 4 chunks.
3847   // The sources are also splitted into 4 chunks, and each destination
3848   // chunk must come from a different source chunk.
3849   //
3850   //  SRC1 =>      X3       X2       X1       X0
3851   //  SRC2 =>      Y3       Y2       Y1       Y0
3852   //
3853   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3854   //
3855   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3856   unsigned HalfLaneElems = NumLaneElems/2;
3857   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3858     for (unsigned i = 0; i != NumLaneElems; ++i) {
3859       int Idx = Mask[i+l];
3860       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3861       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3862         return false;
3863       // For VSHUFPSY, the mask of the second half must be the same as the
3864       // first but with the appropriate offsets. This works in the same way as
3865       // VPERMILPS works with masks.
3866       if (!symetricMaskRequired || Idx < 0)
3867         continue;
3868       if (MaskVal[i] < 0) {
3869         MaskVal[i] = Idx - l;
3870         continue;
3871       }
3872       if ((signed)(Idx - l) != MaskVal[i])
3873         return false;
3874     }
3875   }
3876
3877   return true;
3878 }
3879
3880 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3881 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3882 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3883   if (!VT.is128BitVector())
3884     return false;
3885
3886   unsigned NumElems = VT.getVectorNumElements();
3887
3888   if (NumElems != 4)
3889     return false;
3890
3891   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3892   return isUndefOrEqual(Mask[0], 6) &&
3893          isUndefOrEqual(Mask[1], 7) &&
3894          isUndefOrEqual(Mask[2], 2) &&
3895          isUndefOrEqual(Mask[3], 3);
3896 }
3897
3898 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3899 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3900 /// <2, 3, 2, 3>
3901 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3902   if (!VT.is128BitVector())
3903     return false;
3904
3905   unsigned NumElems = VT.getVectorNumElements();
3906
3907   if (NumElems != 4)
3908     return false;
3909
3910   return isUndefOrEqual(Mask[0], 2) &&
3911          isUndefOrEqual(Mask[1], 3) &&
3912          isUndefOrEqual(Mask[2], 2) &&
3913          isUndefOrEqual(Mask[3], 3);
3914 }
3915
3916 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3917 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3918 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3919   if (!VT.is128BitVector())
3920     return false;
3921
3922   unsigned NumElems = VT.getVectorNumElements();
3923
3924   if (NumElems != 2 && NumElems != 4)
3925     return false;
3926
3927   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3928     if (!isUndefOrEqual(Mask[i], i + NumElems))
3929       return false;
3930
3931   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3932     if (!isUndefOrEqual(Mask[i], i))
3933       return false;
3934
3935   return true;
3936 }
3937
3938 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3939 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3940 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3941   if (!VT.is128BitVector())
3942     return false;
3943
3944   unsigned NumElems = VT.getVectorNumElements();
3945
3946   if (NumElems != 2 && NumElems != 4)
3947     return false;
3948
3949   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3950     if (!isUndefOrEqual(Mask[i], i))
3951       return false;
3952
3953   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3954     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3955       return false;
3956
3957   return true;
3958 }
3959
3960 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3961 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3962 /// i. e: If all but one element come from the same vector.
3963 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3964   // TODO: Deal with AVX's VINSERTPS
3965   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3966     return false;
3967
3968   unsigned CorrectPosV1 = 0;
3969   unsigned CorrectPosV2 = 0;
3970   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3971     if (Mask[i] == i)
3972       ++CorrectPosV1;
3973     else if (Mask[i] == i + 4)
3974       ++CorrectPosV2;
3975
3976   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3977     // We have 3 elements from one vector, and one from another.
3978     return true;
3979
3980   return false;
3981 }
3982
3983 //
3984 // Some special combinations that can be optimized.
3985 //
3986 static
3987 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3988                                SelectionDAG &DAG) {
3989   MVT VT = SVOp->getSimpleValueType(0);
3990   SDLoc dl(SVOp);
3991
3992   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3993     return SDValue();
3994
3995   ArrayRef<int> Mask = SVOp->getMask();
3996
3997   // These are the special masks that may be optimized.
3998   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3999   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4000   bool MatchEvenMask = true;
4001   bool MatchOddMask  = true;
4002   for (int i=0; i<8; ++i) {
4003     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4004       MatchEvenMask = false;
4005     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4006       MatchOddMask = false;
4007   }
4008
4009   if (!MatchEvenMask && !MatchOddMask)
4010     return SDValue();
4011
4012   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4013
4014   SDValue Op0 = SVOp->getOperand(0);
4015   SDValue Op1 = SVOp->getOperand(1);
4016
4017   if (MatchEvenMask) {
4018     // Shift the second operand right to 32 bits.
4019     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4020     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4021   } else {
4022     // Shift the first operand left to 32 bits.
4023     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4024     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4025   }
4026   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4027   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4028 }
4029
4030 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4031 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4032 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4033                          bool HasInt256, bool V2IsSplat = false) {
4034
4035   assert(VT.getSizeInBits() >= 128 &&
4036          "Unsupported vector type for unpckl");
4037
4038   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4039   unsigned NumLanes;
4040   unsigned NumOf256BitLanes;
4041   unsigned NumElts = VT.getVectorNumElements();
4042   if (VT.is256BitVector()) {
4043     if (NumElts != 4 && NumElts != 8 &&
4044         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4045     return false;
4046     NumLanes = 2;
4047     NumOf256BitLanes = 1;
4048   } else if (VT.is512BitVector()) {
4049     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4050            "Unsupported vector type for unpckh");
4051     NumLanes = 2;
4052     NumOf256BitLanes = 2;
4053   } else {
4054     NumLanes = 1;
4055     NumOf256BitLanes = 1;
4056   }
4057
4058   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4059   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4060
4061   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4062     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4063       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4064         int BitI  = Mask[l256*NumEltsInStride+l+i];
4065         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4066         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4067           return false;
4068         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4069           return false;
4070         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4071           return false;
4072       }
4073     }
4074   }
4075   return true;
4076 }
4077
4078 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4079 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4080 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4081                          bool HasInt256, bool V2IsSplat = false) {
4082   assert(VT.getSizeInBits() >= 128 &&
4083          "Unsupported vector type for unpckh");
4084
4085   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4086   unsigned NumLanes;
4087   unsigned NumOf256BitLanes;
4088   unsigned NumElts = VT.getVectorNumElements();
4089   if (VT.is256BitVector()) {
4090     if (NumElts != 4 && NumElts != 8 &&
4091         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4092     return false;
4093     NumLanes = 2;
4094     NumOf256BitLanes = 1;
4095   } else if (VT.is512BitVector()) {
4096     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4097            "Unsupported vector type for unpckh");
4098     NumLanes = 2;
4099     NumOf256BitLanes = 2;
4100   } else {
4101     NumLanes = 1;
4102     NumOf256BitLanes = 1;
4103   }
4104
4105   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4106   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4107
4108   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4109     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4110       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4111         int BitI  = Mask[l256*NumEltsInStride+l+i];
4112         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4113         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4114           return false;
4115         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4116           return false;
4117         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4118           return false;
4119       }
4120     }
4121   }
4122   return true;
4123 }
4124
4125 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4126 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4127 /// <0, 0, 1, 1>
4128 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4129   unsigned NumElts = VT.getVectorNumElements();
4130   bool Is256BitVec = VT.is256BitVector();
4131
4132   if (VT.is512BitVector())
4133     return false;
4134   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4135          "Unsupported vector type for unpckh");
4136
4137   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4138       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4139     return false;
4140
4141   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4142   // FIXME: Need a better way to get rid of this, there's no latency difference
4143   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4144   // the former later. We should also remove the "_undef" special mask.
4145   if (NumElts == 4 && Is256BitVec)
4146     return false;
4147
4148   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4149   // independently on 128-bit lanes.
4150   unsigned NumLanes = VT.getSizeInBits()/128;
4151   unsigned NumLaneElts = NumElts/NumLanes;
4152
4153   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4154     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4155       int BitI  = Mask[l+i];
4156       int BitI1 = Mask[l+i+1];
4157
4158       if (!isUndefOrEqual(BitI, j))
4159         return false;
4160       if (!isUndefOrEqual(BitI1, j))
4161         return false;
4162     }
4163   }
4164
4165   return true;
4166 }
4167
4168 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4169 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4170 /// <2, 2, 3, 3>
4171 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4172   unsigned NumElts = VT.getVectorNumElements();
4173
4174   if (VT.is512BitVector())
4175     return false;
4176
4177   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4178          "Unsupported vector type for unpckh");
4179
4180   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4181       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4182     return false;
4183
4184   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4185   // independently on 128-bit lanes.
4186   unsigned NumLanes = VT.getSizeInBits()/128;
4187   unsigned NumLaneElts = NumElts/NumLanes;
4188
4189   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4190     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4191       int BitI  = Mask[l+i];
4192       int BitI1 = Mask[l+i+1];
4193       if (!isUndefOrEqual(BitI, j))
4194         return false;
4195       if (!isUndefOrEqual(BitI1, j))
4196         return false;
4197     }
4198   }
4199   return true;
4200 }
4201
4202 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4203 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4204 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4205   if (!VT.is512BitVector())
4206     return false;
4207
4208   unsigned NumElts = VT.getVectorNumElements();
4209   unsigned HalfSize = NumElts/2;
4210   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4211     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4212       *Imm = 1;
4213       return true;
4214     }
4215   }
4216   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4217     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4218       *Imm = 0;
4219       return true;
4220     }
4221   }
4222   return false;
4223 }
4224
4225 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4226 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4227 /// MOVSD, and MOVD, i.e. setting the lowest element.
4228 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4229   if (VT.getVectorElementType().getSizeInBits() < 32)
4230     return false;
4231   if (!VT.is128BitVector())
4232     return false;
4233
4234   unsigned NumElts = VT.getVectorNumElements();
4235
4236   if (!isUndefOrEqual(Mask[0], NumElts))
4237     return false;
4238
4239   for (unsigned i = 1; i != NumElts; ++i)
4240     if (!isUndefOrEqual(Mask[i], i))
4241       return false;
4242
4243   return true;
4244 }
4245
4246 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4247 /// as permutations between 128-bit chunks or halves. As an example: this
4248 /// shuffle bellow:
4249 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4250 /// The first half comes from the second half of V1 and the second half from the
4251 /// the second half of V2.
4252 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4253   if (!HasFp256 || !VT.is256BitVector())
4254     return false;
4255
4256   // The shuffle result is divided into half A and half B. In total the two
4257   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4258   // B must come from C, D, E or F.
4259   unsigned HalfSize = VT.getVectorNumElements()/2;
4260   bool MatchA = false, MatchB = false;
4261
4262   // Check if A comes from one of C, D, E, F.
4263   for (unsigned Half = 0; Half != 4; ++Half) {
4264     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4265       MatchA = true;
4266       break;
4267     }
4268   }
4269
4270   // Check if B comes from one of C, D, E, F.
4271   for (unsigned Half = 0; Half != 4; ++Half) {
4272     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4273       MatchB = true;
4274       break;
4275     }
4276   }
4277
4278   return MatchA && MatchB;
4279 }
4280
4281 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4282 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4283 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4284   MVT VT = SVOp->getSimpleValueType(0);
4285
4286   unsigned HalfSize = VT.getVectorNumElements()/2;
4287
4288   unsigned FstHalf = 0, SndHalf = 0;
4289   for (unsigned i = 0; i < HalfSize; ++i) {
4290     if (SVOp->getMaskElt(i) > 0) {
4291       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4292       break;
4293     }
4294   }
4295   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4296     if (SVOp->getMaskElt(i) > 0) {
4297       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4298       break;
4299     }
4300   }
4301
4302   return (FstHalf | (SndHalf << 4));
4303 }
4304
4305 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4306 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4307   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4308   if (EltSize < 32)
4309     return false;
4310
4311   unsigned NumElts = VT.getVectorNumElements();
4312   Imm8 = 0;
4313   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4314     for (unsigned i = 0; i != NumElts; ++i) {
4315       if (Mask[i] < 0)
4316         continue;
4317       Imm8 |= Mask[i] << (i*2);
4318     }
4319     return true;
4320   }
4321
4322   unsigned LaneSize = 4;
4323   SmallVector<int, 4> MaskVal(LaneSize, -1);
4324
4325   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4326     for (unsigned i = 0; i != LaneSize; ++i) {
4327       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4328         return false;
4329       if (Mask[i+l] < 0)
4330         continue;
4331       if (MaskVal[i] < 0) {
4332         MaskVal[i] = Mask[i+l] - l;
4333         Imm8 |= MaskVal[i] << (i*2);
4334         continue;
4335       }
4336       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4337         return false;
4338     }
4339   }
4340   return true;
4341 }
4342
4343 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4344 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4345 /// Note that VPERMIL mask matching is different depending whether theunderlying
4346 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4347 /// to the same elements of the low, but to the higher half of the source.
4348 /// In VPERMILPD the two lanes could be shuffled independently of each other
4349 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4350 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4351   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4352   if (VT.getSizeInBits() < 256 || EltSize < 32)
4353     return false;
4354   bool symetricMaskRequired = (EltSize == 32);
4355   unsigned NumElts = VT.getVectorNumElements();
4356
4357   unsigned NumLanes = VT.getSizeInBits()/128;
4358   unsigned LaneSize = NumElts/NumLanes;
4359   // 2 or 4 elements in one lane
4360
4361   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4362   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4363     for (unsigned i = 0; i != LaneSize; ++i) {
4364       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4365         return false;
4366       if (symetricMaskRequired) {
4367         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4368           ExpectedMaskVal[i] = Mask[i+l] - l;
4369           continue;
4370         }
4371         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4372           return false;
4373       }
4374     }
4375   }
4376   return true;
4377 }
4378
4379 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4380 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4381 /// element of vector 2 and the other elements to come from vector 1 in order.
4382 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4383                                bool V2IsSplat = false, bool V2IsUndef = false) {
4384   if (!VT.is128BitVector())
4385     return false;
4386
4387   unsigned NumOps = VT.getVectorNumElements();
4388   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4389     return false;
4390
4391   if (!isUndefOrEqual(Mask[0], 0))
4392     return false;
4393
4394   for (unsigned i = 1; i != NumOps; ++i)
4395     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4396           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4397           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4398       return false;
4399
4400   return true;
4401 }
4402
4403 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4404 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4405 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4406 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4407                            const X86Subtarget *Subtarget) {
4408   if (!Subtarget->hasSSE3())
4409     return false;
4410
4411   unsigned NumElems = VT.getVectorNumElements();
4412
4413   if ((VT.is128BitVector() && NumElems != 4) ||
4414       (VT.is256BitVector() && NumElems != 8) ||
4415       (VT.is512BitVector() && NumElems != 16))
4416     return false;
4417
4418   // "i+1" is the value the indexed mask element must have
4419   for (unsigned i = 0; i != NumElems; i += 2)
4420     if (!isUndefOrEqual(Mask[i], i+1) ||
4421         !isUndefOrEqual(Mask[i+1], i+1))
4422       return false;
4423
4424   return true;
4425 }
4426
4427 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4428 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4429 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4430 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4431                            const X86Subtarget *Subtarget) {
4432   if (!Subtarget->hasSSE3())
4433     return false;
4434
4435   unsigned NumElems = VT.getVectorNumElements();
4436
4437   if ((VT.is128BitVector() && NumElems != 4) ||
4438       (VT.is256BitVector() && NumElems != 8) ||
4439       (VT.is512BitVector() && NumElems != 16))
4440     return false;
4441
4442   // "i" is the value the indexed mask element must have
4443   for (unsigned i = 0; i != NumElems; i += 2)
4444     if (!isUndefOrEqual(Mask[i], i) ||
4445         !isUndefOrEqual(Mask[i+1], i))
4446       return false;
4447
4448   return true;
4449 }
4450
4451 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4452 /// specifies a shuffle of elements that is suitable for input to 256-bit
4453 /// version of MOVDDUP.
4454 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4455   if (!HasFp256 || !VT.is256BitVector())
4456     return false;
4457
4458   unsigned NumElts = VT.getVectorNumElements();
4459   if (NumElts != 4)
4460     return false;
4461
4462   for (unsigned i = 0; i != NumElts/2; ++i)
4463     if (!isUndefOrEqual(Mask[i], 0))
4464       return false;
4465   for (unsigned i = NumElts/2; i != NumElts; ++i)
4466     if (!isUndefOrEqual(Mask[i], NumElts/2))
4467       return false;
4468   return true;
4469 }
4470
4471 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4472 /// specifies a shuffle of elements that is suitable for input to 128-bit
4473 /// version of MOVDDUP.
4474 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4475   if (!VT.is128BitVector())
4476     return false;
4477
4478   unsigned e = VT.getVectorNumElements() / 2;
4479   for (unsigned i = 0; i != e; ++i)
4480     if (!isUndefOrEqual(Mask[i], i))
4481       return false;
4482   for (unsigned i = 0; i != e; ++i)
4483     if (!isUndefOrEqual(Mask[e+i], i))
4484       return false;
4485   return true;
4486 }
4487
4488 /// isVEXTRACTIndex - Return true if the specified
4489 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4490 /// suitable for instruction that extract 128 or 256 bit vectors
4491 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4492   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4493   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4494     return false;
4495
4496   // The index should be aligned on a vecWidth-bit boundary.
4497   uint64_t Index =
4498     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4499
4500   MVT VT = N->getSimpleValueType(0);
4501   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4502   bool Result = (Index * ElSize) % vecWidth == 0;
4503
4504   return Result;
4505 }
4506
4507 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4508 /// operand specifies a subvector insert that is suitable for input to
4509 /// insertion of 128 or 256-bit subvectors
4510 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4511   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4512   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4513     return false;
4514   // The index should be aligned on a vecWidth-bit boundary.
4515   uint64_t Index =
4516     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4517
4518   MVT VT = N->getSimpleValueType(0);
4519   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4520   bool Result = (Index * ElSize) % vecWidth == 0;
4521
4522   return Result;
4523 }
4524
4525 bool X86::isVINSERT128Index(SDNode *N) {
4526   return isVINSERTIndex(N, 128);
4527 }
4528
4529 bool X86::isVINSERT256Index(SDNode *N) {
4530   return isVINSERTIndex(N, 256);
4531 }
4532
4533 bool X86::isVEXTRACT128Index(SDNode *N) {
4534   return isVEXTRACTIndex(N, 128);
4535 }
4536
4537 bool X86::isVEXTRACT256Index(SDNode *N) {
4538   return isVEXTRACTIndex(N, 256);
4539 }
4540
4541 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4542 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4543 /// Handles 128-bit and 256-bit.
4544 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4545   MVT VT = N->getSimpleValueType(0);
4546
4547   assert((VT.getSizeInBits() >= 128) &&
4548          "Unsupported vector type for PSHUF/SHUFP");
4549
4550   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4551   // independently on 128-bit lanes.
4552   unsigned NumElts = VT.getVectorNumElements();
4553   unsigned NumLanes = VT.getSizeInBits()/128;
4554   unsigned NumLaneElts = NumElts/NumLanes;
4555
4556   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4557          "Only supports 2, 4 or 8 elements per lane");
4558
4559   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4560   unsigned Mask = 0;
4561   for (unsigned i = 0; i != NumElts; ++i) {
4562     int Elt = N->getMaskElt(i);
4563     if (Elt < 0) continue;
4564     Elt &= NumLaneElts - 1;
4565     unsigned ShAmt = (i << Shift) % 8;
4566     Mask |= Elt << ShAmt;
4567   }
4568
4569   return Mask;
4570 }
4571
4572 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4573 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4574 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4575   MVT VT = N->getSimpleValueType(0);
4576
4577   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4578          "Unsupported vector type for PSHUFHW");
4579
4580   unsigned NumElts = VT.getVectorNumElements();
4581
4582   unsigned Mask = 0;
4583   for (unsigned l = 0; l != NumElts; l += 8) {
4584     // 8 nodes per lane, but we only care about the last 4.
4585     for (unsigned i = 0; i < 4; ++i) {
4586       int Elt = N->getMaskElt(l+i+4);
4587       if (Elt < 0) continue;
4588       Elt &= 0x3; // only 2-bits.
4589       Mask |= Elt << (i * 2);
4590     }
4591   }
4592
4593   return Mask;
4594 }
4595
4596 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4597 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4598 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4599   MVT VT = N->getSimpleValueType(0);
4600
4601   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4602          "Unsupported vector type for PSHUFHW");
4603
4604   unsigned NumElts = VT.getVectorNumElements();
4605
4606   unsigned Mask = 0;
4607   for (unsigned l = 0; l != NumElts; l += 8) {
4608     // 8 nodes per lane, but we only care about the first 4.
4609     for (unsigned i = 0; i < 4; ++i) {
4610       int Elt = N->getMaskElt(l+i);
4611       if (Elt < 0) continue;
4612       Elt &= 0x3; // only 2-bits
4613       Mask |= Elt << (i * 2);
4614     }
4615   }
4616
4617   return Mask;
4618 }
4619
4620 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4621 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4622 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4623   MVT VT = SVOp->getSimpleValueType(0);
4624   unsigned EltSize = VT.is512BitVector() ? 1 :
4625     VT.getVectorElementType().getSizeInBits() >> 3;
4626
4627   unsigned NumElts = VT.getVectorNumElements();
4628   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4629   unsigned NumLaneElts = NumElts/NumLanes;
4630
4631   int Val = 0;
4632   unsigned i;
4633   for (i = 0; i != NumElts; ++i) {
4634     Val = SVOp->getMaskElt(i);
4635     if (Val >= 0)
4636       break;
4637   }
4638   if (Val >= (int)NumElts)
4639     Val -= NumElts - NumLaneElts;
4640
4641   assert(Val - i > 0 && "PALIGNR imm should be positive");
4642   return (Val - i) * EltSize;
4643 }
4644
4645 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4646   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4647   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4648     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4649
4650   uint64_t Index =
4651     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4652
4653   MVT VecVT = N->getOperand(0).getSimpleValueType();
4654   MVT ElVT = VecVT.getVectorElementType();
4655
4656   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4657   return Index / NumElemsPerChunk;
4658 }
4659
4660 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4661   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4662   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4663     llvm_unreachable("Illegal insert subvector for VINSERT");
4664
4665   uint64_t Index =
4666     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4667
4668   MVT VecVT = N->getSimpleValueType(0);
4669   MVT ElVT = VecVT.getVectorElementType();
4670
4671   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4672   return Index / NumElemsPerChunk;
4673 }
4674
4675 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4676 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4677 /// and VINSERTI128 instructions.
4678 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4679   return getExtractVEXTRACTImmediate(N, 128);
4680 }
4681
4682 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4683 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4684 /// and VINSERTI64x4 instructions.
4685 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4686   return getExtractVEXTRACTImmediate(N, 256);
4687 }
4688
4689 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4690 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4691 /// and VINSERTI128 instructions.
4692 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4693   return getInsertVINSERTImmediate(N, 128);
4694 }
4695
4696 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4697 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4698 /// and VINSERTI64x4 instructions.
4699 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4700   return getInsertVINSERTImmediate(N, 256);
4701 }
4702
4703 /// isZero - Returns true if Elt is a constant integer zero
4704 static bool isZero(SDValue V) {
4705   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4706   return C && C->isNullValue();
4707 }
4708
4709 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4710 /// constant +0.0.
4711 bool X86::isZeroNode(SDValue Elt) {
4712   if (isZero(Elt))
4713     return true;
4714   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4715     return CFP->getValueAPF().isPosZero();
4716   return false;
4717 }
4718
4719 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4720 /// their permute mask.
4721 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4722                                     SelectionDAG &DAG) {
4723   MVT VT = SVOp->getSimpleValueType(0);
4724   unsigned NumElems = VT.getVectorNumElements();
4725   SmallVector<int, 8> MaskVec;
4726
4727   for (unsigned i = 0; i != NumElems; ++i) {
4728     int Idx = SVOp->getMaskElt(i);
4729     if (Idx >= 0) {
4730       if (Idx < (int)NumElems)
4731         Idx += NumElems;
4732       else
4733         Idx -= NumElems;
4734     }
4735     MaskVec.push_back(Idx);
4736   }
4737   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4738                               SVOp->getOperand(0), &MaskVec[0]);
4739 }
4740
4741 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4742 /// match movhlps. The lower half elements should come from upper half of
4743 /// V1 (and in order), and the upper half elements should come from the upper
4744 /// half of V2 (and in order).
4745 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4746   if (!VT.is128BitVector())
4747     return false;
4748   if (VT.getVectorNumElements() != 4)
4749     return false;
4750   for (unsigned i = 0, e = 2; i != e; ++i)
4751     if (!isUndefOrEqual(Mask[i], i+2))
4752       return false;
4753   for (unsigned i = 2; i != 4; ++i)
4754     if (!isUndefOrEqual(Mask[i], i+4))
4755       return false;
4756   return true;
4757 }
4758
4759 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4760 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4761 /// required.
4762 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4763   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4764     return false;
4765   N = N->getOperand(0).getNode();
4766   if (!ISD::isNON_EXTLoad(N))
4767     return false;
4768   if (LD)
4769     *LD = cast<LoadSDNode>(N);
4770   return true;
4771 }
4772
4773 // Test whether the given value is a vector value which will be legalized
4774 // into a load.
4775 static bool WillBeConstantPoolLoad(SDNode *N) {
4776   if (N->getOpcode() != ISD::BUILD_VECTOR)
4777     return false;
4778
4779   // Check for any non-constant elements.
4780   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4781     switch (N->getOperand(i).getNode()->getOpcode()) {
4782     case ISD::UNDEF:
4783     case ISD::ConstantFP:
4784     case ISD::Constant:
4785       break;
4786     default:
4787       return false;
4788     }
4789
4790   // Vectors of all-zeros and all-ones are materialized with special
4791   // instructions rather than being loaded.
4792   return !ISD::isBuildVectorAllZeros(N) &&
4793          !ISD::isBuildVectorAllOnes(N);
4794 }
4795
4796 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4797 /// match movlp{s|d}. The lower half elements should come from lower half of
4798 /// V1 (and in order), and the upper half elements should come from the upper
4799 /// half of V2 (and in order). And since V1 will become the source of the
4800 /// MOVLP, it must be either a vector load or a scalar load to vector.
4801 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4802                                ArrayRef<int> Mask, MVT VT) {
4803   if (!VT.is128BitVector())
4804     return false;
4805
4806   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4807     return false;
4808   // Is V2 is a vector load, don't do this transformation. We will try to use
4809   // load folding shufps op.
4810   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4811     return false;
4812
4813   unsigned NumElems = VT.getVectorNumElements();
4814
4815   if (NumElems != 2 && NumElems != 4)
4816     return false;
4817   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4818     if (!isUndefOrEqual(Mask[i], i))
4819       return false;
4820   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4821     if (!isUndefOrEqual(Mask[i], i+NumElems))
4822       return false;
4823   return true;
4824 }
4825
4826 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4827 /// all the same.
4828 static bool isSplatVector(SDNode *N) {
4829   if (N->getOpcode() != ISD::BUILD_VECTOR)
4830     return false;
4831
4832   SDValue SplatValue = N->getOperand(0);
4833   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4834     if (N->getOperand(i) != SplatValue)
4835       return false;
4836   return true;
4837 }
4838
4839 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4840 /// to an zero vector.
4841 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4842 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4843   SDValue V1 = N->getOperand(0);
4844   SDValue V2 = N->getOperand(1);
4845   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4846   for (unsigned i = 0; i != NumElems; ++i) {
4847     int Idx = N->getMaskElt(i);
4848     if (Idx >= (int)NumElems) {
4849       unsigned Opc = V2.getOpcode();
4850       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4851         continue;
4852       if (Opc != ISD::BUILD_VECTOR ||
4853           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4854         return false;
4855     } else if (Idx >= 0) {
4856       unsigned Opc = V1.getOpcode();
4857       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4858         continue;
4859       if (Opc != ISD::BUILD_VECTOR ||
4860           !X86::isZeroNode(V1.getOperand(Idx)))
4861         return false;
4862     }
4863   }
4864   return true;
4865 }
4866
4867 /// getZeroVector - Returns a vector of specified type with all zero elements.
4868 ///
4869 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4870                              SelectionDAG &DAG, SDLoc dl) {
4871   assert(VT.isVector() && "Expected a vector type");
4872
4873   // Always build SSE zero vectors as <4 x i32> bitcasted
4874   // to their dest type. This ensures they get CSE'd.
4875   SDValue Vec;
4876   if (VT.is128BitVector()) {  // SSE
4877     if (Subtarget->hasSSE2()) {  // SSE2
4878       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4879       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4880     } else { // SSE1
4881       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4882       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4883     }
4884   } else if (VT.is256BitVector()) { // AVX
4885     if (Subtarget->hasInt256()) { // AVX2
4886       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4887       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4888       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4889     } else {
4890       // 256-bit logic and arithmetic instructions in AVX are all
4891       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4892       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4893       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4894       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4895     }
4896   } else if (VT.is512BitVector()) { // AVX-512
4897       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4898       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4899                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4900       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4901   } else if (VT.getScalarType() == MVT::i1) {
4902     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4903     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4904     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4905     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4906   } else
4907     llvm_unreachable("Unexpected vector type");
4908
4909   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4910 }
4911
4912 /// getOnesVector - Returns a vector of specified type with all bits set.
4913 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4914 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4915 /// Then bitcast to their original type, ensuring they get CSE'd.
4916 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4917                              SDLoc dl) {
4918   assert(VT.isVector() && "Expected a vector type");
4919
4920   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4921   SDValue Vec;
4922   if (VT.is256BitVector()) {
4923     if (HasInt256) { // AVX2
4924       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4925       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4926     } else { // AVX
4927       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4928       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4929     }
4930   } else if (VT.is128BitVector()) {
4931     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4932   } else
4933     llvm_unreachable("Unexpected vector type");
4934
4935   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4936 }
4937
4938 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4939 /// that point to V2 points to its first element.
4940 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4941   for (unsigned i = 0; i != NumElems; ++i) {
4942     if (Mask[i] > (int)NumElems) {
4943       Mask[i] = NumElems;
4944     }
4945   }
4946 }
4947
4948 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4949 /// operation of specified width.
4950 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4951                        SDValue V2) {
4952   unsigned NumElems = VT.getVectorNumElements();
4953   SmallVector<int, 8> Mask;
4954   Mask.push_back(NumElems);
4955   for (unsigned i = 1; i != NumElems; ++i)
4956     Mask.push_back(i);
4957   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4958 }
4959
4960 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4961 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4962                           SDValue V2) {
4963   unsigned NumElems = VT.getVectorNumElements();
4964   SmallVector<int, 8> Mask;
4965   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4966     Mask.push_back(i);
4967     Mask.push_back(i + NumElems);
4968   }
4969   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4970 }
4971
4972 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4973 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4974                           SDValue V2) {
4975   unsigned NumElems = VT.getVectorNumElements();
4976   SmallVector<int, 8> Mask;
4977   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4978     Mask.push_back(i + Half);
4979     Mask.push_back(i + NumElems + Half);
4980   }
4981   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4982 }
4983
4984 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4985 // a generic shuffle instruction because the target has no such instructions.
4986 // Generate shuffles which repeat i16 and i8 several times until they can be
4987 // represented by v4f32 and then be manipulated by target suported shuffles.
4988 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4989   MVT VT = V.getSimpleValueType();
4990   int NumElems = VT.getVectorNumElements();
4991   SDLoc dl(V);
4992
4993   while (NumElems > 4) {
4994     if (EltNo < NumElems/2) {
4995       V = getUnpackl(DAG, dl, VT, V, V);
4996     } else {
4997       V = getUnpackh(DAG, dl, VT, V, V);
4998       EltNo -= NumElems/2;
4999     }
5000     NumElems >>= 1;
5001   }
5002   return V;
5003 }
5004
5005 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5006 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5007   MVT VT = V.getSimpleValueType();
5008   SDLoc dl(V);
5009
5010   if (VT.is128BitVector()) {
5011     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5012     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5013     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5014                              &SplatMask[0]);
5015   } else if (VT.is256BitVector()) {
5016     // To use VPERMILPS to splat scalars, the second half of indicies must
5017     // refer to the higher part, which is a duplication of the lower one,
5018     // because VPERMILPS can only handle in-lane permutations.
5019     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5020                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5021
5022     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5023     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5024                              &SplatMask[0]);
5025   } else
5026     llvm_unreachable("Vector size not supported");
5027
5028   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5029 }
5030
5031 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5032 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5033   MVT SrcVT = SV->getSimpleValueType(0);
5034   SDValue V1 = SV->getOperand(0);
5035   SDLoc dl(SV);
5036
5037   int EltNo = SV->getSplatIndex();
5038   int NumElems = SrcVT.getVectorNumElements();
5039   bool Is256BitVec = SrcVT.is256BitVector();
5040
5041   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5042          "Unknown how to promote splat for type");
5043
5044   // Extract the 128-bit part containing the splat element and update
5045   // the splat element index when it refers to the higher register.
5046   if (Is256BitVec) {
5047     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5048     if (EltNo >= NumElems/2)
5049       EltNo -= NumElems/2;
5050   }
5051
5052   // All i16 and i8 vector types can't be used directly by a generic shuffle
5053   // instruction because the target has no such instruction. Generate shuffles
5054   // which repeat i16 and i8 several times until they fit in i32, and then can
5055   // be manipulated by target suported shuffles.
5056   MVT EltVT = SrcVT.getVectorElementType();
5057   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5058     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5059
5060   // Recreate the 256-bit vector and place the same 128-bit vector
5061   // into the low and high part. This is necessary because we want
5062   // to use VPERM* to shuffle the vectors
5063   if (Is256BitVec) {
5064     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5065   }
5066
5067   return getLegalSplat(DAG, V1, EltNo);
5068 }
5069
5070 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5071 /// vector of zero or undef vector.  This produces a shuffle where the low
5072 /// element of V2 is swizzled into the zero/undef vector, landing at element
5073 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5074 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5075                                            bool IsZero,
5076                                            const X86Subtarget *Subtarget,
5077                                            SelectionDAG &DAG) {
5078   MVT VT = V2.getSimpleValueType();
5079   SDValue V1 = IsZero
5080     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5081   unsigned NumElems = VT.getVectorNumElements();
5082   SmallVector<int, 16> MaskVec;
5083   for (unsigned i = 0; i != NumElems; ++i)
5084     // If this is the insertion idx, put the low elt of V2 here.
5085     MaskVec.push_back(i == Idx ? NumElems : i);
5086   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5087 }
5088
5089 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5090 /// target specific opcode. Returns true if the Mask could be calculated.
5091 /// Sets IsUnary to true if only uses one source.
5092 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5093                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5094   unsigned NumElems = VT.getVectorNumElements();
5095   SDValue ImmN;
5096
5097   IsUnary = false;
5098   switch(N->getOpcode()) {
5099   case X86ISD::SHUFP:
5100     ImmN = N->getOperand(N->getNumOperands()-1);
5101     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5102     break;
5103   case X86ISD::UNPCKH:
5104     DecodeUNPCKHMask(VT, Mask);
5105     break;
5106   case X86ISD::UNPCKL:
5107     DecodeUNPCKLMask(VT, Mask);
5108     break;
5109   case X86ISD::MOVHLPS:
5110     DecodeMOVHLPSMask(NumElems, Mask);
5111     break;
5112   case X86ISD::MOVLHPS:
5113     DecodeMOVLHPSMask(NumElems, Mask);
5114     break;
5115   case X86ISD::PALIGNR:
5116     ImmN = N->getOperand(N->getNumOperands()-1);
5117     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5118     break;
5119   case X86ISD::PSHUFD:
5120   case X86ISD::VPERMILP:
5121     ImmN = N->getOperand(N->getNumOperands()-1);
5122     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5123     IsUnary = true;
5124     break;
5125   case X86ISD::PSHUFHW:
5126     ImmN = N->getOperand(N->getNumOperands()-1);
5127     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5128     IsUnary = true;
5129     break;
5130   case X86ISD::PSHUFLW:
5131     ImmN = N->getOperand(N->getNumOperands()-1);
5132     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5133     IsUnary = true;
5134     break;
5135   case X86ISD::VPERMI:
5136     ImmN = N->getOperand(N->getNumOperands()-1);
5137     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5138     IsUnary = true;
5139     break;
5140   case X86ISD::MOVSS:
5141   case X86ISD::MOVSD: {
5142     // The index 0 always comes from the first element of the second source,
5143     // this is why MOVSS and MOVSD are used in the first place. The other
5144     // elements come from the other positions of the first source vector
5145     Mask.push_back(NumElems);
5146     for (unsigned i = 1; i != NumElems; ++i) {
5147       Mask.push_back(i);
5148     }
5149     break;
5150   }
5151   case X86ISD::VPERM2X128:
5152     ImmN = N->getOperand(N->getNumOperands()-1);
5153     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154     if (Mask.empty()) return false;
5155     break;
5156   case X86ISD::MOVDDUP:
5157   case X86ISD::MOVLHPD:
5158   case X86ISD::MOVLPD:
5159   case X86ISD::MOVLPS:
5160   case X86ISD::MOVSHDUP:
5161   case X86ISD::MOVSLDUP:
5162     // Not yet implemented
5163     return false;
5164   default: llvm_unreachable("unknown target shuffle node");
5165   }
5166
5167   return true;
5168 }
5169
5170 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5171 /// element of the result of the vector shuffle.
5172 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5173                                    unsigned Depth) {
5174   if (Depth == 6)
5175     return SDValue();  // Limit search depth.
5176
5177   SDValue V = SDValue(N, 0);
5178   EVT VT = V.getValueType();
5179   unsigned Opcode = V.getOpcode();
5180
5181   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5182   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5183     int Elt = SV->getMaskElt(Index);
5184
5185     if (Elt < 0)
5186       return DAG.getUNDEF(VT.getVectorElementType());
5187
5188     unsigned NumElems = VT.getVectorNumElements();
5189     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5190                                          : SV->getOperand(1);
5191     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5192   }
5193
5194   // Recurse into target specific vector shuffles to find scalars.
5195   if (isTargetShuffle(Opcode)) {
5196     MVT ShufVT = V.getSimpleValueType();
5197     unsigned NumElems = ShufVT.getVectorNumElements();
5198     SmallVector<int, 16> ShuffleMask;
5199     bool IsUnary;
5200
5201     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5202       return SDValue();
5203
5204     int Elt = ShuffleMask[Index];
5205     if (Elt < 0)
5206       return DAG.getUNDEF(ShufVT.getVectorElementType());
5207
5208     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5209                                          : N->getOperand(1);
5210     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5211                                Depth+1);
5212   }
5213
5214   // Actual nodes that may contain scalar elements
5215   if (Opcode == ISD::BITCAST) {
5216     V = V.getOperand(0);
5217     EVT SrcVT = V.getValueType();
5218     unsigned NumElems = VT.getVectorNumElements();
5219
5220     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5221       return SDValue();
5222   }
5223
5224   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5225     return (Index == 0) ? V.getOperand(0)
5226                         : DAG.getUNDEF(VT.getVectorElementType());
5227
5228   if (V.getOpcode() == ISD::BUILD_VECTOR)
5229     return V.getOperand(Index);
5230
5231   return SDValue();
5232 }
5233
5234 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5235 /// shuffle operation which come from a consecutively from a zero. The
5236 /// search can start in two different directions, from left or right.
5237 /// We count undefs as zeros until PreferredNum is reached.
5238 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5239                                          unsigned NumElems, bool ZerosFromLeft,
5240                                          SelectionDAG &DAG,
5241                                          unsigned PreferredNum = -1U) {
5242   unsigned NumZeros = 0;
5243   for (unsigned i = 0; i != NumElems; ++i) {
5244     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5245     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5246     if (!Elt.getNode())
5247       break;
5248
5249     if (X86::isZeroNode(Elt))
5250       ++NumZeros;
5251     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5252       NumZeros = std::min(NumZeros + 1, PreferredNum);
5253     else
5254       break;
5255   }
5256
5257   return NumZeros;
5258 }
5259
5260 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5261 /// correspond consecutively to elements from one of the vector operands,
5262 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5263 static
5264 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5265                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5266                               unsigned NumElems, unsigned &OpNum) {
5267   bool SeenV1 = false;
5268   bool SeenV2 = false;
5269
5270   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5271     int Idx = SVOp->getMaskElt(i);
5272     // Ignore undef indicies
5273     if (Idx < 0)
5274       continue;
5275
5276     if (Idx < (int)NumElems)
5277       SeenV1 = true;
5278     else
5279       SeenV2 = true;
5280
5281     // Only accept consecutive elements from the same vector
5282     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5283       return false;
5284   }
5285
5286   OpNum = SeenV1 ? 0 : 1;
5287   return true;
5288 }
5289
5290 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5291 /// logical left shift of a vector.
5292 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5293                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5294   unsigned NumElems =
5295     SVOp->getSimpleValueType(0).getVectorNumElements();
5296   unsigned NumZeros = getNumOfConsecutiveZeros(
5297       SVOp, NumElems, false /* check zeros from right */, DAG,
5298       SVOp->getMaskElt(0));
5299   unsigned OpSrc;
5300
5301   if (!NumZeros)
5302     return false;
5303
5304   // Considering the elements in the mask that are not consecutive zeros,
5305   // check if they consecutively come from only one of the source vectors.
5306   //
5307   //               V1 = {X, A, B, C}     0
5308   //                         \  \  \    /
5309   //   vector_shuffle V1, V2 <1, 2, 3, X>
5310   //
5311   if (!isShuffleMaskConsecutive(SVOp,
5312             0,                   // Mask Start Index
5313             NumElems-NumZeros,   // Mask End Index(exclusive)
5314             NumZeros,            // Where to start looking in the src vector
5315             NumElems,            // Number of elements in vector
5316             OpSrc))              // Which source operand ?
5317     return false;
5318
5319   isLeft = false;
5320   ShAmt = NumZeros;
5321   ShVal = SVOp->getOperand(OpSrc);
5322   return true;
5323 }
5324
5325 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5326 /// logical left shift of a vector.
5327 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5328                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5329   unsigned NumElems =
5330     SVOp->getSimpleValueType(0).getVectorNumElements();
5331   unsigned NumZeros = getNumOfConsecutiveZeros(
5332       SVOp, NumElems, true /* check zeros from left */, DAG,
5333       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5334   unsigned OpSrc;
5335
5336   if (!NumZeros)
5337     return false;
5338
5339   // Considering the elements in the mask that are not consecutive zeros,
5340   // check if they consecutively come from only one of the source vectors.
5341   //
5342   //                           0    { A, B, X, X } = V2
5343   //                          / \    /  /
5344   //   vector_shuffle V1, V2 <X, X, 4, 5>
5345   //
5346   if (!isShuffleMaskConsecutive(SVOp,
5347             NumZeros,     // Mask Start Index
5348             NumElems,     // Mask End Index(exclusive)
5349             0,            // Where to start looking in the src vector
5350             NumElems,     // Number of elements in vector
5351             OpSrc))       // Which source operand ?
5352     return false;
5353
5354   isLeft = true;
5355   ShAmt = NumZeros;
5356   ShVal = SVOp->getOperand(OpSrc);
5357   return true;
5358 }
5359
5360 /// isVectorShift - Returns true if the shuffle can be implemented as a
5361 /// logical left or right shift of a vector.
5362 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5363                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5364   // Although the logic below support any bitwidth size, there are no
5365   // shift instructions which handle more than 128-bit vectors.
5366   if (!SVOp->getSimpleValueType(0).is128BitVector())
5367     return false;
5368
5369   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5370       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5371     return true;
5372
5373   return false;
5374 }
5375
5376 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5377 ///
5378 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5379                                        unsigned NumNonZero, unsigned NumZero,
5380                                        SelectionDAG &DAG,
5381                                        const X86Subtarget* Subtarget,
5382                                        const TargetLowering &TLI) {
5383   if (NumNonZero > 8)
5384     return SDValue();
5385
5386   SDLoc dl(Op);
5387   SDValue V;
5388   bool First = true;
5389   for (unsigned i = 0; i < 16; ++i) {
5390     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5391     if (ThisIsNonZero && First) {
5392       if (NumZero)
5393         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5394       else
5395         V = DAG.getUNDEF(MVT::v8i16);
5396       First = false;
5397     }
5398
5399     if ((i & 1) != 0) {
5400       SDValue ThisElt, LastElt;
5401       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5402       if (LastIsNonZero) {
5403         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5404                               MVT::i16, Op.getOperand(i-1));
5405       }
5406       if (ThisIsNonZero) {
5407         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5408         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5409                               ThisElt, DAG.getConstant(8, MVT::i8));
5410         if (LastIsNonZero)
5411           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5412       } else
5413         ThisElt = LastElt;
5414
5415       if (ThisElt.getNode())
5416         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5417                         DAG.getIntPtrConstant(i/2));
5418     }
5419   }
5420
5421   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5422 }
5423
5424 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5425 ///
5426 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5427                                      unsigned NumNonZero, unsigned NumZero,
5428                                      SelectionDAG &DAG,
5429                                      const X86Subtarget* Subtarget,
5430                                      const TargetLowering &TLI) {
5431   if (NumNonZero > 4)
5432     return SDValue();
5433
5434   SDLoc dl(Op);
5435   SDValue V;
5436   bool First = true;
5437   for (unsigned i = 0; i < 8; ++i) {
5438     bool isNonZero = (NonZeros & (1 << i)) != 0;
5439     if (isNonZero) {
5440       if (First) {
5441         if (NumZero)
5442           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5443         else
5444           V = DAG.getUNDEF(MVT::v8i16);
5445         First = false;
5446       }
5447       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5448                       MVT::v8i16, V, Op.getOperand(i),
5449                       DAG.getIntPtrConstant(i));
5450     }
5451   }
5452
5453   return V;
5454 }
5455
5456 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5457 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5458                                      unsigned NonZeros, unsigned NumNonZero,
5459                                      unsigned NumZero, SelectionDAG &DAG,
5460                                      const X86Subtarget *Subtarget,
5461                                      const TargetLowering &TLI) {
5462   // We know there's at least one non-zero element
5463   unsigned FirstNonZeroIdx = 0;
5464   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5465   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5466          X86::isZeroNode(FirstNonZero)) {
5467     ++FirstNonZeroIdx;
5468     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5469   }
5470
5471   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5472       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5473     return SDValue();
5474
5475   SDValue V = FirstNonZero.getOperand(0);
5476   MVT VVT = V.getSimpleValueType();
5477   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5478     return SDValue();
5479
5480   unsigned FirstNonZeroDst =
5481       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5482   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5483   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5484   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5485
5486   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5487     SDValue Elem = Op.getOperand(Idx);
5488     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5489       continue;
5490
5491     // TODO: What else can be here? Deal with it.
5492     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5493       return SDValue();
5494
5495     // TODO: Some optimizations are still possible here
5496     // ex: Getting one element from a vector, and the rest from another.
5497     if (Elem.getOperand(0) != V)
5498       return SDValue();
5499
5500     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5501     if (Dst == Idx)
5502       ++CorrectIdx;
5503     else if (IncorrectIdx == -1U) {
5504       IncorrectIdx = Idx;
5505       IncorrectDst = Dst;
5506     } else
5507       // There was already one element with an incorrect index.
5508       // We can't optimize this case to an insertps.
5509       return SDValue();
5510   }
5511
5512   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5513     SDLoc dl(Op);
5514     EVT VT = Op.getSimpleValueType();
5515     unsigned ElementMoveMask = 0;
5516     if (IncorrectIdx == -1U)
5517       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5518     else
5519       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5520
5521     SDValue InsertpsMask =
5522         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5523     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5524   }
5525
5526   return SDValue();
5527 }
5528
5529 /// getVShift - Return a vector logical shift node.
5530 ///
5531 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5532                          unsigned NumBits, SelectionDAG &DAG,
5533                          const TargetLowering &TLI, SDLoc dl) {
5534   assert(VT.is128BitVector() && "Unknown type for VShift");
5535   EVT ShVT = MVT::v2i64;
5536   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5537   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5538   return DAG.getNode(ISD::BITCAST, dl, VT,
5539                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5540                              DAG.getConstant(NumBits,
5541                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5542 }
5543
5544 static SDValue
5545 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5546
5547   // Check if the scalar load can be widened into a vector load. And if
5548   // the address is "base + cst" see if the cst can be "absorbed" into
5549   // the shuffle mask.
5550   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5551     SDValue Ptr = LD->getBasePtr();
5552     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5553       return SDValue();
5554     EVT PVT = LD->getValueType(0);
5555     if (PVT != MVT::i32 && PVT != MVT::f32)
5556       return SDValue();
5557
5558     int FI = -1;
5559     int64_t Offset = 0;
5560     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5561       FI = FINode->getIndex();
5562       Offset = 0;
5563     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5564                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5565       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5566       Offset = Ptr.getConstantOperandVal(1);
5567       Ptr = Ptr.getOperand(0);
5568     } else {
5569       return SDValue();
5570     }
5571
5572     // FIXME: 256-bit vector instructions don't require a strict alignment,
5573     // improve this code to support it better.
5574     unsigned RequiredAlign = VT.getSizeInBits()/8;
5575     SDValue Chain = LD->getChain();
5576     // Make sure the stack object alignment is at least 16 or 32.
5577     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5578     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5579       if (MFI->isFixedObjectIndex(FI)) {
5580         // Can't change the alignment. FIXME: It's possible to compute
5581         // the exact stack offset and reference FI + adjust offset instead.
5582         // If someone *really* cares about this. That's the way to implement it.
5583         return SDValue();
5584       } else {
5585         MFI->setObjectAlignment(FI, RequiredAlign);
5586       }
5587     }
5588
5589     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5590     // Ptr + (Offset & ~15).
5591     if (Offset < 0)
5592       return SDValue();
5593     if ((Offset % RequiredAlign) & 3)
5594       return SDValue();
5595     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5596     if (StartOffset)
5597       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5598                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5599
5600     int EltNo = (Offset - StartOffset) >> 2;
5601     unsigned NumElems = VT.getVectorNumElements();
5602
5603     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5604     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5605                              LD->getPointerInfo().getWithOffset(StartOffset),
5606                              false, false, false, 0);
5607
5608     SmallVector<int, 8> Mask;
5609     for (unsigned i = 0; i != NumElems; ++i)
5610       Mask.push_back(EltNo);
5611
5612     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5613   }
5614
5615   return SDValue();
5616 }
5617
5618 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5619 /// vector of type 'VT', see if the elements can be replaced by a single large
5620 /// load which has the same value as a build_vector whose operands are 'elts'.
5621 ///
5622 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5623 ///
5624 /// FIXME: we'd also like to handle the case where the last elements are zero
5625 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5626 /// There's even a handy isZeroNode for that purpose.
5627 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5628                                         SDLoc &DL, SelectionDAG &DAG,
5629                                         bool isAfterLegalize) {
5630   EVT EltVT = VT.getVectorElementType();
5631   unsigned NumElems = Elts.size();
5632
5633   LoadSDNode *LDBase = nullptr;
5634   unsigned LastLoadedElt = -1U;
5635
5636   // For each element in the initializer, see if we've found a load or an undef.
5637   // If we don't find an initial load element, or later load elements are
5638   // non-consecutive, bail out.
5639   for (unsigned i = 0; i < NumElems; ++i) {
5640     SDValue Elt = Elts[i];
5641
5642     if (!Elt.getNode() ||
5643         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5644       return SDValue();
5645     if (!LDBase) {
5646       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5647         return SDValue();
5648       LDBase = cast<LoadSDNode>(Elt.getNode());
5649       LastLoadedElt = i;
5650       continue;
5651     }
5652     if (Elt.getOpcode() == ISD::UNDEF)
5653       continue;
5654
5655     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5656     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5657       return SDValue();
5658     LastLoadedElt = i;
5659   }
5660
5661   // If we have found an entire vector of loads and undefs, then return a large
5662   // load of the entire vector width starting at the base pointer.  If we found
5663   // consecutive loads for the low half, generate a vzext_load node.
5664   if (LastLoadedElt == NumElems - 1) {
5665
5666     if (isAfterLegalize &&
5667         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5668       return SDValue();
5669
5670     SDValue NewLd = SDValue();
5671
5672     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5673       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5674                           LDBase->getPointerInfo(),
5675                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5676                           LDBase->isInvariant(), 0);
5677     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5678                         LDBase->getPointerInfo(),
5679                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5680                         LDBase->isInvariant(), LDBase->getAlignment());
5681
5682     if (LDBase->hasAnyUseOfValue(1)) {
5683       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5684                                      SDValue(LDBase, 1),
5685                                      SDValue(NewLd.getNode(), 1));
5686       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5687       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5688                              SDValue(NewLd.getNode(), 1));
5689     }
5690
5691     return NewLd;
5692   }
5693   if (NumElems == 4 && LastLoadedElt == 1 &&
5694       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5695     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5696     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5697     SDValue ResNode =
5698         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5699                                 LDBase->getPointerInfo(),
5700                                 LDBase->getAlignment(),
5701                                 false/*isVolatile*/, true/*ReadMem*/,
5702                                 false/*WriteMem*/);
5703
5704     // Make sure the newly-created LOAD is in the same position as LDBase in
5705     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5706     // update uses of LDBase's output chain to use the TokenFactor.
5707     if (LDBase->hasAnyUseOfValue(1)) {
5708       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5709                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5710       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5711       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5712                              SDValue(ResNode.getNode(), 1));
5713     }
5714
5715     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5716   }
5717   return SDValue();
5718 }
5719
5720 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5721 /// to generate a splat value for the following cases:
5722 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5723 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5724 /// a scalar load, or a constant.
5725 /// The VBROADCAST node is returned when a pattern is found,
5726 /// or SDValue() otherwise.
5727 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5728                                     SelectionDAG &DAG) {
5729   if (!Subtarget->hasFp256())
5730     return SDValue();
5731
5732   MVT VT = Op.getSimpleValueType();
5733   SDLoc dl(Op);
5734
5735   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5736          "Unsupported vector type for broadcast.");
5737
5738   SDValue Ld;
5739   bool ConstSplatVal;
5740
5741   switch (Op.getOpcode()) {
5742     default:
5743       // Unknown pattern found.
5744       return SDValue();
5745
5746     case ISD::BUILD_VECTOR: {
5747       // The BUILD_VECTOR node must be a splat.
5748       if (!isSplatVector(Op.getNode()))
5749         return SDValue();
5750
5751       Ld = Op.getOperand(0);
5752       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5753                      Ld.getOpcode() == ISD::ConstantFP);
5754
5755       // The suspected load node has several users. Make sure that all
5756       // of its users are from the BUILD_VECTOR node.
5757       // Constants may have multiple users.
5758       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5759         return SDValue();
5760       break;
5761     }
5762
5763     case ISD::VECTOR_SHUFFLE: {
5764       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5765
5766       // Shuffles must have a splat mask where the first element is
5767       // broadcasted.
5768       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5769         return SDValue();
5770
5771       SDValue Sc = Op.getOperand(0);
5772       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5773           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5774
5775         if (!Subtarget->hasInt256())
5776           return SDValue();
5777
5778         // Use the register form of the broadcast instruction available on AVX2.
5779         if (VT.getSizeInBits() >= 256)
5780           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5781         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5782       }
5783
5784       Ld = Sc.getOperand(0);
5785       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5786                        Ld.getOpcode() == ISD::ConstantFP);
5787
5788       // The scalar_to_vector node and the suspected
5789       // load node must have exactly one user.
5790       // Constants may have multiple users.
5791
5792       // AVX-512 has register version of the broadcast
5793       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5794         Ld.getValueType().getSizeInBits() >= 32;
5795       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5796           !hasRegVer))
5797         return SDValue();
5798       break;
5799     }
5800   }
5801
5802   bool IsGE256 = (VT.getSizeInBits() >= 256);
5803
5804   // Handle the broadcasting a single constant scalar from the constant pool
5805   // into a vector. On Sandybridge it is still better to load a constant vector
5806   // from the constant pool and not to broadcast it from a scalar.
5807   if (ConstSplatVal && Subtarget->hasInt256()) {
5808     EVT CVT = Ld.getValueType();
5809     assert(!CVT.isVector() && "Must not broadcast a vector type");
5810     unsigned ScalarSize = CVT.getSizeInBits();
5811
5812     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5813       const Constant *C = nullptr;
5814       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5815         C = CI->getConstantIntValue();
5816       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5817         C = CF->getConstantFPValue();
5818
5819       assert(C && "Invalid constant type");
5820
5821       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5822       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5823       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5824       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5825                        MachinePointerInfo::getConstantPool(),
5826                        false, false, false, Alignment);
5827
5828       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5829     }
5830   }
5831
5832   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5833   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5834
5835   // Handle AVX2 in-register broadcasts.
5836   if (!IsLoad && Subtarget->hasInt256() &&
5837       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5838     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5839
5840   // The scalar source must be a normal load.
5841   if (!IsLoad)
5842     return SDValue();
5843
5844   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5845     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5846
5847   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5848   // double since there is no vbroadcastsd xmm
5849   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5850     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5851       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5852   }
5853
5854   // Unsupported broadcast.
5855   return SDValue();
5856 }
5857
5858 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5859 /// underlying vector and index.
5860 ///
5861 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5862 /// index.
5863 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5864                                          SDValue ExtIdx) {
5865   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5866   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5867     return Idx;
5868
5869   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5870   // lowered this:
5871   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5872   // to:
5873   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5874   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5875   //                           undef)
5876   //                       Constant<0>)
5877   // In this case the vector is the extract_subvector expression and the index
5878   // is 2, as specified by the shuffle.
5879   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5880   SDValue ShuffleVec = SVOp->getOperand(0);
5881   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5882   assert(ShuffleVecVT.getVectorElementType() ==
5883          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5884
5885   int ShuffleIdx = SVOp->getMaskElt(Idx);
5886   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5887     ExtractedFromVec = ShuffleVec;
5888     return ShuffleIdx;
5889   }
5890   return Idx;
5891 }
5892
5893 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5894   MVT VT = Op.getSimpleValueType();
5895
5896   // Skip if insert_vec_elt is not supported.
5897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5898   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5899     return SDValue();
5900
5901   SDLoc DL(Op);
5902   unsigned NumElems = Op.getNumOperands();
5903
5904   SDValue VecIn1;
5905   SDValue VecIn2;
5906   SmallVector<unsigned, 4> InsertIndices;
5907   SmallVector<int, 8> Mask(NumElems, -1);
5908
5909   for (unsigned i = 0; i != NumElems; ++i) {
5910     unsigned Opc = Op.getOperand(i).getOpcode();
5911
5912     if (Opc == ISD::UNDEF)
5913       continue;
5914
5915     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5916       // Quit if more than 1 elements need inserting.
5917       if (InsertIndices.size() > 1)
5918         return SDValue();
5919
5920       InsertIndices.push_back(i);
5921       continue;
5922     }
5923
5924     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5925     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5926     // Quit if non-constant index.
5927     if (!isa<ConstantSDNode>(ExtIdx))
5928       return SDValue();
5929     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5930
5931     // Quit if extracted from vector of different type.
5932     if (ExtractedFromVec.getValueType() != VT)
5933       return SDValue();
5934
5935     if (!VecIn1.getNode())
5936       VecIn1 = ExtractedFromVec;
5937     else if (VecIn1 != ExtractedFromVec) {
5938       if (!VecIn2.getNode())
5939         VecIn2 = ExtractedFromVec;
5940       else if (VecIn2 != ExtractedFromVec)
5941         // Quit if more than 2 vectors to shuffle
5942         return SDValue();
5943     }
5944
5945     if (ExtractedFromVec == VecIn1)
5946       Mask[i] = Idx;
5947     else if (ExtractedFromVec == VecIn2)
5948       Mask[i] = Idx + NumElems;
5949   }
5950
5951   if (!VecIn1.getNode())
5952     return SDValue();
5953
5954   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5955   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5956   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5957     unsigned Idx = InsertIndices[i];
5958     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5959                      DAG.getIntPtrConstant(Idx));
5960   }
5961
5962   return NV;
5963 }
5964
5965 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5966 SDValue
5967 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5968
5969   MVT VT = Op.getSimpleValueType();
5970   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5971          "Unexpected type in LowerBUILD_VECTORvXi1!");
5972
5973   SDLoc dl(Op);
5974   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5975     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5976     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5977     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5978   }
5979
5980   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5981     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5982     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5983     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5984   }
5985
5986   bool AllContants = true;
5987   uint64_t Immediate = 0;
5988   int NonConstIdx = -1;
5989   bool IsSplat = true;
5990   unsigned NumNonConsts = 0;
5991   unsigned NumConsts = 0;
5992   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5993     SDValue In = Op.getOperand(idx);
5994     if (In.getOpcode() == ISD::UNDEF)
5995       continue;
5996     if (!isa<ConstantSDNode>(In)) {
5997       AllContants = false;
5998       NonConstIdx = idx;
5999       NumNonConsts++;
6000     }
6001     else {
6002       NumConsts++;
6003       if (cast<ConstantSDNode>(In)->getZExtValue())
6004       Immediate |= (1ULL << idx);
6005     }
6006     if (In != Op.getOperand(0))
6007       IsSplat = false;
6008   }
6009
6010   if (AllContants) {
6011     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6012       DAG.getConstant(Immediate, MVT::i16));
6013     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6014                        DAG.getIntPtrConstant(0));
6015   }
6016
6017   if (NumNonConsts == 1 && NonConstIdx != 0) {
6018     SDValue DstVec;
6019     if (NumConsts) {
6020       SDValue VecAsImm = DAG.getConstant(Immediate,
6021                                          MVT::getIntegerVT(VT.getSizeInBits()));
6022       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6023     }
6024     else 
6025       DstVec = DAG.getUNDEF(VT);
6026     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6027                        Op.getOperand(NonConstIdx),
6028                        DAG.getIntPtrConstant(NonConstIdx));
6029   }
6030   if (!IsSplat && (NonConstIdx != 0))
6031     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6032   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6033   SDValue Select;
6034   if (IsSplat)
6035     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6036                           DAG.getConstant(-1, SelectVT),
6037                           DAG.getConstant(0, SelectVT));
6038   else
6039     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6040                          DAG.getConstant((Immediate | 1), SelectVT),
6041                          DAG.getConstant(Immediate, SelectVT));
6042   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6043 }
6044
6045 SDValue
6046 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6047   SDLoc dl(Op);
6048
6049   MVT VT = Op.getSimpleValueType();
6050   MVT ExtVT = VT.getVectorElementType();
6051   unsigned NumElems = Op.getNumOperands();
6052
6053   // Generate vectors for predicate vectors.
6054   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6055     return LowerBUILD_VECTORvXi1(Op, DAG);
6056
6057   // Vectors containing all zeros can be matched by pxor and xorps later
6058   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6059     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6060     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6061     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6062       return Op;
6063
6064     return getZeroVector(VT, Subtarget, DAG, dl);
6065   }
6066
6067   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6068   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6069   // vpcmpeqd on 256-bit vectors.
6070   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6071     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6072       return Op;
6073
6074     if (!VT.is512BitVector())
6075       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6076   }
6077
6078   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6079   if (Broadcast.getNode())
6080     return Broadcast;
6081
6082   unsigned EVTBits = ExtVT.getSizeInBits();
6083
6084   unsigned NumZero  = 0;
6085   unsigned NumNonZero = 0;
6086   unsigned NonZeros = 0;
6087   bool IsAllConstants = true;
6088   SmallSet<SDValue, 8> Values;
6089   for (unsigned i = 0; i < NumElems; ++i) {
6090     SDValue Elt = Op.getOperand(i);
6091     if (Elt.getOpcode() == ISD::UNDEF)
6092       continue;
6093     Values.insert(Elt);
6094     if (Elt.getOpcode() != ISD::Constant &&
6095         Elt.getOpcode() != ISD::ConstantFP)
6096       IsAllConstants = false;
6097     if (X86::isZeroNode(Elt))
6098       NumZero++;
6099     else {
6100       NonZeros |= (1 << i);
6101       NumNonZero++;
6102     }
6103   }
6104
6105   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6106   if (NumNonZero == 0)
6107     return DAG.getUNDEF(VT);
6108
6109   // Special case for single non-zero, non-undef, element.
6110   if (NumNonZero == 1) {
6111     unsigned Idx = countTrailingZeros(NonZeros);
6112     SDValue Item = Op.getOperand(Idx);
6113
6114     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6115     // the value are obviously zero, truncate the value to i32 and do the
6116     // insertion that way.  Only do this if the value is non-constant or if the
6117     // value is a constant being inserted into element 0.  It is cheaper to do
6118     // a constant pool load than it is to do a movd + shuffle.
6119     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6120         (!IsAllConstants || Idx == 0)) {
6121       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6122         // Handle SSE only.
6123         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6124         EVT VecVT = MVT::v4i32;
6125         unsigned VecElts = 4;
6126
6127         // Truncate the value (which may itself be a constant) to i32, and
6128         // convert it to a vector with movd (S2V+shuffle to zero extend).
6129         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6130         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6131         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6132
6133         // Now we have our 32-bit value zero extended in the low element of
6134         // a vector.  If Idx != 0, swizzle it into place.
6135         if (Idx != 0) {
6136           SmallVector<int, 4> Mask;
6137           Mask.push_back(Idx);
6138           for (unsigned i = 1; i != VecElts; ++i)
6139             Mask.push_back(i);
6140           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6141                                       &Mask[0]);
6142         }
6143         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6144       }
6145     }
6146
6147     // If we have a constant or non-constant insertion into the low element of
6148     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6149     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6150     // depending on what the source datatype is.
6151     if (Idx == 0) {
6152       if (NumZero == 0)
6153         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6154
6155       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6156           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6157         if (VT.is256BitVector() || VT.is512BitVector()) {
6158           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6159           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6160                              Item, DAG.getIntPtrConstant(0));
6161         }
6162         assert(VT.is128BitVector() && "Expected an SSE value type!");
6163         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6164         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6165         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6166       }
6167
6168       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6169         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6170         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6171         if (VT.is256BitVector()) {
6172           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6173           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6174         } else {
6175           assert(VT.is128BitVector() && "Expected an SSE value type!");
6176           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6177         }
6178         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6179       }
6180     }
6181
6182     // Is it a vector logical left shift?
6183     if (NumElems == 2 && Idx == 1 &&
6184         X86::isZeroNode(Op.getOperand(0)) &&
6185         !X86::isZeroNode(Op.getOperand(1))) {
6186       unsigned NumBits = VT.getSizeInBits();
6187       return getVShift(true, VT,
6188                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6189                                    VT, Op.getOperand(1)),
6190                        NumBits/2, DAG, *this, dl);
6191     }
6192
6193     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6194       return SDValue();
6195
6196     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6197     // is a non-constant being inserted into an element other than the low one,
6198     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6199     // movd/movss) to move this into the low element, then shuffle it into
6200     // place.
6201     if (EVTBits == 32) {
6202       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6203
6204       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6205       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6206       SmallVector<int, 8> MaskVec;
6207       for (unsigned i = 0; i != NumElems; ++i)
6208         MaskVec.push_back(i == Idx ? 0 : 1);
6209       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6210     }
6211   }
6212
6213   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6214   if (Values.size() == 1) {
6215     if (EVTBits == 32) {
6216       // Instead of a shuffle like this:
6217       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6218       // Check if it's possible to issue this instead.
6219       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6220       unsigned Idx = countTrailingZeros(NonZeros);
6221       SDValue Item = Op.getOperand(Idx);
6222       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6223         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6224     }
6225     return SDValue();
6226   }
6227
6228   // A vector full of immediates; various special cases are already
6229   // handled, so this is best done with a single constant-pool load.
6230   if (IsAllConstants)
6231     return SDValue();
6232
6233   // For AVX-length vectors, build the individual 128-bit pieces and use
6234   // shuffles to put them in place.
6235   if (VT.is256BitVector() || VT.is512BitVector()) {
6236     SmallVector<SDValue, 64> V;
6237     for (unsigned i = 0; i != NumElems; ++i)
6238       V.push_back(Op.getOperand(i));
6239
6240     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6241
6242     // Build both the lower and upper subvector.
6243     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6244                                 makeArrayRef(&V[0], NumElems/2));
6245     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6246                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6247
6248     // Recreate the wider vector with the lower and upper part.
6249     if (VT.is256BitVector())
6250       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6251     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6252   }
6253
6254   // Let legalizer expand 2-wide build_vectors.
6255   if (EVTBits == 64) {
6256     if (NumNonZero == 1) {
6257       // One half is zero or undef.
6258       unsigned Idx = countTrailingZeros(NonZeros);
6259       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6260                                  Op.getOperand(Idx));
6261       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6262     }
6263     return SDValue();
6264   }
6265
6266   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6267   if (EVTBits == 8 && NumElems == 16) {
6268     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6269                                         Subtarget, *this);
6270     if (V.getNode()) return V;
6271   }
6272
6273   if (EVTBits == 16 && NumElems == 8) {
6274     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6275                                       Subtarget, *this);
6276     if (V.getNode()) return V;
6277   }
6278
6279   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6280   if (EVTBits == 32 && NumElems == 4) {
6281     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6282                                       NumZero, DAG, Subtarget, *this);
6283     if (V.getNode())
6284       return V;
6285   }
6286
6287   // If element VT is == 32 bits, turn it into a number of shuffles.
6288   SmallVector<SDValue, 8> V(NumElems);
6289   if (NumElems == 4 && NumZero > 0) {
6290     for (unsigned i = 0; i < 4; ++i) {
6291       bool isZero = !(NonZeros & (1 << i));
6292       if (isZero)
6293         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6294       else
6295         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6296     }
6297
6298     for (unsigned i = 0; i < 2; ++i) {
6299       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6300         default: break;
6301         case 0:
6302           V[i] = V[i*2];  // Must be a zero vector.
6303           break;
6304         case 1:
6305           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6306           break;
6307         case 2:
6308           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6309           break;
6310         case 3:
6311           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6312           break;
6313       }
6314     }
6315
6316     bool Reverse1 = (NonZeros & 0x3) == 2;
6317     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6318     int MaskVec[] = {
6319       Reverse1 ? 1 : 0,
6320       Reverse1 ? 0 : 1,
6321       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6322       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6323     };
6324     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6325   }
6326
6327   if (Values.size() > 1 && VT.is128BitVector()) {
6328     // Check for a build vector of consecutive loads.
6329     for (unsigned i = 0; i < NumElems; ++i)
6330       V[i] = Op.getOperand(i);
6331
6332     // Check for elements which are consecutive loads.
6333     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6334     if (LD.getNode())
6335       return LD;
6336
6337     // Check for a build vector from mostly shuffle plus few inserting.
6338     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6339     if (Sh.getNode())
6340       return Sh;
6341
6342     // For SSE 4.1, use insertps to put the high elements into the low element.
6343     if (getSubtarget()->hasSSE41()) {
6344       SDValue Result;
6345       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6346         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6347       else
6348         Result = DAG.getUNDEF(VT);
6349
6350       for (unsigned i = 1; i < NumElems; ++i) {
6351         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6352         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6353                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6354       }
6355       return Result;
6356     }
6357
6358     // Otherwise, expand into a number of unpckl*, start by extending each of
6359     // our (non-undef) elements to the full vector width with the element in the
6360     // bottom slot of the vector (which generates no code for SSE).
6361     for (unsigned i = 0; i < NumElems; ++i) {
6362       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6363         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6364       else
6365         V[i] = DAG.getUNDEF(VT);
6366     }
6367
6368     // Next, we iteratively mix elements, e.g. for v4f32:
6369     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6370     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6371     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6372     unsigned EltStride = NumElems >> 1;
6373     while (EltStride != 0) {
6374       for (unsigned i = 0; i < EltStride; ++i) {
6375         // If V[i+EltStride] is undef and this is the first round of mixing,
6376         // then it is safe to just drop this shuffle: V[i] is already in the
6377         // right place, the one element (since it's the first round) being
6378         // inserted as undef can be dropped.  This isn't safe for successive
6379         // rounds because they will permute elements within both vectors.
6380         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6381             EltStride == NumElems/2)
6382           continue;
6383
6384         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6385       }
6386       EltStride >>= 1;
6387     }
6388     return V[0];
6389   }
6390   return SDValue();
6391 }
6392
6393 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6394 // to create 256-bit vectors from two other 128-bit ones.
6395 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6396   SDLoc dl(Op);
6397   MVT ResVT = Op.getSimpleValueType();
6398
6399   assert((ResVT.is256BitVector() ||
6400           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6401
6402   SDValue V1 = Op.getOperand(0);
6403   SDValue V2 = Op.getOperand(1);
6404   unsigned NumElems = ResVT.getVectorNumElements();
6405   if(ResVT.is256BitVector())
6406     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6407
6408   if (Op.getNumOperands() == 4) {
6409     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6410                                 ResVT.getVectorNumElements()/2);
6411     SDValue V3 = Op.getOperand(2);
6412     SDValue V4 = Op.getOperand(3);
6413     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6414       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6415   }
6416   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6417 }
6418
6419 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6420   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6421   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6422          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6423           Op.getNumOperands() == 4)));
6424
6425   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6426   // from two other 128-bit ones.
6427
6428   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6429   return LowerAVXCONCAT_VECTORS(Op, DAG);
6430 }
6431
6432 // Try to lower a shuffle node into a simple blend instruction.
6433 static SDValue
6434 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6435                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6436   SDValue V1 = SVOp->getOperand(0);
6437   SDValue V2 = SVOp->getOperand(1);
6438   SDLoc dl(SVOp);
6439   MVT VT = SVOp->getSimpleValueType(0);
6440   MVT EltVT = VT.getVectorElementType();
6441   unsigned NumElems = VT.getVectorNumElements();
6442
6443   // There is no blend with immediate in AVX-512.
6444   if (VT.is512BitVector())
6445     return SDValue();
6446
6447   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6448     return SDValue();
6449   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6450     return SDValue();
6451
6452   // Check the mask for BLEND and build the value.
6453   unsigned MaskValue = 0;
6454   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6455   unsigned NumLanes = (NumElems-1)/8 + 1;
6456   unsigned NumElemsInLane = NumElems / NumLanes;
6457
6458   // Blend for v16i16 should be symetric for the both lanes.
6459   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6460
6461     int SndLaneEltIdx = (NumLanes == 2) ?
6462       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6463     int EltIdx = SVOp->getMaskElt(i);
6464
6465     if ((EltIdx < 0 || EltIdx == (int)i) &&
6466         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6467       continue;
6468
6469     if (((unsigned)EltIdx == (i + NumElems)) &&
6470         (SndLaneEltIdx < 0 ||
6471          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6472       MaskValue |= (1<<i);
6473     else
6474       return SDValue();
6475   }
6476
6477   // Convert i32 vectors to floating point if it is not AVX2.
6478   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6479   MVT BlendVT = VT;
6480   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6481     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6482                                NumElems);
6483     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6484     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6485   }
6486
6487   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6488                             DAG.getConstant(MaskValue, MVT::i32));
6489   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6490 }
6491
6492 /// In vector type \p VT, return true if the element at index \p InputIdx
6493 /// falls on a different 128-bit lane than \p OutputIdx.
6494 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6495                                      unsigned OutputIdx) {
6496   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6497   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6498 }
6499
6500 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6501 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6502 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6503 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6504 /// zero.
6505 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6506                          SelectionDAG &DAG) {
6507   MVT VT = V1.getSimpleValueType();
6508   assert(VT.is128BitVector() || VT.is256BitVector());
6509
6510   MVT EltVT = VT.getVectorElementType();
6511   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6512   unsigned NumElts = VT.getVectorNumElements();
6513
6514   SmallVector<SDValue, 32> PshufbMask;
6515   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6516     int InputIdx = MaskVals[OutputIdx];
6517     unsigned InputByteIdx;
6518
6519     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6520       InputByteIdx = 0x80;
6521     else {
6522       // Cross lane is not allowed.
6523       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6524         return SDValue();
6525       InputByteIdx = InputIdx * EltSizeInBytes;
6526       // Index is an byte offset within the 128-bit lane.
6527       InputByteIdx &= 0xf;
6528     }
6529
6530     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6531       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6532       if (InputByteIdx != 0x80)
6533         ++InputByteIdx;
6534     }
6535   }
6536
6537   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6538   if (ShufVT != VT)
6539     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6540   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6541                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6542 }
6543
6544 // v8i16 shuffles - Prefer shuffles in the following order:
6545 // 1. [all]   pshuflw, pshufhw, optional move
6546 // 2. [ssse3] 1 x pshufb
6547 // 3. [ssse3] 2 x pshufb + 1 x por
6548 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6549 static SDValue
6550 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6551                          SelectionDAG &DAG) {
6552   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6553   SDValue V1 = SVOp->getOperand(0);
6554   SDValue V2 = SVOp->getOperand(1);
6555   SDLoc dl(SVOp);
6556   SmallVector<int, 8> MaskVals;
6557
6558   // Determine if more than 1 of the words in each of the low and high quadwords
6559   // of the result come from the same quadword of one of the two inputs.  Undef
6560   // mask values count as coming from any quadword, for better codegen.
6561   //
6562   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6563   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6564   unsigned LoQuad[] = { 0, 0, 0, 0 };
6565   unsigned HiQuad[] = { 0, 0, 0, 0 };
6566   // Indices of quads used.
6567   std::bitset<4> InputQuads;
6568   for (unsigned i = 0; i < 8; ++i) {
6569     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6570     int EltIdx = SVOp->getMaskElt(i);
6571     MaskVals.push_back(EltIdx);
6572     if (EltIdx < 0) {
6573       ++Quad[0];
6574       ++Quad[1];
6575       ++Quad[2];
6576       ++Quad[3];
6577       continue;
6578     }
6579     ++Quad[EltIdx / 4];
6580     InputQuads.set(EltIdx / 4);
6581   }
6582
6583   int BestLoQuad = -1;
6584   unsigned MaxQuad = 1;
6585   for (unsigned i = 0; i < 4; ++i) {
6586     if (LoQuad[i] > MaxQuad) {
6587       BestLoQuad = i;
6588       MaxQuad = LoQuad[i];
6589     }
6590   }
6591
6592   int BestHiQuad = -1;
6593   MaxQuad = 1;
6594   for (unsigned i = 0; i < 4; ++i) {
6595     if (HiQuad[i] > MaxQuad) {
6596       BestHiQuad = i;
6597       MaxQuad = HiQuad[i];
6598     }
6599   }
6600
6601   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6602   // of the two input vectors, shuffle them into one input vector so only a
6603   // single pshufb instruction is necessary. If there are more than 2 input
6604   // quads, disable the next transformation since it does not help SSSE3.
6605   bool V1Used = InputQuads[0] || InputQuads[1];
6606   bool V2Used = InputQuads[2] || InputQuads[3];
6607   if (Subtarget->hasSSSE3()) {
6608     if (InputQuads.count() == 2 && V1Used && V2Used) {
6609       BestLoQuad = InputQuads[0] ? 0 : 1;
6610       BestHiQuad = InputQuads[2] ? 2 : 3;
6611     }
6612     if (InputQuads.count() > 2) {
6613       BestLoQuad = -1;
6614       BestHiQuad = -1;
6615     }
6616   }
6617
6618   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6619   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6620   // words from all 4 input quadwords.
6621   SDValue NewV;
6622   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6623     int MaskV[] = {
6624       BestLoQuad < 0 ? 0 : BestLoQuad,
6625       BestHiQuad < 0 ? 1 : BestHiQuad
6626     };
6627     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6628                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6629                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6630     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6631
6632     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6633     // source words for the shuffle, to aid later transformations.
6634     bool AllWordsInNewV = true;
6635     bool InOrder[2] = { true, true };
6636     for (unsigned i = 0; i != 8; ++i) {
6637       int idx = MaskVals[i];
6638       if (idx != (int)i)
6639         InOrder[i/4] = false;
6640       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6641         continue;
6642       AllWordsInNewV = false;
6643       break;
6644     }
6645
6646     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6647     if (AllWordsInNewV) {
6648       for (int i = 0; i != 8; ++i) {
6649         int idx = MaskVals[i];
6650         if (idx < 0)
6651           continue;
6652         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6653         if ((idx != i) && idx < 4)
6654           pshufhw = false;
6655         if ((idx != i) && idx > 3)
6656           pshuflw = false;
6657       }
6658       V1 = NewV;
6659       V2Used = false;
6660       BestLoQuad = 0;
6661       BestHiQuad = 1;
6662     }
6663
6664     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6665     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6666     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6667       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6668       unsigned TargetMask = 0;
6669       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6670                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6671       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6672       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6673                              getShufflePSHUFLWImmediate(SVOp);
6674       V1 = NewV.getOperand(0);
6675       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6676     }
6677   }
6678
6679   // Promote splats to a larger type which usually leads to more efficient code.
6680   // FIXME: Is this true if pshufb is available?
6681   if (SVOp->isSplat())
6682     return PromoteSplat(SVOp, DAG);
6683
6684   // If we have SSSE3, and all words of the result are from 1 input vector,
6685   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6686   // is present, fall back to case 4.
6687   if (Subtarget->hasSSSE3()) {
6688     SmallVector<SDValue,16> pshufbMask;
6689
6690     // If we have elements from both input vectors, set the high bit of the
6691     // shuffle mask element to zero out elements that come from V2 in the V1
6692     // mask, and elements that come from V1 in the V2 mask, so that the two
6693     // results can be OR'd together.
6694     bool TwoInputs = V1Used && V2Used;
6695     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6696     if (!TwoInputs)
6697       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6698
6699     // Calculate the shuffle mask for the second input, shuffle it, and
6700     // OR it with the first shuffled input.
6701     CommuteVectorShuffleMask(MaskVals, 8);
6702     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6703     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6704     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6705   }
6706
6707   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6708   // and update MaskVals with new element order.
6709   std::bitset<8> InOrder;
6710   if (BestLoQuad >= 0) {
6711     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6712     for (int i = 0; i != 4; ++i) {
6713       int idx = MaskVals[i];
6714       if (idx < 0) {
6715         InOrder.set(i);
6716       } else if ((idx / 4) == BestLoQuad) {
6717         MaskV[i] = idx & 3;
6718         InOrder.set(i);
6719       }
6720     }
6721     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6722                                 &MaskV[0]);
6723
6724     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6725       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6726       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6727                                   NewV.getOperand(0),
6728                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6729     }
6730   }
6731
6732   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6733   // and update MaskVals with the new element order.
6734   if (BestHiQuad >= 0) {
6735     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6736     for (unsigned i = 4; i != 8; ++i) {
6737       int idx = MaskVals[i];
6738       if (idx < 0) {
6739         InOrder.set(i);
6740       } else if ((idx / 4) == BestHiQuad) {
6741         MaskV[i] = (idx & 3) + 4;
6742         InOrder.set(i);
6743       }
6744     }
6745     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6746                                 &MaskV[0]);
6747
6748     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6749       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6750       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6751                                   NewV.getOperand(0),
6752                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6753     }
6754   }
6755
6756   // In case BestHi & BestLo were both -1, which means each quadword has a word
6757   // from each of the four input quadwords, calculate the InOrder bitvector now
6758   // before falling through to the insert/extract cleanup.
6759   if (BestLoQuad == -1 && BestHiQuad == -1) {
6760     NewV = V1;
6761     for (int i = 0; i != 8; ++i)
6762       if (MaskVals[i] < 0 || MaskVals[i] == i)
6763         InOrder.set(i);
6764   }
6765
6766   // The other elements are put in the right place using pextrw and pinsrw.
6767   for (unsigned i = 0; i != 8; ++i) {
6768     if (InOrder[i])
6769       continue;
6770     int EltIdx = MaskVals[i];
6771     if (EltIdx < 0)
6772       continue;
6773     SDValue ExtOp = (EltIdx < 8) ?
6774       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6775                   DAG.getIntPtrConstant(EltIdx)) :
6776       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6777                   DAG.getIntPtrConstant(EltIdx - 8));
6778     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6779                        DAG.getIntPtrConstant(i));
6780   }
6781   return NewV;
6782 }
6783
6784 /// \brief v16i16 shuffles
6785 ///
6786 /// FIXME: We only support generation of a single pshufb currently.  We can
6787 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6788 /// well (e.g 2 x pshufb + 1 x por).
6789 static SDValue
6790 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6791   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6792   SDValue V1 = SVOp->getOperand(0);
6793   SDValue V2 = SVOp->getOperand(1);
6794   SDLoc dl(SVOp);
6795
6796   if (V2.getOpcode() != ISD::UNDEF)
6797     return SDValue();
6798
6799   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6800   return getPSHUFB(MaskVals, V1, dl, DAG);
6801 }
6802
6803 // v16i8 shuffles - Prefer shuffles in the following order:
6804 // 1. [ssse3] 1 x pshufb
6805 // 2. [ssse3] 2 x pshufb + 1 x por
6806 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6807 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6808                                         const X86Subtarget* Subtarget,
6809                                         SelectionDAG &DAG) {
6810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6811   SDValue V1 = SVOp->getOperand(0);
6812   SDValue V2 = SVOp->getOperand(1);
6813   SDLoc dl(SVOp);
6814   ArrayRef<int> MaskVals = SVOp->getMask();
6815
6816   // Promote splats to a larger type which usually leads to more efficient code.
6817   // FIXME: Is this true if pshufb is available?
6818   if (SVOp->isSplat())
6819     return PromoteSplat(SVOp, DAG);
6820
6821   // If we have SSSE3, case 1 is generated when all result bytes come from
6822   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6823   // present, fall back to case 3.
6824
6825   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6826   if (Subtarget->hasSSSE3()) {
6827     SmallVector<SDValue,16> pshufbMask;
6828
6829     // If all result elements are from one input vector, then only translate
6830     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6831     //
6832     // Otherwise, we have elements from both input vectors, and must zero out
6833     // elements that come from V2 in the first mask, and V1 in the second mask
6834     // so that we can OR them together.
6835     for (unsigned i = 0; i != 16; ++i) {
6836       int EltIdx = MaskVals[i];
6837       if (EltIdx < 0 || EltIdx >= 16)
6838         EltIdx = 0x80;
6839       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6840     }
6841     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6842                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6843                                  MVT::v16i8, pshufbMask));
6844
6845     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6846     // the 2nd operand if it's undefined or zero.
6847     if (V2.getOpcode() == ISD::UNDEF ||
6848         ISD::isBuildVectorAllZeros(V2.getNode()))
6849       return V1;
6850
6851     // Calculate the shuffle mask for the second input, shuffle it, and
6852     // OR it with the first shuffled input.
6853     pshufbMask.clear();
6854     for (unsigned i = 0; i != 16; ++i) {
6855       int EltIdx = MaskVals[i];
6856       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6857       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6858     }
6859     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6860                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6861                                  MVT::v16i8, pshufbMask));
6862     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6863   }
6864
6865   // No SSSE3 - Calculate in place words and then fix all out of place words
6866   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6867   // the 16 different words that comprise the two doublequadword input vectors.
6868   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6869   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6870   SDValue NewV = V1;
6871   for (int i = 0; i != 8; ++i) {
6872     int Elt0 = MaskVals[i*2];
6873     int Elt1 = MaskVals[i*2+1];
6874
6875     // This word of the result is all undef, skip it.
6876     if (Elt0 < 0 && Elt1 < 0)
6877       continue;
6878
6879     // This word of the result is already in the correct place, skip it.
6880     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6881       continue;
6882
6883     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6884     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6885     SDValue InsElt;
6886
6887     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6888     // using a single extract together, load it and store it.
6889     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6890       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6891                            DAG.getIntPtrConstant(Elt1 / 2));
6892       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6893                         DAG.getIntPtrConstant(i));
6894       continue;
6895     }
6896
6897     // If Elt1 is defined, extract it from the appropriate source.  If the
6898     // source byte is not also odd, shift the extracted word left 8 bits
6899     // otherwise clear the bottom 8 bits if we need to do an or.
6900     if (Elt1 >= 0) {
6901       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6902                            DAG.getIntPtrConstant(Elt1 / 2));
6903       if ((Elt1 & 1) == 0)
6904         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6905                              DAG.getConstant(8,
6906                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6907       else if (Elt0 >= 0)
6908         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6909                              DAG.getConstant(0xFF00, MVT::i16));
6910     }
6911     // If Elt0 is defined, extract it from the appropriate source.  If the
6912     // source byte is not also even, shift the extracted word right 8 bits. If
6913     // Elt1 was also defined, OR the extracted values together before
6914     // inserting them in the result.
6915     if (Elt0 >= 0) {
6916       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6917                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6918       if ((Elt0 & 1) != 0)
6919         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6920                               DAG.getConstant(8,
6921                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6922       else if (Elt1 >= 0)
6923         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6924                              DAG.getConstant(0x00FF, MVT::i16));
6925       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6926                          : InsElt0;
6927     }
6928     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6929                        DAG.getIntPtrConstant(i));
6930   }
6931   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6932 }
6933
6934 // v32i8 shuffles - Translate to VPSHUFB if possible.
6935 static
6936 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6937                                  const X86Subtarget *Subtarget,
6938                                  SelectionDAG &DAG) {
6939   MVT VT = SVOp->getSimpleValueType(0);
6940   SDValue V1 = SVOp->getOperand(0);
6941   SDValue V2 = SVOp->getOperand(1);
6942   SDLoc dl(SVOp);
6943   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6944
6945   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6946   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6947   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6948
6949   // VPSHUFB may be generated if
6950   // (1) one of input vector is undefined or zeroinitializer.
6951   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6952   // And (2) the mask indexes don't cross the 128-bit lane.
6953   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6954       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6955     return SDValue();
6956
6957   if (V1IsAllZero && !V2IsAllZero) {
6958     CommuteVectorShuffleMask(MaskVals, 32);
6959     V1 = V2;
6960   }
6961   return getPSHUFB(MaskVals, V1, dl, DAG);
6962 }
6963
6964 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6965 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6966 /// done when every pair / quad of shuffle mask elements point to elements in
6967 /// the right sequence. e.g.
6968 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6969 static
6970 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6971                                  SelectionDAG &DAG) {
6972   MVT VT = SVOp->getSimpleValueType(0);
6973   SDLoc dl(SVOp);
6974   unsigned NumElems = VT.getVectorNumElements();
6975   MVT NewVT;
6976   unsigned Scale;
6977   switch (VT.SimpleTy) {
6978   default: llvm_unreachable("Unexpected!");
6979   case MVT::v2i64:
6980   case MVT::v2f64:
6981            return SDValue(SVOp, 0);
6982   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6983   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6984   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6985   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6986   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6987   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6988   }
6989
6990   SmallVector<int, 8> MaskVec;
6991   for (unsigned i = 0; i != NumElems; i += Scale) {
6992     int StartIdx = -1;
6993     for (unsigned j = 0; j != Scale; ++j) {
6994       int EltIdx = SVOp->getMaskElt(i+j);
6995       if (EltIdx < 0)
6996         continue;
6997       if (StartIdx < 0)
6998         StartIdx = (EltIdx / Scale);
6999       if (EltIdx != (int)(StartIdx*Scale + j))
7000         return SDValue();
7001     }
7002     MaskVec.push_back(StartIdx);
7003   }
7004
7005   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7006   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7007   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7008 }
7009
7010 /// getVZextMovL - Return a zero-extending vector move low node.
7011 ///
7012 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7013                             SDValue SrcOp, SelectionDAG &DAG,
7014                             const X86Subtarget *Subtarget, SDLoc dl) {
7015   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7016     LoadSDNode *LD = nullptr;
7017     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7018       LD = dyn_cast<LoadSDNode>(SrcOp);
7019     if (!LD) {
7020       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7021       // instead.
7022       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7023       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7024           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7025           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7026           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7027         // PR2108
7028         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7029         return DAG.getNode(ISD::BITCAST, dl, VT,
7030                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7031                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7032                                                    OpVT,
7033                                                    SrcOp.getOperand(0)
7034                                                           .getOperand(0))));
7035       }
7036     }
7037   }
7038
7039   return DAG.getNode(ISD::BITCAST, dl, VT,
7040                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7041                                  DAG.getNode(ISD::BITCAST, dl,
7042                                              OpVT, SrcOp)));
7043 }
7044
7045 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7046 /// which could not be matched by any known target speficic shuffle
7047 static SDValue
7048 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7049
7050   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7051   if (NewOp.getNode())
7052     return NewOp;
7053
7054   MVT VT = SVOp->getSimpleValueType(0);
7055
7056   unsigned NumElems = VT.getVectorNumElements();
7057   unsigned NumLaneElems = NumElems / 2;
7058
7059   SDLoc dl(SVOp);
7060   MVT EltVT = VT.getVectorElementType();
7061   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7062   SDValue Output[2];
7063
7064   SmallVector<int, 16> Mask;
7065   for (unsigned l = 0; l < 2; ++l) {
7066     // Build a shuffle mask for the output, discovering on the fly which
7067     // input vectors to use as shuffle operands (recorded in InputUsed).
7068     // If building a suitable shuffle vector proves too hard, then bail
7069     // out with UseBuildVector set.
7070     bool UseBuildVector = false;
7071     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7072     unsigned LaneStart = l * NumLaneElems;
7073     for (unsigned i = 0; i != NumLaneElems; ++i) {
7074       // The mask element.  This indexes into the input.
7075       int Idx = SVOp->getMaskElt(i+LaneStart);
7076       if (Idx < 0) {
7077         // the mask element does not index into any input vector.
7078         Mask.push_back(-1);
7079         continue;
7080       }
7081
7082       // The input vector this mask element indexes into.
7083       int Input = Idx / NumLaneElems;
7084
7085       // Turn the index into an offset from the start of the input vector.
7086       Idx -= Input * NumLaneElems;
7087
7088       // Find or create a shuffle vector operand to hold this input.
7089       unsigned OpNo;
7090       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7091         if (InputUsed[OpNo] == Input)
7092           // This input vector is already an operand.
7093           break;
7094         if (InputUsed[OpNo] < 0) {
7095           // Create a new operand for this input vector.
7096           InputUsed[OpNo] = Input;
7097           break;
7098         }
7099       }
7100
7101       if (OpNo >= array_lengthof(InputUsed)) {
7102         // More than two input vectors used!  Give up on trying to create a
7103         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7104         UseBuildVector = true;
7105         break;
7106       }
7107
7108       // Add the mask index for the new shuffle vector.
7109       Mask.push_back(Idx + OpNo * NumLaneElems);
7110     }
7111
7112     if (UseBuildVector) {
7113       SmallVector<SDValue, 16> SVOps;
7114       for (unsigned i = 0; i != NumLaneElems; ++i) {
7115         // The mask element.  This indexes into the input.
7116         int Idx = SVOp->getMaskElt(i+LaneStart);
7117         if (Idx < 0) {
7118           SVOps.push_back(DAG.getUNDEF(EltVT));
7119           continue;
7120         }
7121
7122         // The input vector this mask element indexes into.
7123         int Input = Idx / NumElems;
7124
7125         // Turn the index into an offset from the start of the input vector.
7126         Idx -= Input * NumElems;
7127
7128         // Extract the vector element by hand.
7129         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7130                                     SVOp->getOperand(Input),
7131                                     DAG.getIntPtrConstant(Idx)));
7132       }
7133
7134       // Construct the output using a BUILD_VECTOR.
7135       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7136     } else if (InputUsed[0] < 0) {
7137       // No input vectors were used! The result is undefined.
7138       Output[l] = DAG.getUNDEF(NVT);
7139     } else {
7140       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7141                                         (InputUsed[0] % 2) * NumLaneElems,
7142                                         DAG, dl);
7143       // If only one input was used, use an undefined vector for the other.
7144       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7145         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7146                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7147       // At least one input vector was used. Create a new shuffle vector.
7148       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7149     }
7150
7151     Mask.clear();
7152   }
7153
7154   // Concatenate the result back
7155   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7156 }
7157
7158 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7159 /// 4 elements, and match them with several different shuffle types.
7160 static SDValue
7161 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7162   SDValue V1 = SVOp->getOperand(0);
7163   SDValue V2 = SVOp->getOperand(1);
7164   SDLoc dl(SVOp);
7165   MVT VT = SVOp->getSimpleValueType(0);
7166
7167   assert(VT.is128BitVector() && "Unsupported vector size");
7168
7169   std::pair<int, int> Locs[4];
7170   int Mask1[] = { -1, -1, -1, -1 };
7171   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7172
7173   unsigned NumHi = 0;
7174   unsigned NumLo = 0;
7175   for (unsigned i = 0; i != 4; ++i) {
7176     int Idx = PermMask[i];
7177     if (Idx < 0) {
7178       Locs[i] = std::make_pair(-1, -1);
7179     } else {
7180       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7181       if (Idx < 4) {
7182         Locs[i] = std::make_pair(0, NumLo);
7183         Mask1[NumLo] = Idx;
7184         NumLo++;
7185       } else {
7186         Locs[i] = std::make_pair(1, NumHi);
7187         if (2+NumHi < 4)
7188           Mask1[2+NumHi] = Idx;
7189         NumHi++;
7190       }
7191     }
7192   }
7193
7194   if (NumLo <= 2 && NumHi <= 2) {
7195     // If no more than two elements come from either vector. This can be
7196     // implemented with two shuffles. First shuffle gather the elements.
7197     // The second shuffle, which takes the first shuffle as both of its
7198     // vector operands, put the elements into the right order.
7199     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7200
7201     int Mask2[] = { -1, -1, -1, -1 };
7202
7203     for (unsigned i = 0; i != 4; ++i)
7204       if (Locs[i].first != -1) {
7205         unsigned Idx = (i < 2) ? 0 : 4;
7206         Idx += Locs[i].first * 2 + Locs[i].second;
7207         Mask2[i] = Idx;
7208       }
7209
7210     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7211   }
7212
7213   if (NumLo == 3 || NumHi == 3) {
7214     // Otherwise, we must have three elements from one vector, call it X, and
7215     // one element from the other, call it Y.  First, use a shufps to build an
7216     // intermediate vector with the one element from Y and the element from X
7217     // that will be in the same half in the final destination (the indexes don't
7218     // matter). Then, use a shufps to build the final vector, taking the half
7219     // containing the element from Y from the intermediate, and the other half
7220     // from X.
7221     if (NumHi == 3) {
7222       // Normalize it so the 3 elements come from V1.
7223       CommuteVectorShuffleMask(PermMask, 4);
7224       std::swap(V1, V2);
7225     }
7226
7227     // Find the element from V2.
7228     unsigned HiIndex;
7229     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7230       int Val = PermMask[HiIndex];
7231       if (Val < 0)
7232         continue;
7233       if (Val >= 4)
7234         break;
7235     }
7236
7237     Mask1[0] = PermMask[HiIndex];
7238     Mask1[1] = -1;
7239     Mask1[2] = PermMask[HiIndex^1];
7240     Mask1[3] = -1;
7241     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7242
7243     if (HiIndex >= 2) {
7244       Mask1[0] = PermMask[0];
7245       Mask1[1] = PermMask[1];
7246       Mask1[2] = HiIndex & 1 ? 6 : 4;
7247       Mask1[3] = HiIndex & 1 ? 4 : 6;
7248       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7249     }
7250
7251     Mask1[0] = HiIndex & 1 ? 2 : 0;
7252     Mask1[1] = HiIndex & 1 ? 0 : 2;
7253     Mask1[2] = PermMask[2];
7254     Mask1[3] = PermMask[3];
7255     if (Mask1[2] >= 0)
7256       Mask1[2] += 4;
7257     if (Mask1[3] >= 0)
7258       Mask1[3] += 4;
7259     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7260   }
7261
7262   // Break it into (shuffle shuffle_hi, shuffle_lo).
7263   int LoMask[] = { -1, -1, -1, -1 };
7264   int HiMask[] = { -1, -1, -1, -1 };
7265
7266   int *MaskPtr = LoMask;
7267   unsigned MaskIdx = 0;
7268   unsigned LoIdx = 0;
7269   unsigned HiIdx = 2;
7270   for (unsigned i = 0; i != 4; ++i) {
7271     if (i == 2) {
7272       MaskPtr = HiMask;
7273       MaskIdx = 1;
7274       LoIdx = 0;
7275       HiIdx = 2;
7276     }
7277     int Idx = PermMask[i];
7278     if (Idx < 0) {
7279       Locs[i] = std::make_pair(-1, -1);
7280     } else if (Idx < 4) {
7281       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7282       MaskPtr[LoIdx] = Idx;
7283       LoIdx++;
7284     } else {
7285       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7286       MaskPtr[HiIdx] = Idx;
7287       HiIdx++;
7288     }
7289   }
7290
7291   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7292   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7293   int MaskOps[] = { -1, -1, -1, -1 };
7294   for (unsigned i = 0; i != 4; ++i)
7295     if (Locs[i].first != -1)
7296       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7297   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7298 }
7299
7300 static bool MayFoldVectorLoad(SDValue V) {
7301   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7302     V = V.getOperand(0);
7303
7304   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7305     V = V.getOperand(0);
7306   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7307       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7308     // BUILD_VECTOR (load), undef
7309     V = V.getOperand(0);
7310
7311   return MayFoldLoad(V);
7312 }
7313
7314 static
7315 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7316   MVT VT = Op.getSimpleValueType();
7317
7318   // Canonizalize to v2f64.
7319   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7320   return DAG.getNode(ISD::BITCAST, dl, VT,
7321                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7322                                           V1, DAG));
7323 }
7324
7325 static
7326 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7327                         bool HasSSE2) {
7328   SDValue V1 = Op.getOperand(0);
7329   SDValue V2 = Op.getOperand(1);
7330   MVT VT = Op.getSimpleValueType();
7331
7332   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7333
7334   if (HasSSE2 && VT == MVT::v2f64)
7335     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7336
7337   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7338   return DAG.getNode(ISD::BITCAST, dl, VT,
7339                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7340                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7341                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7342 }
7343
7344 static
7345 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7346   SDValue V1 = Op.getOperand(0);
7347   SDValue V2 = Op.getOperand(1);
7348   MVT VT = Op.getSimpleValueType();
7349
7350   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7351          "unsupported shuffle type");
7352
7353   if (V2.getOpcode() == ISD::UNDEF)
7354     V2 = V1;
7355
7356   // v4i32 or v4f32
7357   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7358 }
7359
7360 static
7361 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7362   SDValue V1 = Op.getOperand(0);
7363   SDValue V2 = Op.getOperand(1);
7364   MVT VT = Op.getSimpleValueType();
7365   unsigned NumElems = VT.getVectorNumElements();
7366
7367   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7368   // operand of these instructions is only memory, so check if there's a
7369   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7370   // same masks.
7371   bool CanFoldLoad = false;
7372
7373   // Trivial case, when V2 comes from a load.
7374   if (MayFoldVectorLoad(V2))
7375     CanFoldLoad = true;
7376
7377   // When V1 is a load, it can be folded later into a store in isel, example:
7378   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7379   //    turns into:
7380   //  (MOVLPSmr addr:$src1, VR128:$src2)
7381   // So, recognize this potential and also use MOVLPS or MOVLPD
7382   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7383     CanFoldLoad = true;
7384
7385   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7386   if (CanFoldLoad) {
7387     if (HasSSE2 && NumElems == 2)
7388       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7389
7390     if (NumElems == 4)
7391       // If we don't care about the second element, proceed to use movss.
7392       if (SVOp->getMaskElt(1) != -1)
7393         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7394   }
7395
7396   // movl and movlp will both match v2i64, but v2i64 is never matched by
7397   // movl earlier because we make it strict to avoid messing with the movlp load
7398   // folding logic (see the code above getMOVLP call). Match it here then,
7399   // this is horrible, but will stay like this until we move all shuffle
7400   // matching to x86 specific nodes. Note that for the 1st condition all
7401   // types are matched with movsd.
7402   if (HasSSE2) {
7403     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7404     // as to remove this logic from here, as much as possible
7405     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7406       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7407     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7408   }
7409
7410   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7411
7412   // Invert the operand order and use SHUFPS to match it.
7413   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7414                               getShuffleSHUFImmediate(SVOp), DAG);
7415 }
7416
7417 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7418                                          SelectionDAG &DAG) {
7419   SDLoc dl(Load);
7420   MVT VT = Load->getSimpleValueType(0);
7421   MVT EVT = VT.getVectorElementType();
7422   SDValue Addr = Load->getOperand(1);
7423   SDValue NewAddr = DAG.getNode(
7424       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7425       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7426
7427   SDValue NewLoad =
7428       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7429                   DAG.getMachineFunction().getMachineMemOperand(
7430                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7431   return NewLoad;
7432 }
7433
7434 // It is only safe to call this function if isINSERTPSMask is true for
7435 // this shufflevector mask.
7436 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7437                            SelectionDAG &DAG) {
7438   // Generate an insertps instruction when inserting an f32 from memory onto a
7439   // v4f32 or when copying a member from one v4f32 to another.
7440   // We also use it for transferring i32 from one register to another,
7441   // since it simply copies the same bits.
7442   // If we're transferring an i32 from memory to a specific element in a
7443   // register, we output a generic DAG that will match the PINSRD
7444   // instruction.
7445   MVT VT = SVOp->getSimpleValueType(0);
7446   MVT EVT = VT.getVectorElementType();
7447   SDValue V1 = SVOp->getOperand(0);
7448   SDValue V2 = SVOp->getOperand(1);
7449   auto Mask = SVOp->getMask();
7450   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7451          "unsupported vector type for insertps/pinsrd");
7452
7453   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7454                              [](const int &i) { return i < 4; });
7455
7456   SDValue From;
7457   SDValue To;
7458   unsigned DestIndex;
7459   if (FromV1 == 1) {
7460     From = V1;
7461     To = V2;
7462     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7463                              [](const int &i) { return i < 4; }) -
7464                 Mask.begin();
7465   } else {
7466     From = V2;
7467     To = V1;
7468     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7469                              [](const int &i) { return i >= 4; }) -
7470                 Mask.begin();
7471   }
7472
7473   if (MayFoldLoad(From)) {
7474     // Trivial case, when From comes from a load and is only used by the
7475     // shuffle. Make it use insertps from the vector that we need from that
7476     // load.
7477     SDValue NewLoad =
7478         NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7479     if (!NewLoad.getNode())
7480       return SDValue();
7481
7482     if (EVT == MVT::f32) {
7483       // Create this as a scalar to vector to match the instruction pattern.
7484       SDValue LoadScalarToVector =
7485           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7486       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7487       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7488                          InsertpsMask);
7489     } else { // EVT == MVT::i32
7490       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7491       // instruction, to match the PINSRD instruction, which loads an i32 to a
7492       // certain vector element.
7493       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7494                          DAG.getConstant(DestIndex, MVT::i32));
7495     }
7496   }
7497
7498   // Vector-element-to-vector
7499   unsigned SrcIndex = Mask[DestIndex] % 4;
7500   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7501   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7502 }
7503
7504 // Reduce a vector shuffle to zext.
7505 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7506                                     SelectionDAG &DAG) {
7507   // PMOVZX is only available from SSE41.
7508   if (!Subtarget->hasSSE41())
7509     return SDValue();
7510
7511   MVT VT = Op.getSimpleValueType();
7512
7513   // Only AVX2 support 256-bit vector integer extending.
7514   if (!Subtarget->hasInt256() && VT.is256BitVector())
7515     return SDValue();
7516
7517   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7518   SDLoc DL(Op);
7519   SDValue V1 = Op.getOperand(0);
7520   SDValue V2 = Op.getOperand(1);
7521   unsigned NumElems = VT.getVectorNumElements();
7522
7523   // Extending is an unary operation and the element type of the source vector
7524   // won't be equal to or larger than i64.
7525   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7526       VT.getVectorElementType() == MVT::i64)
7527     return SDValue();
7528
7529   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7530   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7531   while ((1U << Shift) < NumElems) {
7532     if (SVOp->getMaskElt(1U << Shift) == 1)
7533       break;
7534     Shift += 1;
7535     // The maximal ratio is 8, i.e. from i8 to i64.
7536     if (Shift > 3)
7537       return SDValue();
7538   }
7539
7540   // Check the shuffle mask.
7541   unsigned Mask = (1U << Shift) - 1;
7542   for (unsigned i = 0; i != NumElems; ++i) {
7543     int EltIdx = SVOp->getMaskElt(i);
7544     if ((i & Mask) != 0 && EltIdx != -1)
7545       return SDValue();
7546     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7547       return SDValue();
7548   }
7549
7550   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7551   MVT NeVT = MVT::getIntegerVT(NBits);
7552   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7553
7554   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7555     return SDValue();
7556
7557   // Simplify the operand as it's prepared to be fed into shuffle.
7558   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7559   if (V1.getOpcode() == ISD::BITCAST &&
7560       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7561       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7562       V1.getOperand(0).getOperand(0)
7563         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7564     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7565     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7566     ConstantSDNode *CIdx =
7567       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7568     // If it's foldable, i.e. normal load with single use, we will let code
7569     // selection to fold it. Otherwise, we will short the conversion sequence.
7570     if (CIdx && CIdx->getZExtValue() == 0 &&
7571         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7572       MVT FullVT = V.getSimpleValueType();
7573       MVT V1VT = V1.getSimpleValueType();
7574       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7575         // The "ext_vec_elt" node is wider than the result node.
7576         // In this case we should extract subvector from V.
7577         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7578         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7579         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7580                                         FullVT.getVectorNumElements()/Ratio);
7581         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7582                         DAG.getIntPtrConstant(0));
7583       }
7584       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7585     }
7586   }
7587
7588   return DAG.getNode(ISD::BITCAST, DL, VT,
7589                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7590 }
7591
7592 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7593                                       SelectionDAG &DAG) {
7594   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7595   MVT VT = Op.getSimpleValueType();
7596   SDLoc dl(Op);
7597   SDValue V1 = Op.getOperand(0);
7598   SDValue V2 = Op.getOperand(1);
7599
7600   if (isZeroShuffle(SVOp))
7601     return getZeroVector(VT, Subtarget, DAG, dl);
7602
7603   // Handle splat operations
7604   if (SVOp->isSplat()) {
7605     // Use vbroadcast whenever the splat comes from a foldable load
7606     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7607     if (Broadcast.getNode())
7608       return Broadcast;
7609   }
7610
7611   // Check integer expanding shuffles.
7612   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7613   if (NewOp.getNode())
7614     return NewOp;
7615
7616   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7617   // do it!
7618   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7619       VT == MVT::v32i8) {
7620     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7621     if (NewOp.getNode())
7622       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7623   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7624     // FIXME: Figure out a cleaner way to do this.
7625     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7626       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7627       if (NewOp.getNode()) {
7628         MVT NewVT = NewOp.getSimpleValueType();
7629         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7630                                NewVT, true, false))
7631           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7632                               dl);
7633       }
7634     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7635       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7636       if (NewOp.getNode()) {
7637         MVT NewVT = NewOp.getSimpleValueType();
7638         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7639           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7640                               dl);
7641       }
7642     }
7643   }
7644   return SDValue();
7645 }
7646
7647 SDValue
7648 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7649   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7650   SDValue V1 = Op.getOperand(0);
7651   SDValue V2 = Op.getOperand(1);
7652   MVT VT = Op.getSimpleValueType();
7653   SDLoc dl(Op);
7654   unsigned NumElems = VT.getVectorNumElements();
7655   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7656   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7657   bool V1IsSplat = false;
7658   bool V2IsSplat = false;
7659   bool HasSSE2 = Subtarget->hasSSE2();
7660   bool HasFp256    = Subtarget->hasFp256();
7661   bool HasInt256   = Subtarget->hasInt256();
7662   MachineFunction &MF = DAG.getMachineFunction();
7663   bool OptForSize = MF.getFunction()->getAttributes().
7664     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7665
7666   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7667
7668   if (V1IsUndef && V2IsUndef)
7669     return DAG.getUNDEF(VT);
7670
7671   // When we create a shuffle node we put the UNDEF node to second operand,
7672   // but in some cases the first operand may be transformed to UNDEF.
7673   // In this case we should just commute the node.
7674   if (V1IsUndef)
7675     return CommuteVectorShuffle(SVOp, DAG);
7676
7677   // Vector shuffle lowering takes 3 steps:
7678   //
7679   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7680   //    narrowing and commutation of operands should be handled.
7681   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7682   //    shuffle nodes.
7683   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7684   //    so the shuffle can be broken into other shuffles and the legalizer can
7685   //    try the lowering again.
7686   //
7687   // The general idea is that no vector_shuffle operation should be left to
7688   // be matched during isel, all of them must be converted to a target specific
7689   // node here.
7690
7691   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7692   // narrowing and commutation of operands should be handled. The actual code
7693   // doesn't include all of those, work in progress...
7694   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7695   if (NewOp.getNode())
7696     return NewOp;
7697
7698   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7699
7700   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7701   // unpckh_undef). Only use pshufd if speed is more important than size.
7702   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7703     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7704   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7705     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7706
7707   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7708       V2IsUndef && MayFoldVectorLoad(V1))
7709     return getMOVDDup(Op, dl, V1, DAG);
7710
7711   if (isMOVHLPS_v_undef_Mask(M, VT))
7712     return getMOVHighToLow(Op, dl, DAG);
7713
7714   // Use to match splats
7715   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7716       (VT == MVT::v2f64 || VT == MVT::v2i64))
7717     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7718
7719   if (isPSHUFDMask(M, VT)) {
7720     // The actual implementation will match the mask in the if above and then
7721     // during isel it can match several different instructions, not only pshufd
7722     // as its name says, sad but true, emulate the behavior for now...
7723     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7724       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7725
7726     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7727
7728     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7729       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7730
7731     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7732       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7733                                   DAG);
7734
7735     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7736                                 TargetMask, DAG);
7737   }
7738
7739   if (isPALIGNRMask(M, VT, Subtarget))
7740     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7741                                 getShufflePALIGNRImmediate(SVOp),
7742                                 DAG);
7743
7744   // Check if this can be converted into a logical shift.
7745   bool isLeft = false;
7746   unsigned ShAmt = 0;
7747   SDValue ShVal;
7748   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7749   if (isShift && ShVal.hasOneUse()) {
7750     // If the shifted value has multiple uses, it may be cheaper to use
7751     // v_set0 + movlhps or movhlps, etc.
7752     MVT EltVT = VT.getVectorElementType();
7753     ShAmt *= EltVT.getSizeInBits();
7754     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7755   }
7756
7757   if (isMOVLMask(M, VT)) {
7758     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7759       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7760     if (!isMOVLPMask(M, VT)) {
7761       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7762         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7763
7764       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7765         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7766     }
7767   }
7768
7769   // FIXME: fold these into legal mask.
7770   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7771     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7772
7773   if (isMOVHLPSMask(M, VT))
7774     return getMOVHighToLow(Op, dl, DAG);
7775
7776   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7777     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7778
7779   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7780     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7781
7782   if (isMOVLPMask(M, VT))
7783     return getMOVLP(Op, dl, DAG, HasSSE2);
7784
7785   if (ShouldXformToMOVHLPS(M, VT) ||
7786       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7787     return CommuteVectorShuffle(SVOp, DAG);
7788
7789   if (isShift) {
7790     // No better options. Use a vshldq / vsrldq.
7791     MVT EltVT = VT.getVectorElementType();
7792     ShAmt *= EltVT.getSizeInBits();
7793     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7794   }
7795
7796   bool Commuted = false;
7797   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7798   // 1,1,1,1 -> v8i16 though.
7799   V1IsSplat = isSplatVector(V1.getNode());
7800   V2IsSplat = isSplatVector(V2.getNode());
7801
7802   // Canonicalize the splat or undef, if present, to be on the RHS.
7803   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7804     CommuteVectorShuffleMask(M, NumElems);
7805     std::swap(V1, V2);
7806     std::swap(V1IsSplat, V2IsSplat);
7807     Commuted = true;
7808   }
7809
7810   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7811     // Shuffling low element of v1 into undef, just return v1.
7812     if (V2IsUndef)
7813       return V1;
7814     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7815     // the instruction selector will not match, so get a canonical MOVL with
7816     // swapped operands to undo the commute.
7817     return getMOVL(DAG, dl, VT, V2, V1);
7818   }
7819
7820   if (isUNPCKLMask(M, VT, HasInt256))
7821     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7822
7823   if (isUNPCKHMask(M, VT, HasInt256))
7824     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7825
7826   if (V2IsSplat) {
7827     // Normalize mask so all entries that point to V2 points to its first
7828     // element then try to match unpck{h|l} again. If match, return a
7829     // new vector_shuffle with the corrected mask.p
7830     SmallVector<int, 8> NewMask(M.begin(), M.end());
7831     NormalizeMask(NewMask, NumElems);
7832     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7833       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7834     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7835       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7836   }
7837
7838   if (Commuted) {
7839     // Commute is back and try unpck* again.
7840     // FIXME: this seems wrong.
7841     CommuteVectorShuffleMask(M, NumElems);
7842     std::swap(V1, V2);
7843     std::swap(V1IsSplat, V2IsSplat);
7844
7845     if (isUNPCKLMask(M, VT, HasInt256))
7846       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7847
7848     if (isUNPCKHMask(M, VT, HasInt256))
7849       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7850   }
7851
7852   // Normalize the node to match x86 shuffle ops if needed
7853   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7854     return CommuteVectorShuffle(SVOp, DAG);
7855
7856   // The checks below are all present in isShuffleMaskLegal, but they are
7857   // inlined here right now to enable us to directly emit target specific
7858   // nodes, and remove one by one until they don't return Op anymore.
7859
7860   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7861       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7862     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7863       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7864   }
7865
7866   if (isPSHUFHWMask(M, VT, HasInt256))
7867     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7868                                 getShufflePSHUFHWImmediate(SVOp),
7869                                 DAG);
7870
7871   if (isPSHUFLWMask(M, VT, HasInt256))
7872     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7873                                 getShufflePSHUFLWImmediate(SVOp),
7874                                 DAG);
7875
7876   if (isSHUFPMask(M, VT))
7877     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7878                                 getShuffleSHUFImmediate(SVOp), DAG);
7879
7880   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7881     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7882   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7883     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7884
7885   //===--------------------------------------------------------------------===//
7886   // Generate target specific nodes for 128 or 256-bit shuffles only
7887   // supported in the AVX instruction set.
7888   //
7889
7890   // Handle VMOVDDUPY permutations
7891   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7892     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7893
7894   // Handle VPERMILPS/D* permutations
7895   if (isVPERMILPMask(M, VT)) {
7896     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7897       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7898                                   getShuffleSHUFImmediate(SVOp), DAG);
7899     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7900                                 getShuffleSHUFImmediate(SVOp), DAG);
7901   }
7902
7903   unsigned Idx;
7904   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7905     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7906                               Idx*(NumElems/2), DAG, dl);
7907
7908   // Handle VPERM2F128/VPERM2I128 permutations
7909   if (isVPERM2X128Mask(M, VT, HasFp256))
7910     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7911                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7912
7913   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7914   if (BlendOp.getNode())
7915     return BlendOp;
7916
7917   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7918     return getINSERTPS(SVOp, dl, DAG);
7919
7920   unsigned Imm8;
7921   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7922     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7923
7924   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7925       VT.is512BitVector()) {
7926     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7927     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7928     SmallVector<SDValue, 16> permclMask;
7929     for (unsigned i = 0; i != NumElems; ++i) {
7930       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7931     }
7932
7933     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7934     if (V2IsUndef)
7935       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7936       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7937                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7938     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7939                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7940   }
7941
7942   //===--------------------------------------------------------------------===//
7943   // Since no target specific shuffle was selected for this generic one,
7944   // lower it into other known shuffles. FIXME: this isn't true yet, but
7945   // this is the plan.
7946   //
7947
7948   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7949   if (VT == MVT::v8i16) {
7950     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7951     if (NewOp.getNode())
7952       return NewOp;
7953   }
7954
7955   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7956     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7957     if (NewOp.getNode())
7958       return NewOp;
7959   }
7960
7961   if (VT == MVT::v16i8) {
7962     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7963     if (NewOp.getNode())
7964       return NewOp;
7965   }
7966
7967   if (VT == MVT::v32i8) {
7968     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7969     if (NewOp.getNode())
7970       return NewOp;
7971   }
7972
7973   // Handle all 128-bit wide vectors with 4 elements, and match them with
7974   // several different shuffle types.
7975   if (NumElems == 4 && VT.is128BitVector())
7976     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7977
7978   // Handle general 256-bit shuffles
7979   if (VT.is256BitVector())
7980     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7981
7982   return SDValue();
7983 }
7984
7985 // This function assumes its argument is a BUILD_VECTOR of constants or
7986 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
7987 // true.
7988 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
7989                                     unsigned &MaskValue) {
7990   MaskValue = 0;
7991   unsigned NumElems = BuildVector->getNumOperands();
7992   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7993   unsigned NumLanes = (NumElems - 1) / 8 + 1;
7994   unsigned NumElemsInLane = NumElems / NumLanes;
7995
7996   // Blend for v16i16 should be symetric for the both lanes.
7997   for (unsigned i = 0; i < NumElemsInLane; ++i) {
7998     SDValue EltCond = BuildVector->getOperand(i);
7999     SDValue SndLaneEltCond =
8000         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8001
8002     int Lane1Cond = -1, Lane2Cond = -1;
8003     if (isa<ConstantSDNode>(EltCond))
8004       Lane1Cond = !isZero(EltCond);
8005     if (isa<ConstantSDNode>(SndLaneEltCond))
8006       Lane2Cond = !isZero(SndLaneEltCond);
8007
8008     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8009       // Lane1Cond != 0, means we want the first argument.
8010       // Lane1Cond == 0, means we want the second argument.
8011       // The encoding of this argument is 0 for the first argument, 1
8012       // for the second. Therefore, invert the condition.
8013       MaskValue |= !Lane1Cond << i;
8014     else if (Lane1Cond < 0)
8015       MaskValue |= !Lane2Cond << i;
8016     else
8017       return false;
8018   }
8019   return true;
8020 }
8021
8022 // Try to lower a vselect node into a simple blend instruction.
8023 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8024                                    SelectionDAG &DAG) {
8025   SDValue Cond = Op.getOperand(0);
8026   SDValue LHS = Op.getOperand(1);
8027   SDValue RHS = Op.getOperand(2);
8028   SDLoc dl(Op);
8029   MVT VT = Op.getSimpleValueType();
8030   MVT EltVT = VT.getVectorElementType();
8031   unsigned NumElems = VT.getVectorNumElements();
8032
8033   // There is no blend with immediate in AVX-512.
8034   if (VT.is512BitVector())
8035     return SDValue();
8036
8037   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8038     return SDValue();
8039   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8040     return SDValue();
8041
8042   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8043     return SDValue();
8044
8045   // Check the mask for BLEND and build the value.
8046   unsigned MaskValue = 0;
8047   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8048     return SDValue();
8049
8050   // Convert i32 vectors to floating point if it is not AVX2.
8051   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8052   MVT BlendVT = VT;
8053   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8054     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8055                                NumElems);
8056     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8057     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8058   }
8059
8060   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8061                             DAG.getConstant(MaskValue, MVT::i32));
8062   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8063 }
8064
8065 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8066   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8067   if (BlendOp.getNode())
8068     return BlendOp;
8069
8070   // Some types for vselect were previously set to Expand, not Legal or
8071   // Custom. Return an empty SDValue so we fall-through to Expand, after
8072   // the Custom lowering phase.
8073   MVT VT = Op.getSimpleValueType();
8074   switch (VT.SimpleTy) {
8075   default:
8076     break;
8077   case MVT::v8i16:
8078   case MVT::v16i16:
8079     return SDValue();
8080   }
8081
8082   // We couldn't create a "Blend with immediate" node.
8083   // This node should still be legal, but we'll have to emit a blendv*
8084   // instruction.
8085   return Op;
8086 }
8087
8088 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8089   MVT VT = Op.getSimpleValueType();
8090   SDLoc dl(Op);
8091
8092   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8093     return SDValue();
8094
8095   if (VT.getSizeInBits() == 8) {
8096     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8097                                   Op.getOperand(0), Op.getOperand(1));
8098     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8099                                   DAG.getValueType(VT));
8100     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8101   }
8102
8103   if (VT.getSizeInBits() == 16) {
8104     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8105     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8106     if (Idx == 0)
8107       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8108                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8109                                      DAG.getNode(ISD::BITCAST, dl,
8110                                                  MVT::v4i32,
8111                                                  Op.getOperand(0)),
8112                                      Op.getOperand(1)));
8113     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8114                                   Op.getOperand(0), Op.getOperand(1));
8115     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8116                                   DAG.getValueType(VT));
8117     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8118   }
8119
8120   if (VT == MVT::f32) {
8121     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8122     // the result back to FR32 register. It's only worth matching if the
8123     // result has a single use which is a store or a bitcast to i32.  And in
8124     // the case of a store, it's not worth it if the index is a constant 0,
8125     // because a MOVSSmr can be used instead, which is smaller and faster.
8126     if (!Op.hasOneUse())
8127       return SDValue();
8128     SDNode *User = *Op.getNode()->use_begin();
8129     if ((User->getOpcode() != ISD::STORE ||
8130          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8131           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8132         (User->getOpcode() != ISD::BITCAST ||
8133          User->getValueType(0) != MVT::i32))
8134       return SDValue();
8135     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8136                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8137                                               Op.getOperand(0)),
8138                                               Op.getOperand(1));
8139     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8140   }
8141
8142   if (VT == MVT::i32 || VT == MVT::i64) {
8143     // ExtractPS/pextrq works with constant index.
8144     if (isa<ConstantSDNode>(Op.getOperand(1)))
8145       return Op;
8146   }
8147   return SDValue();
8148 }
8149
8150 /// Extract one bit from mask vector, like v16i1 or v8i1.
8151 /// AVX-512 feature.
8152 SDValue
8153 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8154   SDValue Vec = Op.getOperand(0);
8155   SDLoc dl(Vec);
8156   MVT VecVT = Vec.getSimpleValueType();
8157   SDValue Idx = Op.getOperand(1);
8158   MVT EltVT = Op.getSimpleValueType();
8159
8160   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8161
8162   // variable index can't be handled in mask registers,
8163   // extend vector to VR512
8164   if (!isa<ConstantSDNode>(Idx)) {
8165     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8166     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8167     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8168                               ExtVT.getVectorElementType(), Ext, Idx);
8169     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8170   }
8171
8172   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8173   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8174   unsigned MaxSift = rc->getSize()*8 - 1;
8175   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8176                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8177   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8178                     DAG.getConstant(MaxSift, MVT::i8));
8179   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8180                        DAG.getIntPtrConstant(0));
8181 }
8182
8183 SDValue
8184 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8185                                            SelectionDAG &DAG) const {
8186   SDLoc dl(Op);
8187   SDValue Vec = Op.getOperand(0);
8188   MVT VecVT = Vec.getSimpleValueType();
8189   SDValue Idx = Op.getOperand(1);
8190
8191   if (Op.getSimpleValueType() == MVT::i1)
8192     return ExtractBitFromMaskVector(Op, DAG);
8193
8194   if (!isa<ConstantSDNode>(Idx)) {
8195     if (VecVT.is512BitVector() ||
8196         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8197          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8198
8199       MVT MaskEltVT =
8200         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8201       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8202                                     MaskEltVT.getSizeInBits());
8203
8204       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8205       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8206                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8207                                 Idx, DAG.getConstant(0, getPointerTy()));
8208       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8209       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8210                         Perm, DAG.getConstant(0, getPointerTy()));
8211     }
8212     return SDValue();
8213   }
8214
8215   // If this is a 256-bit vector result, first extract the 128-bit vector and
8216   // then extract the element from the 128-bit vector.
8217   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8218
8219     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8220     // Get the 128-bit vector.
8221     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8222     MVT EltVT = VecVT.getVectorElementType();
8223
8224     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8225
8226     //if (IdxVal >= NumElems/2)
8227     //  IdxVal -= NumElems/2;
8228     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8229     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8230                        DAG.getConstant(IdxVal, MVT::i32));
8231   }
8232
8233   assert(VecVT.is128BitVector() && "Unexpected vector length");
8234
8235   if (Subtarget->hasSSE41()) {
8236     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8237     if (Res.getNode())
8238       return Res;
8239   }
8240
8241   MVT VT = Op.getSimpleValueType();
8242   // TODO: handle v16i8.
8243   if (VT.getSizeInBits() == 16) {
8244     SDValue Vec = Op.getOperand(0);
8245     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8246     if (Idx == 0)
8247       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8248                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8249                                      DAG.getNode(ISD::BITCAST, dl,
8250                                                  MVT::v4i32, Vec),
8251                                      Op.getOperand(1)));
8252     // Transform it so it match pextrw which produces a 32-bit result.
8253     MVT EltVT = MVT::i32;
8254     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8255                                   Op.getOperand(0), Op.getOperand(1));
8256     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8257                                   DAG.getValueType(VT));
8258     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8259   }
8260
8261   if (VT.getSizeInBits() == 32) {
8262     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8263     if (Idx == 0)
8264       return Op;
8265
8266     // SHUFPS the element to the lowest double word, then movss.
8267     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8268     MVT VVT = Op.getOperand(0).getSimpleValueType();
8269     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8270                                        DAG.getUNDEF(VVT), Mask);
8271     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8272                        DAG.getIntPtrConstant(0));
8273   }
8274
8275   if (VT.getSizeInBits() == 64) {
8276     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8277     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8278     //        to match extract_elt for f64.
8279     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8280     if (Idx == 0)
8281       return Op;
8282
8283     // UNPCKHPD the element to the lowest double word, then movsd.
8284     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8285     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8286     int Mask[2] = { 1, -1 };
8287     MVT VVT = Op.getOperand(0).getSimpleValueType();
8288     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8289                                        DAG.getUNDEF(VVT), Mask);
8290     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8291                        DAG.getIntPtrConstant(0));
8292   }
8293
8294   return SDValue();
8295 }
8296
8297 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8298   MVT VT = Op.getSimpleValueType();
8299   MVT EltVT = VT.getVectorElementType();
8300   SDLoc dl(Op);
8301
8302   SDValue N0 = Op.getOperand(0);
8303   SDValue N1 = Op.getOperand(1);
8304   SDValue N2 = Op.getOperand(2);
8305
8306   if (!VT.is128BitVector())
8307     return SDValue();
8308
8309   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8310       isa<ConstantSDNode>(N2)) {
8311     unsigned Opc;
8312     if (VT == MVT::v8i16)
8313       Opc = X86ISD::PINSRW;
8314     else if (VT == MVT::v16i8)
8315       Opc = X86ISD::PINSRB;
8316     else
8317       Opc = X86ISD::PINSRB;
8318
8319     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8320     // argument.
8321     if (N1.getValueType() != MVT::i32)
8322       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8323     if (N2.getValueType() != MVT::i32)
8324       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8325     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8326   }
8327
8328   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8329     // Bits [7:6] of the constant are the source select.  This will always be
8330     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8331     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8332     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8333     // Bits [5:4] of the constant are the destination select.  This is the
8334     //  value of the incoming immediate.
8335     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8336     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8337     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8338     // Create this as a scalar to vector..
8339     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8340     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8341   }
8342
8343   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8344     // PINSR* works with constant index.
8345     return Op;
8346   }
8347   return SDValue();
8348 }
8349
8350 /// Insert one bit to mask vector, like v16i1 or v8i1.
8351 /// AVX-512 feature.
8352 SDValue 
8353 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8354   SDLoc dl(Op);
8355   SDValue Vec = Op.getOperand(0);
8356   SDValue Elt = Op.getOperand(1);
8357   SDValue Idx = Op.getOperand(2);
8358   MVT VecVT = Vec.getSimpleValueType();
8359
8360   if (!isa<ConstantSDNode>(Idx)) {
8361     // Non constant index. Extend source and destination,
8362     // insert element and then truncate the result.
8363     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8364     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8365     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8366       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8367       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8368     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8369   }
8370
8371   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8372   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8373   if (Vec.getOpcode() == ISD::UNDEF)
8374     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8375                        DAG.getConstant(IdxVal, MVT::i8));
8376   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8377   unsigned MaxSift = rc->getSize()*8 - 1;
8378   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8379                     DAG.getConstant(MaxSift, MVT::i8));
8380   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8381                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8382   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8383 }
8384 SDValue
8385 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8386   MVT VT = Op.getSimpleValueType();
8387   MVT EltVT = VT.getVectorElementType();
8388   
8389   if (EltVT == MVT::i1)
8390     return InsertBitToMaskVector(Op, DAG);
8391
8392   SDLoc dl(Op);
8393   SDValue N0 = Op.getOperand(0);
8394   SDValue N1 = Op.getOperand(1);
8395   SDValue N2 = Op.getOperand(2);
8396
8397   // If this is a 256-bit vector result, first extract the 128-bit vector,
8398   // insert the element into the extracted half and then place it back.
8399   if (VT.is256BitVector() || VT.is512BitVector()) {
8400     if (!isa<ConstantSDNode>(N2))
8401       return SDValue();
8402
8403     // Get the desired 128-bit vector half.
8404     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8405     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8406
8407     // Insert the element into the desired half.
8408     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8409     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8410
8411     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8412                     DAG.getConstant(IdxIn128, MVT::i32));
8413
8414     // Insert the changed part back to the 256-bit vector
8415     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8416   }
8417
8418   if (Subtarget->hasSSE41())
8419     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8420
8421   if (EltVT == MVT::i8)
8422     return SDValue();
8423
8424   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8425     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8426     // as its second argument.
8427     if (N1.getValueType() != MVT::i32)
8428       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8429     if (N2.getValueType() != MVT::i32)
8430       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8431     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8432   }
8433   return SDValue();
8434 }
8435
8436 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8437   SDLoc dl(Op);
8438   MVT OpVT = Op.getSimpleValueType();
8439
8440   // If this is a 256-bit vector result, first insert into a 128-bit
8441   // vector and then insert into the 256-bit vector.
8442   if (!OpVT.is128BitVector()) {
8443     // Insert into a 128-bit vector.
8444     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8445     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8446                                  OpVT.getVectorNumElements() / SizeFactor);
8447
8448     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8449
8450     // Insert the 128-bit vector.
8451     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8452   }
8453
8454   if (OpVT == MVT::v1i64 &&
8455       Op.getOperand(0).getValueType() == MVT::i64)
8456     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8457
8458   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8459   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8460   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8461                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8462 }
8463
8464 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8465 // a simple subregister reference or explicit instructions to grab
8466 // upper bits of a vector.
8467 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8468                                       SelectionDAG &DAG) {
8469   SDLoc dl(Op);
8470   SDValue In =  Op.getOperand(0);
8471   SDValue Idx = Op.getOperand(1);
8472   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8473   MVT ResVT   = Op.getSimpleValueType();
8474   MVT InVT    = In.getSimpleValueType();
8475
8476   if (Subtarget->hasFp256()) {
8477     if (ResVT.is128BitVector() &&
8478         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8479         isa<ConstantSDNode>(Idx)) {
8480       return Extract128BitVector(In, IdxVal, DAG, dl);
8481     }
8482     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8483         isa<ConstantSDNode>(Idx)) {
8484       return Extract256BitVector(In, IdxVal, DAG, dl);
8485     }
8486   }
8487   return SDValue();
8488 }
8489
8490 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8491 // simple superregister reference or explicit instructions to insert
8492 // the upper bits of a vector.
8493 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8494                                      SelectionDAG &DAG) {
8495   if (Subtarget->hasFp256()) {
8496     SDLoc dl(Op.getNode());
8497     SDValue Vec = Op.getNode()->getOperand(0);
8498     SDValue SubVec = Op.getNode()->getOperand(1);
8499     SDValue Idx = Op.getNode()->getOperand(2);
8500
8501     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8502          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8503         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8504         isa<ConstantSDNode>(Idx)) {
8505       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8506       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8507     }
8508
8509     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8510         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8511         isa<ConstantSDNode>(Idx)) {
8512       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8513       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8514     }
8515   }
8516   return SDValue();
8517 }
8518
8519 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8520 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8521 // one of the above mentioned nodes. It has to be wrapped because otherwise
8522 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8523 // be used to form addressing mode. These wrapped nodes will be selected
8524 // into MOV32ri.
8525 SDValue
8526 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8527   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8528
8529   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8530   // global base reg.
8531   unsigned char OpFlag = 0;
8532   unsigned WrapperKind = X86ISD::Wrapper;
8533   CodeModel::Model M = getTargetMachine().getCodeModel();
8534
8535   if (Subtarget->isPICStyleRIPRel() &&
8536       (M == CodeModel::Small || M == CodeModel::Kernel))
8537     WrapperKind = X86ISD::WrapperRIP;
8538   else if (Subtarget->isPICStyleGOT())
8539     OpFlag = X86II::MO_GOTOFF;
8540   else if (Subtarget->isPICStyleStubPIC())
8541     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8542
8543   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8544                                              CP->getAlignment(),
8545                                              CP->getOffset(), OpFlag);
8546   SDLoc DL(CP);
8547   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8548   // With PIC, the address is actually $g + Offset.
8549   if (OpFlag) {
8550     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8551                          DAG.getNode(X86ISD::GlobalBaseReg,
8552                                      SDLoc(), getPointerTy()),
8553                          Result);
8554   }
8555
8556   return Result;
8557 }
8558
8559 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8560   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8561
8562   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8563   // global base reg.
8564   unsigned char OpFlag = 0;
8565   unsigned WrapperKind = X86ISD::Wrapper;
8566   CodeModel::Model M = getTargetMachine().getCodeModel();
8567
8568   if (Subtarget->isPICStyleRIPRel() &&
8569       (M == CodeModel::Small || M == CodeModel::Kernel))
8570     WrapperKind = X86ISD::WrapperRIP;
8571   else if (Subtarget->isPICStyleGOT())
8572     OpFlag = X86II::MO_GOTOFF;
8573   else if (Subtarget->isPICStyleStubPIC())
8574     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8575
8576   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8577                                           OpFlag);
8578   SDLoc DL(JT);
8579   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8580
8581   // With PIC, the address is actually $g + Offset.
8582   if (OpFlag)
8583     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8584                          DAG.getNode(X86ISD::GlobalBaseReg,
8585                                      SDLoc(), getPointerTy()),
8586                          Result);
8587
8588   return Result;
8589 }
8590
8591 SDValue
8592 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8593   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8594
8595   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8596   // global base reg.
8597   unsigned char OpFlag = 0;
8598   unsigned WrapperKind = X86ISD::Wrapper;
8599   CodeModel::Model M = getTargetMachine().getCodeModel();
8600
8601   if (Subtarget->isPICStyleRIPRel() &&
8602       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8603     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8604       OpFlag = X86II::MO_GOTPCREL;
8605     WrapperKind = X86ISD::WrapperRIP;
8606   } else if (Subtarget->isPICStyleGOT()) {
8607     OpFlag = X86II::MO_GOT;
8608   } else if (Subtarget->isPICStyleStubPIC()) {
8609     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8610   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8611     OpFlag = X86II::MO_DARWIN_NONLAZY;
8612   }
8613
8614   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8615
8616   SDLoc DL(Op);
8617   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8618
8619   // With PIC, the address is actually $g + Offset.
8620   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8621       !Subtarget->is64Bit()) {
8622     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8623                          DAG.getNode(X86ISD::GlobalBaseReg,
8624                                      SDLoc(), getPointerTy()),
8625                          Result);
8626   }
8627
8628   // For symbols that require a load from a stub to get the address, emit the
8629   // load.
8630   if (isGlobalStubReference(OpFlag))
8631     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8632                          MachinePointerInfo::getGOT(), false, false, false, 0);
8633
8634   return Result;
8635 }
8636
8637 SDValue
8638 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8639   // Create the TargetBlockAddressAddress node.
8640   unsigned char OpFlags =
8641     Subtarget->ClassifyBlockAddressReference();
8642   CodeModel::Model M = getTargetMachine().getCodeModel();
8643   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8644   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8645   SDLoc dl(Op);
8646   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8647                                              OpFlags);
8648
8649   if (Subtarget->isPICStyleRIPRel() &&
8650       (M == CodeModel::Small || M == CodeModel::Kernel))
8651     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8652   else
8653     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8654
8655   // With PIC, the address is actually $g + Offset.
8656   if (isGlobalRelativeToPICBase(OpFlags)) {
8657     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8658                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8659                          Result);
8660   }
8661
8662   return Result;
8663 }
8664
8665 SDValue
8666 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8667                                       int64_t Offset, SelectionDAG &DAG) const {
8668   // Create the TargetGlobalAddress node, folding in the constant
8669   // offset if it is legal.
8670   unsigned char OpFlags =
8671     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8672   CodeModel::Model M = getTargetMachine().getCodeModel();
8673   SDValue Result;
8674   if (OpFlags == X86II::MO_NO_FLAG &&
8675       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8676     // A direct static reference to a global.
8677     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8678     Offset = 0;
8679   } else {
8680     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8681   }
8682
8683   if (Subtarget->isPICStyleRIPRel() &&
8684       (M == CodeModel::Small || M == CodeModel::Kernel))
8685     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8686   else
8687     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8688
8689   // With PIC, the address is actually $g + Offset.
8690   if (isGlobalRelativeToPICBase(OpFlags)) {
8691     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8692                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8693                          Result);
8694   }
8695
8696   // For globals that require a load from a stub to get the address, emit the
8697   // load.
8698   if (isGlobalStubReference(OpFlags))
8699     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8700                          MachinePointerInfo::getGOT(), false, false, false, 0);
8701
8702   // If there was a non-zero offset that we didn't fold, create an explicit
8703   // addition for it.
8704   if (Offset != 0)
8705     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8706                          DAG.getConstant(Offset, getPointerTy()));
8707
8708   return Result;
8709 }
8710
8711 SDValue
8712 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8713   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8714   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8715   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8716 }
8717
8718 static SDValue
8719 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8720            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8721            unsigned char OperandFlags, bool LocalDynamic = false) {
8722   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8723   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8724   SDLoc dl(GA);
8725   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8726                                            GA->getValueType(0),
8727                                            GA->getOffset(),
8728                                            OperandFlags);
8729
8730   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8731                                            : X86ISD::TLSADDR;
8732
8733   if (InFlag) {
8734     SDValue Ops[] = { Chain,  TGA, *InFlag };
8735     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8736   } else {
8737     SDValue Ops[]  = { Chain, TGA };
8738     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8739   }
8740
8741   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8742   MFI->setAdjustsStack(true);
8743
8744   SDValue Flag = Chain.getValue(1);
8745   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8746 }
8747
8748 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8749 static SDValue
8750 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8751                                 const EVT PtrVT) {
8752   SDValue InFlag;
8753   SDLoc dl(GA);  // ? function entry point might be better
8754   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8755                                    DAG.getNode(X86ISD::GlobalBaseReg,
8756                                                SDLoc(), PtrVT), InFlag);
8757   InFlag = Chain.getValue(1);
8758
8759   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8760 }
8761
8762 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8763 static SDValue
8764 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8765                                 const EVT PtrVT) {
8766   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8767                     X86::RAX, X86II::MO_TLSGD);
8768 }
8769
8770 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8771                                            SelectionDAG &DAG,
8772                                            const EVT PtrVT,
8773                                            bool is64Bit) {
8774   SDLoc dl(GA);
8775
8776   // Get the start address of the TLS block for this module.
8777   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8778       .getInfo<X86MachineFunctionInfo>();
8779   MFI->incNumLocalDynamicTLSAccesses();
8780
8781   SDValue Base;
8782   if (is64Bit) {
8783     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8784                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8785   } else {
8786     SDValue InFlag;
8787     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8788         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8789     InFlag = Chain.getValue(1);
8790     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8791                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8792   }
8793
8794   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8795   // of Base.
8796
8797   // Build x@dtpoff.
8798   unsigned char OperandFlags = X86II::MO_DTPOFF;
8799   unsigned WrapperKind = X86ISD::Wrapper;
8800   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8801                                            GA->getValueType(0),
8802                                            GA->getOffset(), OperandFlags);
8803   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8804
8805   // Add x@dtpoff with the base.
8806   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8807 }
8808
8809 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8810 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8811                                    const EVT PtrVT, TLSModel::Model model,
8812                                    bool is64Bit, bool isPIC) {
8813   SDLoc dl(GA);
8814
8815   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8816   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8817                                                          is64Bit ? 257 : 256));
8818
8819   SDValue ThreadPointer =
8820       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8821                   MachinePointerInfo(Ptr), false, false, false, 0);
8822
8823   unsigned char OperandFlags = 0;
8824   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8825   // initialexec.
8826   unsigned WrapperKind = X86ISD::Wrapper;
8827   if (model == TLSModel::LocalExec) {
8828     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8829   } else if (model == TLSModel::InitialExec) {
8830     if (is64Bit) {
8831       OperandFlags = X86II::MO_GOTTPOFF;
8832       WrapperKind = X86ISD::WrapperRIP;
8833     } else {
8834       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8835     }
8836   } else {
8837     llvm_unreachable("Unexpected model");
8838   }
8839
8840   // emit "addl x@ntpoff,%eax" (local exec)
8841   // or "addl x@indntpoff,%eax" (initial exec)
8842   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8843   SDValue TGA =
8844       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8845                                  GA->getOffset(), OperandFlags);
8846   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8847
8848   if (model == TLSModel::InitialExec) {
8849     if (isPIC && !is64Bit) {
8850       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8851                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8852                            Offset);
8853     }
8854
8855     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8856                          MachinePointerInfo::getGOT(), false, false, false, 0);
8857   }
8858
8859   // The address of the thread local variable is the add of the thread
8860   // pointer with the offset of the variable.
8861   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8862 }
8863
8864 SDValue
8865 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8866
8867   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8868   const GlobalValue *GV = GA->getGlobal();
8869
8870   if (Subtarget->isTargetELF()) {
8871     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8872
8873     switch (model) {
8874       case TLSModel::GeneralDynamic:
8875         if (Subtarget->is64Bit())
8876           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8877         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8878       case TLSModel::LocalDynamic:
8879         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8880                                            Subtarget->is64Bit());
8881       case TLSModel::InitialExec:
8882       case TLSModel::LocalExec:
8883         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8884                                    Subtarget->is64Bit(),
8885                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8886     }
8887     llvm_unreachable("Unknown TLS model.");
8888   }
8889
8890   if (Subtarget->isTargetDarwin()) {
8891     // Darwin only has one model of TLS.  Lower to that.
8892     unsigned char OpFlag = 0;
8893     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8894                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8895
8896     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8897     // global base reg.
8898     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8899                   !Subtarget->is64Bit();
8900     if (PIC32)
8901       OpFlag = X86II::MO_TLVP_PIC_BASE;
8902     else
8903       OpFlag = X86II::MO_TLVP;
8904     SDLoc DL(Op);
8905     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8906                                                 GA->getValueType(0),
8907                                                 GA->getOffset(), OpFlag);
8908     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8909
8910     // With PIC32, the address is actually $g + Offset.
8911     if (PIC32)
8912       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8913                            DAG.getNode(X86ISD::GlobalBaseReg,
8914                                        SDLoc(), getPointerTy()),
8915                            Offset);
8916
8917     // Lowering the machine isd will make sure everything is in the right
8918     // location.
8919     SDValue Chain = DAG.getEntryNode();
8920     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8921     SDValue Args[] = { Chain, Offset };
8922     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8923
8924     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8925     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8926     MFI->setAdjustsStack(true);
8927
8928     // And our return value (tls address) is in the standard call return value
8929     // location.
8930     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8931     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8932                               Chain.getValue(1));
8933   }
8934
8935   if (Subtarget->isTargetKnownWindowsMSVC() ||
8936       Subtarget->isTargetWindowsGNU()) {
8937     // Just use the implicit TLS architecture
8938     // Need to generate someting similar to:
8939     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8940     //                                  ; from TEB
8941     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8942     //   mov     rcx, qword [rdx+rcx*8]
8943     //   mov     eax, .tls$:tlsvar
8944     //   [rax+rcx] contains the address
8945     // Windows 64bit: gs:0x58
8946     // Windows 32bit: fs:__tls_array
8947
8948     // If GV is an alias then use the aliasee for determining
8949     // thread-localness.
8950     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8951       GV = GA->getAliasee();
8952     SDLoc dl(GA);
8953     SDValue Chain = DAG.getEntryNode();
8954
8955     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8956     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8957     // use its literal value of 0x2C.
8958     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8959                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8960                                                              256)
8961                                         : Type::getInt32PtrTy(*DAG.getContext(),
8962                                                               257));
8963
8964     SDValue TlsArray =
8965         Subtarget->is64Bit()
8966             ? DAG.getIntPtrConstant(0x58)
8967             : (Subtarget->isTargetWindowsGNU()
8968                    ? DAG.getIntPtrConstant(0x2C)
8969                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8970
8971     SDValue ThreadPointer =
8972         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8973                     MachinePointerInfo(Ptr), false, false, false, 0);
8974
8975     // Load the _tls_index variable
8976     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8977     if (Subtarget->is64Bit())
8978       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8979                            IDX, MachinePointerInfo(), MVT::i32,
8980                            false, false, 0);
8981     else
8982       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8983                         false, false, false, 0);
8984
8985     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8986                                     getPointerTy());
8987     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8988
8989     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8990     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8991                       false, false, false, 0);
8992
8993     // Get the offset of start of .tls section
8994     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8995                                              GA->getValueType(0),
8996                                              GA->getOffset(), X86II::MO_SECREL);
8997     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8998
8999     // The address of the thread local variable is the add of the thread
9000     // pointer with the offset of the variable.
9001     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9002   }
9003
9004   llvm_unreachable("TLS not implemented for this target.");
9005 }
9006
9007 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9008 /// and take a 2 x i32 value to shift plus a shift amount.
9009 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9010   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9011   MVT VT = Op.getSimpleValueType();
9012   unsigned VTBits = VT.getSizeInBits();
9013   SDLoc dl(Op);
9014   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9015   SDValue ShOpLo = Op.getOperand(0);
9016   SDValue ShOpHi = Op.getOperand(1);
9017   SDValue ShAmt  = Op.getOperand(2);
9018   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9019   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9020   // during isel.
9021   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9022                                   DAG.getConstant(VTBits - 1, MVT::i8));
9023   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9024                                      DAG.getConstant(VTBits - 1, MVT::i8))
9025                        : DAG.getConstant(0, VT);
9026
9027   SDValue Tmp2, Tmp3;
9028   if (Op.getOpcode() == ISD::SHL_PARTS) {
9029     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9030     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9031   } else {
9032     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9033     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9034   }
9035
9036   // If the shift amount is larger or equal than the width of a part we can't
9037   // rely on the results of shld/shrd. Insert a test and select the appropriate
9038   // values for large shift amounts.
9039   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9040                                 DAG.getConstant(VTBits, MVT::i8));
9041   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9042                              AndNode, DAG.getConstant(0, MVT::i8));
9043
9044   SDValue Hi, Lo;
9045   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9046   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9047   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9048
9049   if (Op.getOpcode() == ISD::SHL_PARTS) {
9050     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9051     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9052   } else {
9053     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9054     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9055   }
9056
9057   SDValue Ops[2] = { Lo, Hi };
9058   return DAG.getMergeValues(Ops, dl);
9059 }
9060
9061 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9062                                            SelectionDAG &DAG) const {
9063   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9064
9065   if (SrcVT.isVector())
9066     return SDValue();
9067
9068   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9069          "Unknown SINT_TO_FP to lower!");
9070
9071   // These are really Legal; return the operand so the caller accepts it as
9072   // Legal.
9073   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9074     return Op;
9075   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9076       Subtarget->is64Bit()) {
9077     return Op;
9078   }
9079
9080   SDLoc dl(Op);
9081   unsigned Size = SrcVT.getSizeInBits()/8;
9082   MachineFunction &MF = DAG.getMachineFunction();
9083   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9084   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9085   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9086                                StackSlot,
9087                                MachinePointerInfo::getFixedStack(SSFI),
9088                                false, false, 0);
9089   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9090 }
9091
9092 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9093                                      SDValue StackSlot,
9094                                      SelectionDAG &DAG) const {
9095   // Build the FILD
9096   SDLoc DL(Op);
9097   SDVTList Tys;
9098   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9099   if (useSSE)
9100     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9101   else
9102     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9103
9104   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9105
9106   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9107   MachineMemOperand *MMO;
9108   if (FI) {
9109     int SSFI = FI->getIndex();
9110     MMO =
9111       DAG.getMachineFunction()
9112       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9113                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9114   } else {
9115     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9116     StackSlot = StackSlot.getOperand(1);
9117   }
9118   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9119   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9120                                            X86ISD::FILD, DL,
9121                                            Tys, Ops, SrcVT, MMO);
9122
9123   if (useSSE) {
9124     Chain = Result.getValue(1);
9125     SDValue InFlag = Result.getValue(2);
9126
9127     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9128     // shouldn't be necessary except that RFP cannot be live across
9129     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9130     MachineFunction &MF = DAG.getMachineFunction();
9131     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9132     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9133     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9134     Tys = DAG.getVTList(MVT::Other);
9135     SDValue Ops[] = {
9136       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9137     };
9138     MachineMemOperand *MMO =
9139       DAG.getMachineFunction()
9140       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9141                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9142
9143     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9144                                     Ops, Op.getValueType(), MMO);
9145     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9146                          MachinePointerInfo::getFixedStack(SSFI),
9147                          false, false, false, 0);
9148   }
9149
9150   return Result;
9151 }
9152
9153 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9154 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9155                                                SelectionDAG &DAG) const {
9156   // This algorithm is not obvious. Here it is what we're trying to output:
9157   /*
9158      movq       %rax,  %xmm0
9159      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9160      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9161      #ifdef __SSE3__
9162        haddpd   %xmm0, %xmm0
9163      #else
9164        pshufd   $0x4e, %xmm0, %xmm1
9165        addpd    %xmm1, %xmm0
9166      #endif
9167   */
9168
9169   SDLoc dl(Op);
9170   LLVMContext *Context = DAG.getContext();
9171
9172   // Build some magic constants.
9173   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9174   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9175   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9176
9177   SmallVector<Constant*,2> CV1;
9178   CV1.push_back(
9179     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9180                                       APInt(64, 0x4330000000000000ULL))));
9181   CV1.push_back(
9182     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9183                                       APInt(64, 0x4530000000000000ULL))));
9184   Constant *C1 = ConstantVector::get(CV1);
9185   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9186
9187   // Load the 64-bit value into an XMM register.
9188   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9189                             Op.getOperand(0));
9190   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9191                               MachinePointerInfo::getConstantPool(),
9192                               false, false, false, 16);
9193   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9194                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9195                               CLod0);
9196
9197   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9198                               MachinePointerInfo::getConstantPool(),
9199                               false, false, false, 16);
9200   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9201   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9202   SDValue Result;
9203
9204   if (Subtarget->hasSSE3()) {
9205     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9206     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9207   } else {
9208     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9209     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9210                                            S2F, 0x4E, DAG);
9211     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9212                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9213                          Sub);
9214   }
9215
9216   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9217                      DAG.getIntPtrConstant(0));
9218 }
9219
9220 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9221 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9222                                                SelectionDAG &DAG) const {
9223   SDLoc dl(Op);
9224   // FP constant to bias correct the final result.
9225   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9226                                    MVT::f64);
9227
9228   // Load the 32-bit value into an XMM register.
9229   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9230                              Op.getOperand(0));
9231
9232   // Zero out the upper parts of the register.
9233   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9234
9235   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9236                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9237                      DAG.getIntPtrConstant(0));
9238
9239   // Or the load with the bias.
9240   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9241                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9242                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9243                                                    MVT::v2f64, Load)),
9244                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9245                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9246                                                    MVT::v2f64, Bias)));
9247   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9248                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9249                    DAG.getIntPtrConstant(0));
9250
9251   // Subtract the bias.
9252   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9253
9254   // Handle final rounding.
9255   EVT DestVT = Op.getValueType();
9256
9257   if (DestVT.bitsLT(MVT::f64))
9258     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9259                        DAG.getIntPtrConstant(0));
9260   if (DestVT.bitsGT(MVT::f64))
9261     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9262
9263   // Handle final rounding.
9264   return Sub;
9265 }
9266
9267 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9268                                                SelectionDAG &DAG) const {
9269   SDValue N0 = Op.getOperand(0);
9270   MVT SVT = N0.getSimpleValueType();
9271   SDLoc dl(Op);
9272
9273   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9274           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9275          "Custom UINT_TO_FP is not supported!");
9276
9277   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9278   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9279                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9280 }
9281
9282 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9283                                            SelectionDAG &DAG) const {
9284   SDValue N0 = Op.getOperand(0);
9285   SDLoc dl(Op);
9286
9287   if (Op.getValueType().isVector())
9288     return lowerUINT_TO_FP_vec(Op, DAG);
9289
9290   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9291   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9292   // the optimization here.
9293   if (DAG.SignBitIsZero(N0))
9294     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9295
9296   MVT SrcVT = N0.getSimpleValueType();
9297   MVT DstVT = Op.getSimpleValueType();
9298   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9299     return LowerUINT_TO_FP_i64(Op, DAG);
9300   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9301     return LowerUINT_TO_FP_i32(Op, DAG);
9302   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9303     return SDValue();
9304
9305   // Make a 64-bit buffer, and use it to build an FILD.
9306   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9307   if (SrcVT == MVT::i32) {
9308     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9309     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9310                                      getPointerTy(), StackSlot, WordOff);
9311     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9312                                   StackSlot, MachinePointerInfo(),
9313                                   false, false, 0);
9314     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9315                                   OffsetSlot, MachinePointerInfo(),
9316                                   false, false, 0);
9317     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9318     return Fild;
9319   }
9320
9321   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9322   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9323                                StackSlot, MachinePointerInfo(),
9324                                false, false, 0);
9325   // For i64 source, we need to add the appropriate power of 2 if the input
9326   // was negative.  This is the same as the optimization in
9327   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9328   // we must be careful to do the computation in x87 extended precision, not
9329   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9330   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9331   MachineMemOperand *MMO =
9332     DAG.getMachineFunction()
9333     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9334                           MachineMemOperand::MOLoad, 8, 8);
9335
9336   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9337   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9338   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9339                                          MVT::i64, MMO);
9340
9341   APInt FF(32, 0x5F800000ULL);
9342
9343   // Check whether the sign bit is set.
9344   SDValue SignSet = DAG.getSetCC(dl,
9345                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9346                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9347                                  ISD::SETLT);
9348
9349   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9350   SDValue FudgePtr = DAG.getConstantPool(
9351                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9352                                          getPointerTy());
9353
9354   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9355   SDValue Zero = DAG.getIntPtrConstant(0);
9356   SDValue Four = DAG.getIntPtrConstant(4);
9357   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9358                                Zero, Four);
9359   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9360
9361   // Load the value out, extending it from f32 to f80.
9362   // FIXME: Avoid the extend by constructing the right constant pool?
9363   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9364                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9365                                  MVT::f32, false, false, 4);
9366   // Extend everything to 80 bits to force it to be done on x87.
9367   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9368   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9369 }
9370
9371 std::pair<SDValue,SDValue>
9372 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9373                                     bool IsSigned, bool IsReplace) const {
9374   SDLoc DL(Op);
9375
9376   EVT DstTy = Op.getValueType();
9377
9378   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9379     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9380     DstTy = MVT::i64;
9381   }
9382
9383   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9384          DstTy.getSimpleVT() >= MVT::i16 &&
9385          "Unknown FP_TO_INT to lower!");
9386
9387   // These are really Legal.
9388   if (DstTy == MVT::i32 &&
9389       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9390     return std::make_pair(SDValue(), SDValue());
9391   if (Subtarget->is64Bit() &&
9392       DstTy == MVT::i64 &&
9393       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9394     return std::make_pair(SDValue(), SDValue());
9395
9396   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9397   // stack slot, or into the FTOL runtime function.
9398   MachineFunction &MF = DAG.getMachineFunction();
9399   unsigned MemSize = DstTy.getSizeInBits()/8;
9400   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9401   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9402
9403   unsigned Opc;
9404   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9405     Opc = X86ISD::WIN_FTOL;
9406   else
9407     switch (DstTy.getSimpleVT().SimpleTy) {
9408     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9409     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9410     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9411     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9412     }
9413
9414   SDValue Chain = DAG.getEntryNode();
9415   SDValue Value = Op.getOperand(0);
9416   EVT TheVT = Op.getOperand(0).getValueType();
9417   // FIXME This causes a redundant load/store if the SSE-class value is already
9418   // in memory, such as if it is on the callstack.
9419   if (isScalarFPTypeInSSEReg(TheVT)) {
9420     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9421     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9422                          MachinePointerInfo::getFixedStack(SSFI),
9423                          false, false, 0);
9424     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9425     SDValue Ops[] = {
9426       Chain, StackSlot, DAG.getValueType(TheVT)
9427     };
9428
9429     MachineMemOperand *MMO =
9430       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9431                               MachineMemOperand::MOLoad, MemSize, MemSize);
9432     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9433     Chain = Value.getValue(1);
9434     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9435     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9436   }
9437
9438   MachineMemOperand *MMO =
9439     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9440                             MachineMemOperand::MOStore, MemSize, MemSize);
9441
9442   if (Opc != X86ISD::WIN_FTOL) {
9443     // Build the FP_TO_INT*_IN_MEM
9444     SDValue Ops[] = { Chain, Value, StackSlot };
9445     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9446                                            Ops, DstTy, MMO);
9447     return std::make_pair(FIST, StackSlot);
9448   } else {
9449     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9450       DAG.getVTList(MVT::Other, MVT::Glue),
9451       Chain, Value);
9452     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9453       MVT::i32, ftol.getValue(1));
9454     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9455       MVT::i32, eax.getValue(2));
9456     SDValue Ops[] = { eax, edx };
9457     SDValue pair = IsReplace
9458       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9459       : DAG.getMergeValues(Ops, DL);
9460     return std::make_pair(pair, SDValue());
9461   }
9462 }
9463
9464 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9465                               const X86Subtarget *Subtarget) {
9466   MVT VT = Op->getSimpleValueType(0);
9467   SDValue In = Op->getOperand(0);
9468   MVT InVT = In.getSimpleValueType();
9469   SDLoc dl(Op);
9470
9471   // Optimize vectors in AVX mode:
9472   //
9473   //   v8i16 -> v8i32
9474   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9475   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9476   //   Concat upper and lower parts.
9477   //
9478   //   v4i32 -> v4i64
9479   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9480   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9481   //   Concat upper and lower parts.
9482   //
9483
9484   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9485       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9486       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9487     return SDValue();
9488
9489   if (Subtarget->hasInt256())
9490     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9491
9492   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9493   SDValue Undef = DAG.getUNDEF(InVT);
9494   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9495   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9496   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9497
9498   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9499                              VT.getVectorNumElements()/2);
9500
9501   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9502   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9503
9504   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9505 }
9506
9507 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9508                                         SelectionDAG &DAG) {
9509   MVT VT = Op->getSimpleValueType(0);
9510   SDValue In = Op->getOperand(0);
9511   MVT InVT = In.getSimpleValueType();
9512   SDLoc DL(Op);
9513   unsigned int NumElts = VT.getVectorNumElements();
9514   if (NumElts != 8 && NumElts != 16)
9515     return SDValue();
9516
9517   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9518     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9519
9520   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9522   // Now we have only mask extension
9523   assert(InVT.getVectorElementType() == MVT::i1);
9524   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9525   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9526   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9527   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9528   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9529                            MachinePointerInfo::getConstantPool(),
9530                            false, false, false, Alignment);
9531
9532   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9533   if (VT.is512BitVector())
9534     return Brcst;
9535   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9536 }
9537
9538 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9539                                SelectionDAG &DAG) {
9540   if (Subtarget->hasFp256()) {
9541     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9542     if (Res.getNode())
9543       return Res;
9544   }
9545
9546   return SDValue();
9547 }
9548
9549 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9550                                 SelectionDAG &DAG) {
9551   SDLoc DL(Op);
9552   MVT VT = Op.getSimpleValueType();
9553   SDValue In = Op.getOperand(0);
9554   MVT SVT = In.getSimpleValueType();
9555
9556   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9557     return LowerZERO_EXTEND_AVX512(Op, DAG);
9558
9559   if (Subtarget->hasFp256()) {
9560     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9561     if (Res.getNode())
9562       return Res;
9563   }
9564
9565   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9566          VT.getVectorNumElements() != SVT.getVectorNumElements());
9567   return SDValue();
9568 }
9569
9570 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9571   SDLoc DL(Op);
9572   MVT VT = Op.getSimpleValueType();
9573   SDValue In = Op.getOperand(0);
9574   MVT InVT = In.getSimpleValueType();
9575
9576   if (VT == MVT::i1) {
9577     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9578            "Invalid scalar TRUNCATE operation");
9579     if (InVT == MVT::i32)
9580       return SDValue();
9581     if (InVT.getSizeInBits() == 64)
9582       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9583     else if (InVT.getSizeInBits() < 32)
9584       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9585     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9586   }
9587   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9588          "Invalid TRUNCATE operation");
9589
9590   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9591     if (VT.getVectorElementType().getSizeInBits() >=8)
9592       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9593
9594     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9595     unsigned NumElts = InVT.getVectorNumElements();
9596     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9597     if (InVT.getSizeInBits() < 512) {
9598       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9599       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9600       InVT = ExtVT;
9601     }
9602     
9603     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9604     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9605     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9606     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9607     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9608                            MachinePointerInfo::getConstantPool(),
9609                            false, false, false, Alignment);
9610     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9611     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9612     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9613   }
9614
9615   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9616     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9617     if (Subtarget->hasInt256()) {
9618       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9619       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9620       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9621                                 ShufMask);
9622       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9623                          DAG.getIntPtrConstant(0));
9624     }
9625
9626     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9627                                DAG.getIntPtrConstant(0));
9628     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9629                                DAG.getIntPtrConstant(2));
9630     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9631     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9632     static const int ShufMask[] = {0, 2, 4, 6};
9633     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9634   }
9635
9636   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9637     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9638     if (Subtarget->hasInt256()) {
9639       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9640
9641       SmallVector<SDValue,32> pshufbMask;
9642       for (unsigned i = 0; i < 2; ++i) {
9643         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9644         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9645         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9646         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9647         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9648         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9649         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9650         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9651         for (unsigned j = 0; j < 8; ++j)
9652           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9653       }
9654       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9655       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9656       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9657
9658       static const int ShufMask[] = {0,  2,  -1,  -1};
9659       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9660                                 &ShufMask[0]);
9661       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9662                        DAG.getIntPtrConstant(0));
9663       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9664     }
9665
9666     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9667                                DAG.getIntPtrConstant(0));
9668
9669     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9670                                DAG.getIntPtrConstant(4));
9671
9672     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9673     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9674
9675     // The PSHUFB mask:
9676     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9677                                    -1, -1, -1, -1, -1, -1, -1, -1};
9678
9679     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9680     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9681     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9682
9683     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9684     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9685
9686     // The MOVLHPS Mask:
9687     static const int ShufMask2[] = {0, 1, 4, 5};
9688     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9689     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9690   }
9691
9692   // Handle truncation of V256 to V128 using shuffles.
9693   if (!VT.is128BitVector() || !InVT.is256BitVector())
9694     return SDValue();
9695
9696   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9697
9698   unsigned NumElems = VT.getVectorNumElements();
9699   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9700
9701   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9702   // Prepare truncation shuffle mask
9703   for (unsigned i = 0; i != NumElems; ++i)
9704     MaskVec[i] = i * 2;
9705   SDValue V = DAG.getVectorShuffle(NVT, DL,
9706                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9707                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9708   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9709                      DAG.getIntPtrConstant(0));
9710 }
9711
9712 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9713                                            SelectionDAG &DAG) const {
9714   assert(!Op.getSimpleValueType().isVector());
9715
9716   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9717     /*IsSigned=*/ true, /*IsReplace=*/ false);
9718   SDValue FIST = Vals.first, StackSlot = Vals.second;
9719   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9720   if (!FIST.getNode()) return Op;
9721
9722   if (StackSlot.getNode())
9723     // Load the result.
9724     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9725                        FIST, StackSlot, MachinePointerInfo(),
9726                        false, false, false, 0);
9727
9728   // The node is the result.
9729   return FIST;
9730 }
9731
9732 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9733                                            SelectionDAG &DAG) const {
9734   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9735     /*IsSigned=*/ false, /*IsReplace=*/ false);
9736   SDValue FIST = Vals.first, StackSlot = Vals.second;
9737   assert(FIST.getNode() && "Unexpected failure");
9738
9739   if (StackSlot.getNode())
9740     // Load the result.
9741     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9742                        FIST, StackSlot, MachinePointerInfo(),
9743                        false, false, false, 0);
9744
9745   // The node is the result.
9746   return FIST;
9747 }
9748
9749 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9750   SDLoc DL(Op);
9751   MVT VT = Op.getSimpleValueType();
9752   SDValue In = Op.getOperand(0);
9753   MVT SVT = In.getSimpleValueType();
9754
9755   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9756
9757   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9758                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9759                                  In, DAG.getUNDEF(SVT)));
9760 }
9761
9762 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9763   LLVMContext *Context = DAG.getContext();
9764   SDLoc dl(Op);
9765   MVT VT = Op.getSimpleValueType();
9766   MVT EltVT = VT;
9767   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9768   if (VT.isVector()) {
9769     EltVT = VT.getVectorElementType();
9770     NumElts = VT.getVectorNumElements();
9771   }
9772   Constant *C;
9773   if (EltVT == MVT::f64)
9774     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9775                                           APInt(64, ~(1ULL << 63))));
9776   else
9777     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9778                                           APInt(32, ~(1U << 31))));
9779   C = ConstantVector::getSplat(NumElts, C);
9780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9781   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9782   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9783   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9784                              MachinePointerInfo::getConstantPool(),
9785                              false, false, false, Alignment);
9786   if (VT.isVector()) {
9787     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9788     return DAG.getNode(ISD::BITCAST, dl, VT,
9789                        DAG.getNode(ISD::AND, dl, ANDVT,
9790                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9791                                                Op.getOperand(0)),
9792                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9793   }
9794   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9795 }
9796
9797 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9798   LLVMContext *Context = DAG.getContext();
9799   SDLoc dl(Op);
9800   MVT VT = Op.getSimpleValueType();
9801   MVT EltVT = VT;
9802   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9803   if (VT.isVector()) {
9804     EltVT = VT.getVectorElementType();
9805     NumElts = VT.getVectorNumElements();
9806   }
9807   Constant *C;
9808   if (EltVT == MVT::f64)
9809     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9810                                           APInt(64, 1ULL << 63)));
9811   else
9812     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9813                                           APInt(32, 1U << 31)));
9814   C = ConstantVector::getSplat(NumElts, C);
9815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9816   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9817   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9818   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9819                              MachinePointerInfo::getConstantPool(),
9820                              false, false, false, Alignment);
9821   if (VT.isVector()) {
9822     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9823     return DAG.getNode(ISD::BITCAST, dl, VT,
9824                        DAG.getNode(ISD::XOR, dl, XORVT,
9825                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9826                                                Op.getOperand(0)),
9827                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9828   }
9829
9830   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9831 }
9832
9833 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9834   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9835   LLVMContext *Context = DAG.getContext();
9836   SDValue Op0 = Op.getOperand(0);
9837   SDValue Op1 = Op.getOperand(1);
9838   SDLoc dl(Op);
9839   MVT VT = Op.getSimpleValueType();
9840   MVT SrcVT = Op1.getSimpleValueType();
9841
9842   // If second operand is smaller, extend it first.
9843   if (SrcVT.bitsLT(VT)) {
9844     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9845     SrcVT = VT;
9846   }
9847   // And if it is bigger, shrink it first.
9848   if (SrcVT.bitsGT(VT)) {
9849     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9850     SrcVT = VT;
9851   }
9852
9853   // At this point the operands and the result should have the same
9854   // type, and that won't be f80 since that is not custom lowered.
9855
9856   // First get the sign bit of second operand.
9857   SmallVector<Constant*,4> CV;
9858   if (SrcVT == MVT::f64) {
9859     const fltSemantics &Sem = APFloat::IEEEdouble;
9860     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9861     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9862   } else {
9863     const fltSemantics &Sem = APFloat::IEEEsingle;
9864     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9865     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9866     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9867     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9868   }
9869   Constant *C = ConstantVector::get(CV);
9870   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9871   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9872                               MachinePointerInfo::getConstantPool(),
9873                               false, false, false, 16);
9874   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9875
9876   // Shift sign bit right or left if the two operands have different types.
9877   if (SrcVT.bitsGT(VT)) {
9878     // Op0 is MVT::f32, Op1 is MVT::f64.
9879     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9880     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9881                           DAG.getConstant(32, MVT::i32));
9882     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9883     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9884                           DAG.getIntPtrConstant(0));
9885   }
9886
9887   // Clear first operand sign bit.
9888   CV.clear();
9889   if (VT == MVT::f64) {
9890     const fltSemantics &Sem = APFloat::IEEEdouble;
9891     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9892                                                    APInt(64, ~(1ULL << 63)))));
9893     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9894   } else {
9895     const fltSemantics &Sem = APFloat::IEEEsingle;
9896     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9897                                                    APInt(32, ~(1U << 31)))));
9898     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9899     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9900     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9901   }
9902   C = ConstantVector::get(CV);
9903   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9904   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9905                               MachinePointerInfo::getConstantPool(),
9906                               false, false, false, 16);
9907   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9908
9909   // Or the value with the sign bit.
9910   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9911 }
9912
9913 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9914   SDValue N0 = Op.getOperand(0);
9915   SDLoc dl(Op);
9916   MVT VT = Op.getSimpleValueType();
9917
9918   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9919   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9920                                   DAG.getConstant(1, VT));
9921   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9922 }
9923
9924 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9925 //
9926 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9927                                       SelectionDAG &DAG) {
9928   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9929
9930   if (!Subtarget->hasSSE41())
9931     return SDValue();
9932
9933   if (!Op->hasOneUse())
9934     return SDValue();
9935
9936   SDNode *N = Op.getNode();
9937   SDLoc DL(N);
9938
9939   SmallVector<SDValue, 8> Opnds;
9940   DenseMap<SDValue, unsigned> VecInMap;
9941   SmallVector<SDValue, 8> VecIns;
9942   EVT VT = MVT::Other;
9943
9944   // Recognize a special case where a vector is casted into wide integer to
9945   // test all 0s.
9946   Opnds.push_back(N->getOperand(0));
9947   Opnds.push_back(N->getOperand(1));
9948
9949   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9950     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9951     // BFS traverse all OR'd operands.
9952     if (I->getOpcode() == ISD::OR) {
9953       Opnds.push_back(I->getOperand(0));
9954       Opnds.push_back(I->getOperand(1));
9955       // Re-evaluate the number of nodes to be traversed.
9956       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9957       continue;
9958     }
9959
9960     // Quit if a non-EXTRACT_VECTOR_ELT
9961     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9962       return SDValue();
9963
9964     // Quit if without a constant index.
9965     SDValue Idx = I->getOperand(1);
9966     if (!isa<ConstantSDNode>(Idx))
9967       return SDValue();
9968
9969     SDValue ExtractedFromVec = I->getOperand(0);
9970     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9971     if (M == VecInMap.end()) {
9972       VT = ExtractedFromVec.getValueType();
9973       // Quit if not 128/256-bit vector.
9974       if (!VT.is128BitVector() && !VT.is256BitVector())
9975         return SDValue();
9976       // Quit if not the same type.
9977       if (VecInMap.begin() != VecInMap.end() &&
9978           VT != VecInMap.begin()->first.getValueType())
9979         return SDValue();
9980       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9981       VecIns.push_back(ExtractedFromVec);
9982     }
9983     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9984   }
9985
9986   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9987          "Not extracted from 128-/256-bit vector.");
9988
9989   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9990
9991   for (DenseMap<SDValue, unsigned>::const_iterator
9992         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9993     // Quit if not all elements are used.
9994     if (I->second != FullMask)
9995       return SDValue();
9996   }
9997
9998   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9999
10000   // Cast all vectors into TestVT for PTEST.
10001   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10002     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10003
10004   // If more than one full vectors are evaluated, OR them first before PTEST.
10005   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10006     // Each iteration will OR 2 nodes and append the result until there is only
10007     // 1 node left, i.e. the final OR'd value of all vectors.
10008     SDValue LHS = VecIns[Slot];
10009     SDValue RHS = VecIns[Slot + 1];
10010     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10011   }
10012
10013   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10014                      VecIns.back(), VecIns.back());
10015 }
10016
10017 /// \brief return true if \c Op has a use that doesn't just read flags.
10018 static bool hasNonFlagsUse(SDValue Op) {
10019   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10020        ++UI) {
10021     SDNode *User = *UI;
10022     unsigned UOpNo = UI.getOperandNo();
10023     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10024       // Look pass truncate.
10025       UOpNo = User->use_begin().getOperandNo();
10026       User = *User->use_begin();
10027     }
10028
10029     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10030         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10031       return true;
10032   }
10033   return false;
10034 }
10035
10036 /// Emit nodes that will be selected as "test Op0,Op0", or something
10037 /// equivalent.
10038 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10039                                     SelectionDAG &DAG) const {
10040   if (Op.getValueType() == MVT::i1)
10041     // KORTEST instruction should be selected
10042     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10043                        DAG.getConstant(0, Op.getValueType()));
10044
10045   // CF and OF aren't always set the way we want. Determine which
10046   // of these we need.
10047   bool NeedCF = false;
10048   bool NeedOF = false;
10049   switch (X86CC) {
10050   default: break;
10051   case X86::COND_A: case X86::COND_AE:
10052   case X86::COND_B: case X86::COND_BE:
10053     NeedCF = true;
10054     break;
10055   case X86::COND_G: case X86::COND_GE:
10056   case X86::COND_L: case X86::COND_LE:
10057   case X86::COND_O: case X86::COND_NO:
10058     NeedOF = true;
10059     break;
10060   }
10061   // See if we can use the EFLAGS value from the operand instead of
10062   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10063   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10064   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10065     // Emit a CMP with 0, which is the TEST pattern.
10066     //if (Op.getValueType() == MVT::i1)
10067     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10068     //                     DAG.getConstant(0, MVT::i1));
10069     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10070                        DAG.getConstant(0, Op.getValueType()));
10071   }
10072   unsigned Opcode = 0;
10073   unsigned NumOperands = 0;
10074
10075   // Truncate operations may prevent the merge of the SETCC instruction
10076   // and the arithmetic instruction before it. Attempt to truncate the operands
10077   // of the arithmetic instruction and use a reduced bit-width instruction.
10078   bool NeedTruncation = false;
10079   SDValue ArithOp = Op;
10080   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10081     SDValue Arith = Op->getOperand(0);
10082     // Both the trunc and the arithmetic op need to have one user each.
10083     if (Arith->hasOneUse())
10084       switch (Arith.getOpcode()) {
10085         default: break;
10086         case ISD::ADD:
10087         case ISD::SUB:
10088         case ISD::AND:
10089         case ISD::OR:
10090         case ISD::XOR: {
10091           NeedTruncation = true;
10092           ArithOp = Arith;
10093         }
10094       }
10095   }
10096
10097   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10098   // which may be the result of a CAST.  We use the variable 'Op', which is the
10099   // non-casted variable when we check for possible users.
10100   switch (ArithOp.getOpcode()) {
10101   case ISD::ADD:
10102     // Due to an isel shortcoming, be conservative if this add is likely to be
10103     // selected as part of a load-modify-store instruction. When the root node
10104     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10105     // uses of other nodes in the match, such as the ADD in this case. This
10106     // leads to the ADD being left around and reselected, with the result being
10107     // two adds in the output.  Alas, even if none our users are stores, that
10108     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10109     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10110     // climbing the DAG back to the root, and it doesn't seem to be worth the
10111     // effort.
10112     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10113          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10114       if (UI->getOpcode() != ISD::CopyToReg &&
10115           UI->getOpcode() != ISD::SETCC &&
10116           UI->getOpcode() != ISD::STORE)
10117         goto default_case;
10118
10119     if (ConstantSDNode *C =
10120         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10121       // An add of one will be selected as an INC.
10122       if (C->getAPIntValue() == 1) {
10123         Opcode = X86ISD::INC;
10124         NumOperands = 1;
10125         break;
10126       }
10127
10128       // An add of negative one (subtract of one) will be selected as a DEC.
10129       if (C->getAPIntValue().isAllOnesValue()) {
10130         Opcode = X86ISD::DEC;
10131         NumOperands = 1;
10132         break;
10133       }
10134     }
10135
10136     // Otherwise use a regular EFLAGS-setting add.
10137     Opcode = X86ISD::ADD;
10138     NumOperands = 2;
10139     break;
10140   case ISD::SHL:
10141   case ISD::SRL:
10142     // If we have a constant logical shift that's only used in a comparison
10143     // against zero turn it into an equivalent AND. This allows turning it into
10144     // a TEST instruction later.
10145     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
10146         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10147       EVT VT = Op.getValueType();
10148       unsigned BitWidth = VT.getSizeInBits();
10149       unsigned ShAmt = Op->getConstantOperandVal(1);
10150       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10151         break;
10152       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10153                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10154                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10155       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10156         break;
10157       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10158                                 DAG.getConstant(Mask, VT));
10159       DAG.ReplaceAllUsesWith(Op, New);
10160       Op = New;
10161     }
10162     break;
10163
10164   case ISD::AND:
10165     // If the primary and result isn't used, don't bother using X86ISD::AND,
10166     // because a TEST instruction will be better.
10167     if (!hasNonFlagsUse(Op))
10168       break;
10169     // FALL THROUGH
10170   case ISD::SUB:
10171   case ISD::OR:
10172   case ISD::XOR:
10173     // Due to the ISEL shortcoming noted above, be conservative if this op is
10174     // likely to be selected as part of a load-modify-store instruction.
10175     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10176            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10177       if (UI->getOpcode() == ISD::STORE)
10178         goto default_case;
10179
10180     // Otherwise use a regular EFLAGS-setting instruction.
10181     switch (ArithOp.getOpcode()) {
10182     default: llvm_unreachable("unexpected operator!");
10183     case ISD::SUB: Opcode = X86ISD::SUB; break;
10184     case ISD::XOR: Opcode = X86ISD::XOR; break;
10185     case ISD::AND: Opcode = X86ISD::AND; break;
10186     case ISD::OR: {
10187       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10188         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10189         if (EFLAGS.getNode())
10190           return EFLAGS;
10191       }
10192       Opcode = X86ISD::OR;
10193       break;
10194     }
10195     }
10196
10197     NumOperands = 2;
10198     break;
10199   case X86ISD::ADD:
10200   case X86ISD::SUB:
10201   case X86ISD::INC:
10202   case X86ISD::DEC:
10203   case X86ISD::OR:
10204   case X86ISD::XOR:
10205   case X86ISD::AND:
10206     return SDValue(Op.getNode(), 1);
10207   default:
10208   default_case:
10209     break;
10210   }
10211
10212   // If we found that truncation is beneficial, perform the truncation and
10213   // update 'Op'.
10214   if (NeedTruncation) {
10215     EVT VT = Op.getValueType();
10216     SDValue WideVal = Op->getOperand(0);
10217     EVT WideVT = WideVal.getValueType();
10218     unsigned ConvertedOp = 0;
10219     // Use a target machine opcode to prevent further DAGCombine
10220     // optimizations that may separate the arithmetic operations
10221     // from the setcc node.
10222     switch (WideVal.getOpcode()) {
10223       default: break;
10224       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10225       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10226       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10227       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10228       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10229     }
10230
10231     if (ConvertedOp) {
10232       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10233       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10234         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10235         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10236         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10237       }
10238     }
10239   }
10240
10241   if (Opcode == 0)
10242     // Emit a CMP with 0, which is the TEST pattern.
10243     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10244                        DAG.getConstant(0, Op.getValueType()));
10245
10246   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10247   SmallVector<SDValue, 4> Ops;
10248   for (unsigned i = 0; i != NumOperands; ++i)
10249     Ops.push_back(Op.getOperand(i));
10250
10251   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10252   DAG.ReplaceAllUsesWith(Op, New);
10253   return SDValue(New.getNode(), 1);
10254 }
10255
10256 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10257 /// equivalent.
10258 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10259                                    SDLoc dl, SelectionDAG &DAG) const {
10260   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10261     if (C->getAPIntValue() == 0)
10262       return EmitTest(Op0, X86CC, dl, DAG);
10263
10264      if (Op0.getValueType() == MVT::i1)
10265        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10266   }
10267  
10268   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10269        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10270     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10271     // This avoids subregister aliasing issues. Keep the smaller reference 
10272     // if we're optimizing for size, however, as that'll allow better folding 
10273     // of memory operations.
10274     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10275         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10276              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10277         !Subtarget->isAtom()) {
10278       unsigned ExtendOp =
10279           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10280       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10281       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10282     }
10283     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10284     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10285     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10286                               Op0, Op1);
10287     return SDValue(Sub.getNode(), 1);
10288   }
10289   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10290 }
10291
10292 /// Convert a comparison if required by the subtarget.
10293 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10294                                                  SelectionDAG &DAG) const {
10295   // If the subtarget does not support the FUCOMI instruction, floating-point
10296   // comparisons have to be converted.
10297   if (Subtarget->hasCMov() ||
10298       Cmp.getOpcode() != X86ISD::CMP ||
10299       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10300       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10301     return Cmp;
10302
10303   // The instruction selector will select an FUCOM instruction instead of
10304   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10305   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10306   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10307   SDLoc dl(Cmp);
10308   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10309   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10310   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10311                             DAG.getConstant(8, MVT::i8));
10312   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10313   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10314 }
10315
10316 static bool isAllOnes(SDValue V) {
10317   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10318   return C && C->isAllOnesValue();
10319 }
10320
10321 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10322 /// if it's possible.
10323 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10324                                      SDLoc dl, SelectionDAG &DAG) const {
10325   SDValue Op0 = And.getOperand(0);
10326   SDValue Op1 = And.getOperand(1);
10327   if (Op0.getOpcode() == ISD::TRUNCATE)
10328     Op0 = Op0.getOperand(0);
10329   if (Op1.getOpcode() == ISD::TRUNCATE)
10330     Op1 = Op1.getOperand(0);
10331
10332   SDValue LHS, RHS;
10333   if (Op1.getOpcode() == ISD::SHL)
10334     std::swap(Op0, Op1);
10335   if (Op0.getOpcode() == ISD::SHL) {
10336     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10337       if (And00C->getZExtValue() == 1) {
10338         // If we looked past a truncate, check that it's only truncating away
10339         // known zeros.
10340         unsigned BitWidth = Op0.getValueSizeInBits();
10341         unsigned AndBitWidth = And.getValueSizeInBits();
10342         if (BitWidth > AndBitWidth) {
10343           APInt Zeros, Ones;
10344           DAG.computeKnownBits(Op0, Zeros, Ones);
10345           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10346             return SDValue();
10347         }
10348         LHS = Op1;
10349         RHS = Op0.getOperand(1);
10350       }
10351   } else if (Op1.getOpcode() == ISD::Constant) {
10352     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10353     uint64_t AndRHSVal = AndRHS->getZExtValue();
10354     SDValue AndLHS = Op0;
10355
10356     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10357       LHS = AndLHS.getOperand(0);
10358       RHS = AndLHS.getOperand(1);
10359     }
10360
10361     // Use BT if the immediate can't be encoded in a TEST instruction.
10362     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10363       LHS = AndLHS;
10364       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10365     }
10366   }
10367
10368   if (LHS.getNode()) {
10369     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10370     // instruction.  Since the shift amount is in-range-or-undefined, we know
10371     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10372     // the encoding for the i16 version is larger than the i32 version.
10373     // Also promote i16 to i32 for performance / code size reason.
10374     if (LHS.getValueType() == MVT::i8 ||
10375         LHS.getValueType() == MVT::i16)
10376       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10377
10378     // If the operand types disagree, extend the shift amount to match.  Since
10379     // BT ignores high bits (like shifts) we can use anyextend.
10380     if (LHS.getValueType() != RHS.getValueType())
10381       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10382
10383     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10384     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10385     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10386                        DAG.getConstant(Cond, MVT::i8), BT);
10387   }
10388
10389   return SDValue();
10390 }
10391
10392 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10393 /// mask CMPs.
10394 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10395                               SDValue &Op1) {
10396   unsigned SSECC;
10397   bool Swap = false;
10398
10399   // SSE Condition code mapping:
10400   //  0 - EQ
10401   //  1 - LT
10402   //  2 - LE
10403   //  3 - UNORD
10404   //  4 - NEQ
10405   //  5 - NLT
10406   //  6 - NLE
10407   //  7 - ORD
10408   switch (SetCCOpcode) {
10409   default: llvm_unreachable("Unexpected SETCC condition");
10410   case ISD::SETOEQ:
10411   case ISD::SETEQ:  SSECC = 0; break;
10412   case ISD::SETOGT:
10413   case ISD::SETGT:  Swap = true; // Fallthrough
10414   case ISD::SETLT:
10415   case ISD::SETOLT: SSECC = 1; break;
10416   case ISD::SETOGE:
10417   case ISD::SETGE:  Swap = true; // Fallthrough
10418   case ISD::SETLE:
10419   case ISD::SETOLE: SSECC = 2; break;
10420   case ISD::SETUO:  SSECC = 3; break;
10421   case ISD::SETUNE:
10422   case ISD::SETNE:  SSECC = 4; break;
10423   case ISD::SETULE: Swap = true; // Fallthrough
10424   case ISD::SETUGE: SSECC = 5; break;
10425   case ISD::SETULT: Swap = true; // Fallthrough
10426   case ISD::SETUGT: SSECC = 6; break;
10427   case ISD::SETO:   SSECC = 7; break;
10428   case ISD::SETUEQ:
10429   case ISD::SETONE: SSECC = 8; break;
10430   }
10431   if (Swap)
10432     std::swap(Op0, Op1);
10433
10434   return SSECC;
10435 }
10436
10437 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10438 // ones, and then concatenate the result back.
10439 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10440   MVT VT = Op.getSimpleValueType();
10441
10442   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10443          "Unsupported value type for operation");
10444
10445   unsigned NumElems = VT.getVectorNumElements();
10446   SDLoc dl(Op);
10447   SDValue CC = Op.getOperand(2);
10448
10449   // Extract the LHS vectors
10450   SDValue LHS = Op.getOperand(0);
10451   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10452   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10453
10454   // Extract the RHS vectors
10455   SDValue RHS = Op.getOperand(1);
10456   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10457   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10458
10459   // Issue the operation on the smaller types and concatenate the result back
10460   MVT EltVT = VT.getVectorElementType();
10461   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10462   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10463                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10464                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10465 }
10466
10467 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10468                                      const X86Subtarget *Subtarget) {
10469   SDValue Op0 = Op.getOperand(0);
10470   SDValue Op1 = Op.getOperand(1);
10471   SDValue CC = Op.getOperand(2);
10472   MVT VT = Op.getSimpleValueType();
10473   SDLoc dl(Op);
10474
10475   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10476          Op.getValueType().getScalarType() == MVT::i1 &&
10477          "Cannot set masked compare for this operation");
10478
10479   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10480   unsigned  Opc = 0;
10481   bool Unsigned = false;
10482   bool Swap = false;
10483   unsigned SSECC;
10484   switch (SetCCOpcode) {
10485   default: llvm_unreachable("Unexpected SETCC condition");
10486   case ISD::SETNE:  SSECC = 4; break;
10487   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10488   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10489   case ISD::SETLT:  Swap = true; //fall-through
10490   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10491   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10492   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10493   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10494   case ISD::SETULE: Unsigned = true; //fall-through
10495   case ISD::SETLE:  SSECC = 2; break;
10496   }
10497
10498   if (Swap)
10499     std::swap(Op0, Op1);
10500   if (Opc)
10501     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10502   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10503   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10504                      DAG.getConstant(SSECC, MVT::i8));
10505 }
10506
10507 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10508 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10509 /// return an empty value.
10510 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10511 {
10512   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10513   if (!BV)
10514     return SDValue();
10515
10516   MVT VT = Op1.getSimpleValueType();
10517   MVT EVT = VT.getVectorElementType();
10518   unsigned n = VT.getVectorNumElements();
10519   SmallVector<SDValue, 8> ULTOp1;
10520
10521   for (unsigned i = 0; i < n; ++i) {
10522     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10523     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10524       return SDValue();
10525
10526     // Avoid underflow.
10527     APInt Val = Elt->getAPIntValue();
10528     if (Val == 0)
10529       return SDValue();
10530
10531     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10532   }
10533
10534   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10535 }
10536
10537 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10538                            SelectionDAG &DAG) {
10539   SDValue Op0 = Op.getOperand(0);
10540   SDValue Op1 = Op.getOperand(1);
10541   SDValue CC = Op.getOperand(2);
10542   MVT VT = Op.getSimpleValueType();
10543   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10544   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10545   SDLoc dl(Op);
10546
10547   if (isFP) {
10548 #ifndef NDEBUG
10549     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10550     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10551 #endif
10552
10553     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10554     unsigned Opc = X86ISD::CMPP;
10555     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10556       assert(VT.getVectorNumElements() <= 16);
10557       Opc = X86ISD::CMPM;
10558     }
10559     // In the two special cases we can't handle, emit two comparisons.
10560     if (SSECC == 8) {
10561       unsigned CC0, CC1;
10562       unsigned CombineOpc;
10563       if (SetCCOpcode == ISD::SETUEQ) {
10564         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10565       } else {
10566         assert(SetCCOpcode == ISD::SETONE);
10567         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10568       }
10569
10570       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10571                                  DAG.getConstant(CC0, MVT::i8));
10572       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10573                                  DAG.getConstant(CC1, MVT::i8));
10574       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10575     }
10576     // Handle all other FP comparisons here.
10577     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10578                        DAG.getConstant(SSECC, MVT::i8));
10579   }
10580
10581   // Break 256-bit integer vector compare into smaller ones.
10582   if (VT.is256BitVector() && !Subtarget->hasInt256())
10583     return Lower256IntVSETCC(Op, DAG);
10584
10585   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10586   EVT OpVT = Op1.getValueType();
10587   if (Subtarget->hasAVX512()) {
10588     if (Op1.getValueType().is512BitVector() ||
10589         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10590       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10591
10592     // In AVX-512 architecture setcc returns mask with i1 elements,
10593     // But there is no compare instruction for i8 and i16 elements.
10594     // We are not talking about 512-bit operands in this case, these
10595     // types are illegal.
10596     if (MaskResult &&
10597         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10598          OpVT.getVectorElementType().getSizeInBits() >= 8))
10599       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10600                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10601   }
10602
10603   // We are handling one of the integer comparisons here.  Since SSE only has
10604   // GT and EQ comparisons for integer, swapping operands and multiple
10605   // operations may be required for some comparisons.
10606   unsigned Opc;
10607   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10608   bool Subus = false;
10609
10610   switch (SetCCOpcode) {
10611   default: llvm_unreachable("Unexpected SETCC condition");
10612   case ISD::SETNE:  Invert = true;
10613   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10614   case ISD::SETLT:  Swap = true;
10615   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10616   case ISD::SETGE:  Swap = true;
10617   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10618                     Invert = true; break;
10619   case ISD::SETULT: Swap = true;
10620   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10621                     FlipSigns = true; break;
10622   case ISD::SETUGE: Swap = true;
10623   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10624                     FlipSigns = true; Invert = true; break;
10625   }
10626
10627   // Special case: Use min/max operations for SETULE/SETUGE
10628   MVT VET = VT.getVectorElementType();
10629   bool hasMinMax =
10630        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10631     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10632
10633   if (hasMinMax) {
10634     switch (SetCCOpcode) {
10635     default: break;
10636     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10637     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10638     }
10639
10640     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10641   }
10642
10643   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10644   if (!MinMax && hasSubus) {
10645     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10646     // Op0 u<= Op1:
10647     //   t = psubus Op0, Op1
10648     //   pcmpeq t, <0..0>
10649     switch (SetCCOpcode) {
10650     default: break;
10651     case ISD::SETULT: {
10652       // If the comparison is against a constant we can turn this into a
10653       // setule.  With psubus, setule does not require a swap.  This is
10654       // beneficial because the constant in the register is no longer
10655       // destructed as the destination so it can be hoisted out of a loop.
10656       // Only do this pre-AVX since vpcmp* is no longer destructive.
10657       if (Subtarget->hasAVX())
10658         break;
10659       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10660       if (ULEOp1.getNode()) {
10661         Op1 = ULEOp1;
10662         Subus = true; Invert = false; Swap = false;
10663       }
10664       break;
10665     }
10666     // Psubus is better than flip-sign because it requires no inversion.
10667     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10668     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10669     }
10670
10671     if (Subus) {
10672       Opc = X86ISD::SUBUS;
10673       FlipSigns = false;
10674     }
10675   }
10676
10677   if (Swap)
10678     std::swap(Op0, Op1);
10679
10680   // Check that the operation in question is available (most are plain SSE2,
10681   // but PCMPGTQ and PCMPEQQ have different requirements).
10682   if (VT == MVT::v2i64) {
10683     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10684       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10685
10686       // First cast everything to the right type.
10687       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10688       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10689
10690       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10691       // bits of the inputs before performing those operations. The lower
10692       // compare is always unsigned.
10693       SDValue SB;
10694       if (FlipSigns) {
10695         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10696       } else {
10697         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10698         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10699         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10700                          Sign, Zero, Sign, Zero);
10701       }
10702       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10703       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10704
10705       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10706       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10707       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10708
10709       // Create masks for only the low parts/high parts of the 64 bit integers.
10710       static const int MaskHi[] = { 1, 1, 3, 3 };
10711       static const int MaskLo[] = { 0, 0, 2, 2 };
10712       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10713       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10714       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10715
10716       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10717       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10718
10719       if (Invert)
10720         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10721
10722       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10723     }
10724
10725     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10726       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10727       // pcmpeqd + pshufd + pand.
10728       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10729
10730       // First cast everything to the right type.
10731       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10732       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10733
10734       // Do the compare.
10735       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10736
10737       // Make sure the lower and upper halves are both all-ones.
10738       static const int Mask[] = { 1, 0, 3, 2 };
10739       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10740       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10741
10742       if (Invert)
10743         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10744
10745       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10746     }
10747   }
10748
10749   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10750   // bits of the inputs before performing those operations.
10751   if (FlipSigns) {
10752     EVT EltVT = VT.getVectorElementType();
10753     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10754     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10755     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10756   }
10757
10758   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10759
10760   // If the logical-not of the result is required, perform that now.
10761   if (Invert)
10762     Result = DAG.getNOT(dl, Result, VT);
10763
10764   if (MinMax)
10765     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10766
10767   if (Subus)
10768     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10769                          getZeroVector(VT, Subtarget, DAG, dl));
10770
10771   return Result;
10772 }
10773
10774 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10775
10776   MVT VT = Op.getSimpleValueType();
10777
10778   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10779
10780   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10781          && "SetCC type must be 8-bit or 1-bit integer");
10782   SDValue Op0 = Op.getOperand(0);
10783   SDValue Op1 = Op.getOperand(1);
10784   SDLoc dl(Op);
10785   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10786
10787   // Optimize to BT if possible.
10788   // Lower (X & (1 << N)) == 0 to BT(X, N).
10789   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10790   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10791   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10792       Op1.getOpcode() == ISD::Constant &&
10793       cast<ConstantSDNode>(Op1)->isNullValue() &&
10794       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10795     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10796     if (NewSetCC.getNode())
10797       return NewSetCC;
10798   }
10799
10800   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10801   // these.
10802   if (Op1.getOpcode() == ISD::Constant &&
10803       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10804        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10805       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10806
10807     // If the input is a setcc, then reuse the input setcc or use a new one with
10808     // the inverted condition.
10809     if (Op0.getOpcode() == X86ISD::SETCC) {
10810       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10811       bool Invert = (CC == ISD::SETNE) ^
10812         cast<ConstantSDNode>(Op1)->isNullValue();
10813       if (!Invert)
10814         return Op0;
10815
10816       CCode = X86::GetOppositeBranchCondition(CCode);
10817       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10818                                   DAG.getConstant(CCode, MVT::i8),
10819                                   Op0.getOperand(1));
10820       if (VT == MVT::i1)
10821         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10822       return SetCC;
10823     }
10824   }
10825   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10826       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10827       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10828
10829     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10830     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10831   }
10832
10833   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10834   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10835   if (X86CC == X86::COND_INVALID)
10836     return SDValue();
10837
10838   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10839   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10840   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10841                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10842   if (VT == MVT::i1)
10843     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10844   return SetCC;
10845 }
10846
10847 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10848 static bool isX86LogicalCmp(SDValue Op) {
10849   unsigned Opc = Op.getNode()->getOpcode();
10850   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10851       Opc == X86ISD::SAHF)
10852     return true;
10853   if (Op.getResNo() == 1 &&
10854       (Opc == X86ISD::ADD ||
10855        Opc == X86ISD::SUB ||
10856        Opc == X86ISD::ADC ||
10857        Opc == X86ISD::SBB ||
10858        Opc == X86ISD::SMUL ||
10859        Opc == X86ISD::UMUL ||
10860        Opc == X86ISD::INC ||
10861        Opc == X86ISD::DEC ||
10862        Opc == X86ISD::OR ||
10863        Opc == X86ISD::XOR ||
10864        Opc == X86ISD::AND))
10865     return true;
10866
10867   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10868     return true;
10869
10870   return false;
10871 }
10872
10873 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10874   if (V.getOpcode() != ISD::TRUNCATE)
10875     return false;
10876
10877   SDValue VOp0 = V.getOperand(0);
10878   unsigned InBits = VOp0.getValueSizeInBits();
10879   unsigned Bits = V.getValueSizeInBits();
10880   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10881 }
10882
10883 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10884   bool addTest = true;
10885   SDValue Cond  = Op.getOperand(0);
10886   SDValue Op1 = Op.getOperand(1);
10887   SDValue Op2 = Op.getOperand(2);
10888   SDLoc DL(Op);
10889   EVT VT = Op1.getValueType();
10890   SDValue CC;
10891
10892   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10893   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10894   // sequence later on.
10895   if (Cond.getOpcode() == ISD::SETCC &&
10896       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10897        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10898       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10899     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10900     int SSECC = translateX86FSETCC(
10901         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10902
10903     if (SSECC != 8) {
10904       if (Subtarget->hasAVX512()) {
10905         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10906                                   DAG.getConstant(SSECC, MVT::i8));
10907         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10908       }
10909       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10910                                 DAG.getConstant(SSECC, MVT::i8));
10911       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10912       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10913       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10914     }
10915   }
10916
10917   if (Cond.getOpcode() == ISD::SETCC) {
10918     SDValue NewCond = LowerSETCC(Cond, DAG);
10919     if (NewCond.getNode())
10920       Cond = NewCond;
10921   }
10922
10923   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10924   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10925   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10926   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10927   if (Cond.getOpcode() == X86ISD::SETCC &&
10928       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10929       isZero(Cond.getOperand(1).getOperand(1))) {
10930     SDValue Cmp = Cond.getOperand(1);
10931
10932     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10933
10934     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10935         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10936       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10937
10938       SDValue CmpOp0 = Cmp.getOperand(0);
10939       // Apply further optimizations for special cases
10940       // (select (x != 0), -1, 0) -> neg & sbb
10941       // (select (x == 0), 0, -1) -> neg & sbb
10942       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10943         if (YC->isNullValue() &&
10944             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10945           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10946           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10947                                     DAG.getConstant(0, CmpOp0.getValueType()),
10948                                     CmpOp0);
10949           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10950                                     DAG.getConstant(X86::COND_B, MVT::i8),
10951                                     SDValue(Neg.getNode(), 1));
10952           return Res;
10953         }
10954
10955       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10956                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10957       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10958
10959       SDValue Res =   // Res = 0 or -1.
10960         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10961                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10962
10963       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10964         Res = DAG.getNOT(DL, Res, Res.getValueType());
10965
10966       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10967       if (!N2C || !N2C->isNullValue())
10968         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10969       return Res;
10970     }
10971   }
10972
10973   // Look past (and (setcc_carry (cmp ...)), 1).
10974   if (Cond.getOpcode() == ISD::AND &&
10975       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10976     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10977     if (C && C->getAPIntValue() == 1)
10978       Cond = Cond.getOperand(0);
10979   }
10980
10981   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10982   // setting operand in place of the X86ISD::SETCC.
10983   unsigned CondOpcode = Cond.getOpcode();
10984   if (CondOpcode == X86ISD::SETCC ||
10985       CondOpcode == X86ISD::SETCC_CARRY) {
10986     CC = Cond.getOperand(0);
10987
10988     SDValue Cmp = Cond.getOperand(1);
10989     unsigned Opc = Cmp.getOpcode();
10990     MVT VT = Op.getSimpleValueType();
10991
10992     bool IllegalFPCMov = false;
10993     if (VT.isFloatingPoint() && !VT.isVector() &&
10994         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10995       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10996
10997     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10998         Opc == X86ISD::BT) { // FIXME
10999       Cond = Cmp;
11000       addTest = false;
11001     }
11002   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11003              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11004              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11005               Cond.getOperand(0).getValueType() != MVT::i8)) {
11006     SDValue LHS = Cond.getOperand(0);
11007     SDValue RHS = Cond.getOperand(1);
11008     unsigned X86Opcode;
11009     unsigned X86Cond;
11010     SDVTList VTs;
11011     switch (CondOpcode) {
11012     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11013     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11014     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11015     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11016     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11017     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11018     default: llvm_unreachable("unexpected overflowing operator");
11019     }
11020     if (CondOpcode == ISD::UMULO)
11021       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11022                           MVT::i32);
11023     else
11024       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11025
11026     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11027
11028     if (CondOpcode == ISD::UMULO)
11029       Cond = X86Op.getValue(2);
11030     else
11031       Cond = X86Op.getValue(1);
11032
11033     CC = DAG.getConstant(X86Cond, MVT::i8);
11034     addTest = false;
11035   }
11036
11037   if (addTest) {
11038     // Look pass the truncate if the high bits are known zero.
11039     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11040         Cond = Cond.getOperand(0);
11041
11042     // We know the result of AND is compared against zero. Try to match
11043     // it to BT.
11044     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11045       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11046       if (NewSetCC.getNode()) {
11047         CC = NewSetCC.getOperand(0);
11048         Cond = NewSetCC.getOperand(1);
11049         addTest = false;
11050       }
11051     }
11052   }
11053
11054   if (addTest) {
11055     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11056     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11057   }
11058
11059   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11060   // a <  b ?  0 : -1 -> RES = setcc_carry
11061   // a >= b ? -1 :  0 -> RES = setcc_carry
11062   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11063   if (Cond.getOpcode() == X86ISD::SUB) {
11064     Cond = ConvertCmpIfNecessary(Cond, DAG);
11065     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11066
11067     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11068         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11069       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11070                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11071       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11072         return DAG.getNOT(DL, Res, Res.getValueType());
11073       return Res;
11074     }
11075   }
11076
11077   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11078   // widen the cmov and push the truncate through. This avoids introducing a new
11079   // branch during isel and doesn't add any extensions.
11080   if (Op.getValueType() == MVT::i8 &&
11081       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11082     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11083     if (T1.getValueType() == T2.getValueType() &&
11084         // Blacklist CopyFromReg to avoid partial register stalls.
11085         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11086       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11087       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11088       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11089     }
11090   }
11091
11092   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11093   // condition is true.
11094   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11095   SDValue Ops[] = { Op2, Op1, CC, Cond };
11096   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11097 }
11098
11099 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11100   MVT VT = Op->getSimpleValueType(0);
11101   SDValue In = Op->getOperand(0);
11102   MVT InVT = In.getSimpleValueType();
11103   SDLoc dl(Op);
11104
11105   unsigned int NumElts = VT.getVectorNumElements();
11106   if (NumElts != 8 && NumElts != 16)
11107     return SDValue();
11108
11109   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11110     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11111
11112   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11113   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11114
11115   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11116   Constant *C = ConstantInt::get(*DAG.getContext(),
11117     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11118
11119   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11120   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11121   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11122                           MachinePointerInfo::getConstantPool(),
11123                           false, false, false, Alignment);
11124   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11125   if (VT.is512BitVector())
11126     return Brcst;
11127   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11128 }
11129
11130 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11131                                 SelectionDAG &DAG) {
11132   MVT VT = Op->getSimpleValueType(0);
11133   SDValue In = Op->getOperand(0);
11134   MVT InVT = In.getSimpleValueType();
11135   SDLoc dl(Op);
11136
11137   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11138     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11139
11140   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11141       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11142       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11143     return SDValue();
11144
11145   if (Subtarget->hasInt256())
11146     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11147
11148   // Optimize vectors in AVX mode
11149   // Sign extend  v8i16 to v8i32 and
11150   //              v4i32 to v4i64
11151   //
11152   // Divide input vector into two parts
11153   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11154   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11155   // concat the vectors to original VT
11156
11157   unsigned NumElems = InVT.getVectorNumElements();
11158   SDValue Undef = DAG.getUNDEF(InVT);
11159
11160   SmallVector<int,8> ShufMask1(NumElems, -1);
11161   for (unsigned i = 0; i != NumElems/2; ++i)
11162     ShufMask1[i] = i;
11163
11164   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11165
11166   SmallVector<int,8> ShufMask2(NumElems, -1);
11167   for (unsigned i = 0; i != NumElems/2; ++i)
11168     ShufMask2[i] = i + NumElems/2;
11169
11170   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11171
11172   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11173                                 VT.getVectorNumElements()/2);
11174
11175   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11176   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11177
11178   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11179 }
11180
11181 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11182 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11183 // from the AND / OR.
11184 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11185   Opc = Op.getOpcode();
11186   if (Opc != ISD::OR && Opc != ISD::AND)
11187     return false;
11188   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11189           Op.getOperand(0).hasOneUse() &&
11190           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11191           Op.getOperand(1).hasOneUse());
11192 }
11193
11194 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11195 // 1 and that the SETCC node has a single use.
11196 static bool isXor1OfSetCC(SDValue Op) {
11197   if (Op.getOpcode() != ISD::XOR)
11198     return false;
11199   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11200   if (N1C && N1C->getAPIntValue() == 1) {
11201     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11202       Op.getOperand(0).hasOneUse();
11203   }
11204   return false;
11205 }
11206
11207 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11208   bool addTest = true;
11209   SDValue Chain = Op.getOperand(0);
11210   SDValue Cond  = Op.getOperand(1);
11211   SDValue Dest  = Op.getOperand(2);
11212   SDLoc dl(Op);
11213   SDValue CC;
11214   bool Inverted = false;
11215
11216   if (Cond.getOpcode() == ISD::SETCC) {
11217     // Check for setcc([su]{add,sub,mul}o == 0).
11218     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11219         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11220         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11221         Cond.getOperand(0).getResNo() == 1 &&
11222         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11223          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11224          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11225          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11226          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11227          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11228       Inverted = true;
11229       Cond = Cond.getOperand(0);
11230     } else {
11231       SDValue NewCond = LowerSETCC(Cond, DAG);
11232       if (NewCond.getNode())
11233         Cond = NewCond;
11234     }
11235   }
11236 #if 0
11237   // FIXME: LowerXALUO doesn't handle these!!
11238   else if (Cond.getOpcode() == X86ISD::ADD  ||
11239            Cond.getOpcode() == X86ISD::SUB  ||
11240            Cond.getOpcode() == X86ISD::SMUL ||
11241            Cond.getOpcode() == X86ISD::UMUL)
11242     Cond = LowerXALUO(Cond, DAG);
11243 #endif
11244
11245   // Look pass (and (setcc_carry (cmp ...)), 1).
11246   if (Cond.getOpcode() == ISD::AND &&
11247       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11248     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11249     if (C && C->getAPIntValue() == 1)
11250       Cond = Cond.getOperand(0);
11251   }
11252
11253   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11254   // setting operand in place of the X86ISD::SETCC.
11255   unsigned CondOpcode = Cond.getOpcode();
11256   if (CondOpcode == X86ISD::SETCC ||
11257       CondOpcode == X86ISD::SETCC_CARRY) {
11258     CC = Cond.getOperand(0);
11259
11260     SDValue Cmp = Cond.getOperand(1);
11261     unsigned Opc = Cmp.getOpcode();
11262     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11263     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11264       Cond = Cmp;
11265       addTest = false;
11266     } else {
11267       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11268       default: break;
11269       case X86::COND_O:
11270       case X86::COND_B:
11271         // These can only come from an arithmetic instruction with overflow,
11272         // e.g. SADDO, UADDO.
11273         Cond = Cond.getNode()->getOperand(1);
11274         addTest = false;
11275         break;
11276       }
11277     }
11278   }
11279   CondOpcode = Cond.getOpcode();
11280   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11281       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11282       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11283        Cond.getOperand(0).getValueType() != MVT::i8)) {
11284     SDValue LHS = Cond.getOperand(0);
11285     SDValue RHS = Cond.getOperand(1);
11286     unsigned X86Opcode;
11287     unsigned X86Cond;
11288     SDVTList VTs;
11289     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11290     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11291     // X86ISD::INC).
11292     switch (CondOpcode) {
11293     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11294     case ISD::SADDO:
11295       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11296         if (C->isOne()) {
11297           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11298           break;
11299         }
11300       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11301     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11302     case ISD::SSUBO:
11303       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11304         if (C->isOne()) {
11305           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11306           break;
11307         }
11308       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11309     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11310     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11311     default: llvm_unreachable("unexpected overflowing operator");
11312     }
11313     if (Inverted)
11314       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11315     if (CondOpcode == ISD::UMULO)
11316       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11317                           MVT::i32);
11318     else
11319       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11320
11321     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11322
11323     if (CondOpcode == ISD::UMULO)
11324       Cond = X86Op.getValue(2);
11325     else
11326       Cond = X86Op.getValue(1);
11327
11328     CC = DAG.getConstant(X86Cond, MVT::i8);
11329     addTest = false;
11330   } else {
11331     unsigned CondOpc;
11332     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11333       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11334       if (CondOpc == ISD::OR) {
11335         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11336         // two branches instead of an explicit OR instruction with a
11337         // separate test.
11338         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11339             isX86LogicalCmp(Cmp)) {
11340           CC = Cond.getOperand(0).getOperand(0);
11341           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11342                               Chain, Dest, CC, Cmp);
11343           CC = Cond.getOperand(1).getOperand(0);
11344           Cond = Cmp;
11345           addTest = false;
11346         }
11347       } else { // ISD::AND
11348         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11349         // two branches instead of an explicit AND instruction with a
11350         // separate test. However, we only do this if this block doesn't
11351         // have a fall-through edge, because this requires an explicit
11352         // jmp when the condition is false.
11353         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11354             isX86LogicalCmp(Cmp) &&
11355             Op.getNode()->hasOneUse()) {
11356           X86::CondCode CCode =
11357             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11358           CCode = X86::GetOppositeBranchCondition(CCode);
11359           CC = DAG.getConstant(CCode, MVT::i8);
11360           SDNode *User = *Op.getNode()->use_begin();
11361           // Look for an unconditional branch following this conditional branch.
11362           // We need this because we need to reverse the successors in order
11363           // to implement FCMP_OEQ.
11364           if (User->getOpcode() == ISD::BR) {
11365             SDValue FalseBB = User->getOperand(1);
11366             SDNode *NewBR =
11367               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11368             assert(NewBR == User);
11369             (void)NewBR;
11370             Dest = FalseBB;
11371
11372             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11373                                 Chain, Dest, CC, Cmp);
11374             X86::CondCode CCode =
11375               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11376             CCode = X86::GetOppositeBranchCondition(CCode);
11377             CC = DAG.getConstant(CCode, MVT::i8);
11378             Cond = Cmp;
11379             addTest = false;
11380           }
11381         }
11382       }
11383     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11384       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11385       // It should be transformed during dag combiner except when the condition
11386       // is set by a arithmetics with overflow node.
11387       X86::CondCode CCode =
11388         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11389       CCode = X86::GetOppositeBranchCondition(CCode);
11390       CC = DAG.getConstant(CCode, MVT::i8);
11391       Cond = Cond.getOperand(0).getOperand(1);
11392       addTest = false;
11393     } else if (Cond.getOpcode() == ISD::SETCC &&
11394                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11395       // For FCMP_OEQ, we can emit
11396       // two branches instead of an explicit AND instruction with a
11397       // separate test. However, we only do this if this block doesn't
11398       // have a fall-through edge, because this requires an explicit
11399       // jmp when the condition is false.
11400       if (Op.getNode()->hasOneUse()) {
11401         SDNode *User = *Op.getNode()->use_begin();
11402         // Look for an unconditional branch following this conditional branch.
11403         // We need this because we need to reverse the successors in order
11404         // to implement FCMP_OEQ.
11405         if (User->getOpcode() == ISD::BR) {
11406           SDValue FalseBB = User->getOperand(1);
11407           SDNode *NewBR =
11408             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11409           assert(NewBR == User);
11410           (void)NewBR;
11411           Dest = FalseBB;
11412
11413           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11414                                     Cond.getOperand(0), Cond.getOperand(1));
11415           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11416           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11417           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11418                               Chain, Dest, CC, Cmp);
11419           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11420           Cond = Cmp;
11421           addTest = false;
11422         }
11423       }
11424     } else if (Cond.getOpcode() == ISD::SETCC &&
11425                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11426       // For FCMP_UNE, we can emit
11427       // two branches instead of an explicit AND instruction with a
11428       // separate test. However, we only do this if this block doesn't
11429       // have a fall-through edge, because this requires an explicit
11430       // jmp when the condition is false.
11431       if (Op.getNode()->hasOneUse()) {
11432         SDNode *User = *Op.getNode()->use_begin();
11433         // Look for an unconditional branch following this conditional branch.
11434         // We need this because we need to reverse the successors in order
11435         // to implement FCMP_UNE.
11436         if (User->getOpcode() == ISD::BR) {
11437           SDValue FalseBB = User->getOperand(1);
11438           SDNode *NewBR =
11439             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11440           assert(NewBR == User);
11441           (void)NewBR;
11442
11443           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11444                                     Cond.getOperand(0), Cond.getOperand(1));
11445           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11446           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11447           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11448                               Chain, Dest, CC, Cmp);
11449           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11450           Cond = Cmp;
11451           addTest = false;
11452           Dest = FalseBB;
11453         }
11454       }
11455     }
11456   }
11457
11458   if (addTest) {
11459     // Look pass the truncate if the high bits are known zero.
11460     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11461         Cond = Cond.getOperand(0);
11462
11463     // We know the result of AND is compared against zero. Try to match
11464     // it to BT.
11465     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11466       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11467       if (NewSetCC.getNode()) {
11468         CC = NewSetCC.getOperand(0);
11469         Cond = NewSetCC.getOperand(1);
11470         addTest = false;
11471       }
11472     }
11473   }
11474
11475   if (addTest) {
11476     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11477     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11478   }
11479   Cond = ConvertCmpIfNecessary(Cond, DAG);
11480   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11481                      Chain, Dest, CC, Cond);
11482 }
11483
11484 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11485 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11486 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11487 // that the guard pages used by the OS virtual memory manager are allocated in
11488 // correct sequence.
11489 SDValue
11490 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11491                                            SelectionDAG &DAG) const {
11492   MachineFunction &MF = DAG.getMachineFunction();
11493   bool SplitStack = MF.shouldSplitStack();
11494   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11495                SplitStack;
11496   SDLoc dl(Op);
11497
11498   if (!Lower) {
11499     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11500     SDNode* Node = Op.getNode();
11501
11502     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11503     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11504         " not tell us which reg is the stack pointer!");
11505     EVT VT = Node->getValueType(0);
11506     SDValue Tmp1 = SDValue(Node, 0);
11507     SDValue Tmp2 = SDValue(Node, 1);
11508     SDValue Tmp3 = Node->getOperand(2);
11509     SDValue Chain = Tmp1.getOperand(0);
11510
11511     // Chain the dynamic stack allocation so that it doesn't modify the stack
11512     // pointer when other instructions are using the stack.
11513     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11514         SDLoc(Node));
11515
11516     SDValue Size = Tmp2.getOperand(1);
11517     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11518     Chain = SP.getValue(1);
11519     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11520     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11521     unsigned StackAlign = TFI.getStackAlignment();
11522     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11523     if (Align > StackAlign)
11524       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11525           DAG.getConstant(-(uint64_t)Align, VT));
11526     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11527
11528     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11529         DAG.getIntPtrConstant(0, true), SDValue(),
11530         SDLoc(Node));
11531
11532     SDValue Ops[2] = { Tmp1, Tmp2 };
11533     return DAG.getMergeValues(Ops, dl);
11534   }
11535
11536   // Get the inputs.
11537   SDValue Chain = Op.getOperand(0);
11538   SDValue Size  = Op.getOperand(1);
11539   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11540   EVT VT = Op.getNode()->getValueType(0);
11541
11542   bool Is64Bit = Subtarget->is64Bit();
11543   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11544
11545   if (SplitStack) {
11546     MachineRegisterInfo &MRI = MF.getRegInfo();
11547
11548     if (Is64Bit) {
11549       // The 64 bit implementation of segmented stacks needs to clobber both r10
11550       // r11. This makes it impossible to use it along with nested parameters.
11551       const Function *F = MF.getFunction();
11552
11553       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11554            I != E; ++I)
11555         if (I->hasNestAttr())
11556           report_fatal_error("Cannot use segmented stacks with functions that "
11557                              "have nested arguments.");
11558     }
11559
11560     const TargetRegisterClass *AddrRegClass =
11561       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11562     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11563     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11564     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11565                                 DAG.getRegister(Vreg, SPTy));
11566     SDValue Ops1[2] = { Value, Chain };
11567     return DAG.getMergeValues(Ops1, dl);
11568   } else {
11569     SDValue Flag;
11570     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11571
11572     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11573     Flag = Chain.getValue(1);
11574     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11575
11576     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11577
11578     const X86RegisterInfo *RegInfo =
11579       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11580     unsigned SPReg = RegInfo->getStackRegister();
11581     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11582     Chain = SP.getValue(1);
11583
11584     if (Align) {
11585       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11586                        DAG.getConstant(-(uint64_t)Align, VT));
11587       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11588     }
11589
11590     SDValue Ops1[2] = { SP, Chain };
11591     return DAG.getMergeValues(Ops1, dl);
11592   }
11593 }
11594
11595 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11596   MachineFunction &MF = DAG.getMachineFunction();
11597   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11598
11599   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11600   SDLoc DL(Op);
11601
11602   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11603     // vastart just stores the address of the VarArgsFrameIndex slot into the
11604     // memory location argument.
11605     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11606                                    getPointerTy());
11607     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11608                         MachinePointerInfo(SV), false, false, 0);
11609   }
11610
11611   // __va_list_tag:
11612   //   gp_offset         (0 - 6 * 8)
11613   //   fp_offset         (48 - 48 + 8 * 16)
11614   //   overflow_arg_area (point to parameters coming in memory).
11615   //   reg_save_area
11616   SmallVector<SDValue, 8> MemOps;
11617   SDValue FIN = Op.getOperand(1);
11618   // Store gp_offset
11619   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11620                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11621                                                MVT::i32),
11622                                FIN, MachinePointerInfo(SV), false, false, 0);
11623   MemOps.push_back(Store);
11624
11625   // Store fp_offset
11626   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11627                     FIN, DAG.getIntPtrConstant(4));
11628   Store = DAG.getStore(Op.getOperand(0), DL,
11629                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11630                                        MVT::i32),
11631                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11632   MemOps.push_back(Store);
11633
11634   // Store ptr to overflow_arg_area
11635   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11636                     FIN, DAG.getIntPtrConstant(4));
11637   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11638                                     getPointerTy());
11639   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11640                        MachinePointerInfo(SV, 8),
11641                        false, false, 0);
11642   MemOps.push_back(Store);
11643
11644   // Store ptr to reg_save_area.
11645   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11646                     FIN, DAG.getIntPtrConstant(8));
11647   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11648                                     getPointerTy());
11649   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11650                        MachinePointerInfo(SV, 16), false, false, 0);
11651   MemOps.push_back(Store);
11652   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11653 }
11654
11655 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11656   assert(Subtarget->is64Bit() &&
11657          "LowerVAARG only handles 64-bit va_arg!");
11658   assert((Subtarget->isTargetLinux() ||
11659           Subtarget->isTargetDarwin()) &&
11660           "Unhandled target in LowerVAARG");
11661   assert(Op.getNode()->getNumOperands() == 4);
11662   SDValue Chain = Op.getOperand(0);
11663   SDValue SrcPtr = Op.getOperand(1);
11664   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11665   unsigned Align = Op.getConstantOperandVal(3);
11666   SDLoc dl(Op);
11667
11668   EVT ArgVT = Op.getNode()->getValueType(0);
11669   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11670   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11671   uint8_t ArgMode;
11672
11673   // Decide which area this value should be read from.
11674   // TODO: Implement the AMD64 ABI in its entirety. This simple
11675   // selection mechanism works only for the basic types.
11676   if (ArgVT == MVT::f80) {
11677     llvm_unreachable("va_arg for f80 not yet implemented");
11678   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11679     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11680   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11681     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11682   } else {
11683     llvm_unreachable("Unhandled argument type in LowerVAARG");
11684   }
11685
11686   if (ArgMode == 2) {
11687     // Sanity Check: Make sure using fp_offset makes sense.
11688     assert(!getTargetMachine().Options.UseSoftFloat &&
11689            !(DAG.getMachineFunction()
11690                 .getFunction()->getAttributes()
11691                 .hasAttribute(AttributeSet::FunctionIndex,
11692                               Attribute::NoImplicitFloat)) &&
11693            Subtarget->hasSSE1());
11694   }
11695
11696   // Insert VAARG_64 node into the DAG
11697   // VAARG_64 returns two values: Variable Argument Address, Chain
11698   SmallVector<SDValue, 11> InstOps;
11699   InstOps.push_back(Chain);
11700   InstOps.push_back(SrcPtr);
11701   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11702   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11703   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11704   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11705   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11706                                           VTs, InstOps, MVT::i64,
11707                                           MachinePointerInfo(SV),
11708                                           /*Align=*/0,
11709                                           /*Volatile=*/false,
11710                                           /*ReadMem=*/true,
11711                                           /*WriteMem=*/true);
11712   Chain = VAARG.getValue(1);
11713
11714   // Load the next argument and return it
11715   return DAG.getLoad(ArgVT, dl,
11716                      Chain,
11717                      VAARG,
11718                      MachinePointerInfo(),
11719                      false, false, false, 0);
11720 }
11721
11722 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11723                            SelectionDAG &DAG) {
11724   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11725   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11726   SDValue Chain = Op.getOperand(0);
11727   SDValue DstPtr = Op.getOperand(1);
11728   SDValue SrcPtr = Op.getOperand(2);
11729   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11730   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11731   SDLoc DL(Op);
11732
11733   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11734                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11735                        false,
11736                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11737 }
11738
11739 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11740 // amount is a constant. Takes immediate version of shift as input.
11741 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11742                                           SDValue SrcOp, uint64_t ShiftAmt,
11743                                           SelectionDAG &DAG) {
11744   MVT ElementType = VT.getVectorElementType();
11745
11746   // Fold this packed shift into its first operand if ShiftAmt is 0.
11747   if (ShiftAmt == 0)
11748     return SrcOp;
11749
11750   // Check for ShiftAmt >= element width
11751   if (ShiftAmt >= ElementType.getSizeInBits()) {
11752     if (Opc == X86ISD::VSRAI)
11753       ShiftAmt = ElementType.getSizeInBits() - 1;
11754     else
11755       return DAG.getConstant(0, VT);
11756   }
11757
11758   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11759          && "Unknown target vector shift-by-constant node");
11760
11761   // Fold this packed vector shift into a build vector if SrcOp is a
11762   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11763   if (VT == SrcOp.getSimpleValueType() &&
11764       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11765     SmallVector<SDValue, 8> Elts;
11766     unsigned NumElts = SrcOp->getNumOperands();
11767     ConstantSDNode *ND;
11768
11769     switch(Opc) {
11770     default: llvm_unreachable(nullptr);
11771     case X86ISD::VSHLI:
11772       for (unsigned i=0; i!=NumElts; ++i) {
11773         SDValue CurrentOp = SrcOp->getOperand(i);
11774         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11775           Elts.push_back(CurrentOp);
11776           continue;
11777         }
11778         ND = cast<ConstantSDNode>(CurrentOp);
11779         const APInt &C = ND->getAPIntValue();
11780         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11781       }
11782       break;
11783     case X86ISD::VSRLI:
11784       for (unsigned i=0; i!=NumElts; ++i) {
11785         SDValue CurrentOp = SrcOp->getOperand(i);
11786         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11787           Elts.push_back(CurrentOp);
11788           continue;
11789         }
11790         ND = cast<ConstantSDNode>(CurrentOp);
11791         const APInt &C = ND->getAPIntValue();
11792         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11793       }
11794       break;
11795     case X86ISD::VSRAI:
11796       for (unsigned i=0; i!=NumElts; ++i) {
11797         SDValue CurrentOp = SrcOp->getOperand(i);
11798         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11799           Elts.push_back(CurrentOp);
11800           continue;
11801         }
11802         ND = cast<ConstantSDNode>(CurrentOp);
11803         const APInt &C = ND->getAPIntValue();
11804         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11805       }
11806       break;
11807     }
11808
11809     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11810   }
11811
11812   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11813 }
11814
11815 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11816 // may or may not be a constant. Takes immediate version of shift as input.
11817 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11818                                    SDValue SrcOp, SDValue ShAmt,
11819                                    SelectionDAG &DAG) {
11820   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11821
11822   // Catch shift-by-constant.
11823   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11824     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11825                                       CShAmt->getZExtValue(), DAG);
11826
11827   // Change opcode to non-immediate version
11828   switch (Opc) {
11829     default: llvm_unreachable("Unknown target vector shift node");
11830     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11831     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11832     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11833   }
11834
11835   // Need to build a vector containing shift amount
11836   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11837   SDValue ShOps[4];
11838   ShOps[0] = ShAmt;
11839   ShOps[1] = DAG.getConstant(0, MVT::i32);
11840   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11841   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11842
11843   // The return type has to be a 128-bit type with the same element
11844   // type as the input type.
11845   MVT EltVT = VT.getVectorElementType();
11846   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11847
11848   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11849   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11850 }
11851
11852 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11853   SDLoc dl(Op);
11854   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11855   switch (IntNo) {
11856   default: return SDValue();    // Don't custom lower most intrinsics.
11857   // Comparison intrinsics.
11858   case Intrinsic::x86_sse_comieq_ss:
11859   case Intrinsic::x86_sse_comilt_ss:
11860   case Intrinsic::x86_sse_comile_ss:
11861   case Intrinsic::x86_sse_comigt_ss:
11862   case Intrinsic::x86_sse_comige_ss:
11863   case Intrinsic::x86_sse_comineq_ss:
11864   case Intrinsic::x86_sse_ucomieq_ss:
11865   case Intrinsic::x86_sse_ucomilt_ss:
11866   case Intrinsic::x86_sse_ucomile_ss:
11867   case Intrinsic::x86_sse_ucomigt_ss:
11868   case Intrinsic::x86_sse_ucomige_ss:
11869   case Intrinsic::x86_sse_ucomineq_ss:
11870   case Intrinsic::x86_sse2_comieq_sd:
11871   case Intrinsic::x86_sse2_comilt_sd:
11872   case Intrinsic::x86_sse2_comile_sd:
11873   case Intrinsic::x86_sse2_comigt_sd:
11874   case Intrinsic::x86_sse2_comige_sd:
11875   case Intrinsic::x86_sse2_comineq_sd:
11876   case Intrinsic::x86_sse2_ucomieq_sd:
11877   case Intrinsic::x86_sse2_ucomilt_sd:
11878   case Intrinsic::x86_sse2_ucomile_sd:
11879   case Intrinsic::x86_sse2_ucomigt_sd:
11880   case Intrinsic::x86_sse2_ucomige_sd:
11881   case Intrinsic::x86_sse2_ucomineq_sd: {
11882     unsigned Opc;
11883     ISD::CondCode CC;
11884     switch (IntNo) {
11885     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11886     case Intrinsic::x86_sse_comieq_ss:
11887     case Intrinsic::x86_sse2_comieq_sd:
11888       Opc = X86ISD::COMI;
11889       CC = ISD::SETEQ;
11890       break;
11891     case Intrinsic::x86_sse_comilt_ss:
11892     case Intrinsic::x86_sse2_comilt_sd:
11893       Opc = X86ISD::COMI;
11894       CC = ISD::SETLT;
11895       break;
11896     case Intrinsic::x86_sse_comile_ss:
11897     case Intrinsic::x86_sse2_comile_sd:
11898       Opc = X86ISD::COMI;
11899       CC = ISD::SETLE;
11900       break;
11901     case Intrinsic::x86_sse_comigt_ss:
11902     case Intrinsic::x86_sse2_comigt_sd:
11903       Opc = X86ISD::COMI;
11904       CC = ISD::SETGT;
11905       break;
11906     case Intrinsic::x86_sse_comige_ss:
11907     case Intrinsic::x86_sse2_comige_sd:
11908       Opc = X86ISD::COMI;
11909       CC = ISD::SETGE;
11910       break;
11911     case Intrinsic::x86_sse_comineq_ss:
11912     case Intrinsic::x86_sse2_comineq_sd:
11913       Opc = X86ISD::COMI;
11914       CC = ISD::SETNE;
11915       break;
11916     case Intrinsic::x86_sse_ucomieq_ss:
11917     case Intrinsic::x86_sse2_ucomieq_sd:
11918       Opc = X86ISD::UCOMI;
11919       CC = ISD::SETEQ;
11920       break;
11921     case Intrinsic::x86_sse_ucomilt_ss:
11922     case Intrinsic::x86_sse2_ucomilt_sd:
11923       Opc = X86ISD::UCOMI;
11924       CC = ISD::SETLT;
11925       break;
11926     case Intrinsic::x86_sse_ucomile_ss:
11927     case Intrinsic::x86_sse2_ucomile_sd:
11928       Opc = X86ISD::UCOMI;
11929       CC = ISD::SETLE;
11930       break;
11931     case Intrinsic::x86_sse_ucomigt_ss:
11932     case Intrinsic::x86_sse2_ucomigt_sd:
11933       Opc = X86ISD::UCOMI;
11934       CC = ISD::SETGT;
11935       break;
11936     case Intrinsic::x86_sse_ucomige_ss:
11937     case Intrinsic::x86_sse2_ucomige_sd:
11938       Opc = X86ISD::UCOMI;
11939       CC = ISD::SETGE;
11940       break;
11941     case Intrinsic::x86_sse_ucomineq_ss:
11942     case Intrinsic::x86_sse2_ucomineq_sd:
11943       Opc = X86ISD::UCOMI;
11944       CC = ISD::SETNE;
11945       break;
11946     }
11947
11948     SDValue LHS = Op.getOperand(1);
11949     SDValue RHS = Op.getOperand(2);
11950     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11951     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11952     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11953     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11954                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11955     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11956   }
11957
11958   // Arithmetic intrinsics.
11959   case Intrinsic::x86_sse2_pmulu_dq:
11960   case Intrinsic::x86_avx2_pmulu_dq:
11961     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11962                        Op.getOperand(1), Op.getOperand(2));
11963
11964   case Intrinsic::x86_sse41_pmuldq:
11965   case Intrinsic::x86_avx2_pmul_dq:
11966     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11967                        Op.getOperand(1), Op.getOperand(2));
11968
11969   case Intrinsic::x86_sse2_pmulhu_w:
11970   case Intrinsic::x86_avx2_pmulhu_w:
11971     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11972                        Op.getOperand(1), Op.getOperand(2));
11973
11974   case Intrinsic::x86_sse2_pmulh_w:
11975   case Intrinsic::x86_avx2_pmulh_w:
11976     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11977                        Op.getOperand(1), Op.getOperand(2));
11978
11979   // SSE2/AVX2 sub with unsigned saturation intrinsics
11980   case Intrinsic::x86_sse2_psubus_b:
11981   case Intrinsic::x86_sse2_psubus_w:
11982   case Intrinsic::x86_avx2_psubus_b:
11983   case Intrinsic::x86_avx2_psubus_w:
11984     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11985                        Op.getOperand(1), Op.getOperand(2));
11986
11987   // SSE3/AVX horizontal add/sub intrinsics
11988   case Intrinsic::x86_sse3_hadd_ps:
11989   case Intrinsic::x86_sse3_hadd_pd:
11990   case Intrinsic::x86_avx_hadd_ps_256:
11991   case Intrinsic::x86_avx_hadd_pd_256:
11992   case Intrinsic::x86_sse3_hsub_ps:
11993   case Intrinsic::x86_sse3_hsub_pd:
11994   case Intrinsic::x86_avx_hsub_ps_256:
11995   case Intrinsic::x86_avx_hsub_pd_256:
11996   case Intrinsic::x86_ssse3_phadd_w_128:
11997   case Intrinsic::x86_ssse3_phadd_d_128:
11998   case Intrinsic::x86_avx2_phadd_w:
11999   case Intrinsic::x86_avx2_phadd_d:
12000   case Intrinsic::x86_ssse3_phsub_w_128:
12001   case Intrinsic::x86_ssse3_phsub_d_128:
12002   case Intrinsic::x86_avx2_phsub_w:
12003   case Intrinsic::x86_avx2_phsub_d: {
12004     unsigned Opcode;
12005     switch (IntNo) {
12006     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12007     case Intrinsic::x86_sse3_hadd_ps:
12008     case Intrinsic::x86_sse3_hadd_pd:
12009     case Intrinsic::x86_avx_hadd_ps_256:
12010     case Intrinsic::x86_avx_hadd_pd_256:
12011       Opcode = X86ISD::FHADD;
12012       break;
12013     case Intrinsic::x86_sse3_hsub_ps:
12014     case Intrinsic::x86_sse3_hsub_pd:
12015     case Intrinsic::x86_avx_hsub_ps_256:
12016     case Intrinsic::x86_avx_hsub_pd_256:
12017       Opcode = X86ISD::FHSUB;
12018       break;
12019     case Intrinsic::x86_ssse3_phadd_w_128:
12020     case Intrinsic::x86_ssse3_phadd_d_128:
12021     case Intrinsic::x86_avx2_phadd_w:
12022     case Intrinsic::x86_avx2_phadd_d:
12023       Opcode = X86ISD::HADD;
12024       break;
12025     case Intrinsic::x86_ssse3_phsub_w_128:
12026     case Intrinsic::x86_ssse3_phsub_d_128:
12027     case Intrinsic::x86_avx2_phsub_w:
12028     case Intrinsic::x86_avx2_phsub_d:
12029       Opcode = X86ISD::HSUB;
12030       break;
12031     }
12032     return DAG.getNode(Opcode, dl, Op.getValueType(),
12033                        Op.getOperand(1), Op.getOperand(2));
12034   }
12035
12036   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12037   case Intrinsic::x86_sse2_pmaxu_b:
12038   case Intrinsic::x86_sse41_pmaxuw:
12039   case Intrinsic::x86_sse41_pmaxud:
12040   case Intrinsic::x86_avx2_pmaxu_b:
12041   case Intrinsic::x86_avx2_pmaxu_w:
12042   case Intrinsic::x86_avx2_pmaxu_d:
12043   case Intrinsic::x86_sse2_pminu_b:
12044   case Intrinsic::x86_sse41_pminuw:
12045   case Intrinsic::x86_sse41_pminud:
12046   case Intrinsic::x86_avx2_pminu_b:
12047   case Intrinsic::x86_avx2_pminu_w:
12048   case Intrinsic::x86_avx2_pminu_d:
12049   case Intrinsic::x86_sse41_pmaxsb:
12050   case Intrinsic::x86_sse2_pmaxs_w:
12051   case Intrinsic::x86_sse41_pmaxsd:
12052   case Intrinsic::x86_avx2_pmaxs_b:
12053   case Intrinsic::x86_avx2_pmaxs_w:
12054   case Intrinsic::x86_avx2_pmaxs_d:
12055   case Intrinsic::x86_sse41_pminsb:
12056   case Intrinsic::x86_sse2_pmins_w:
12057   case Intrinsic::x86_sse41_pminsd:
12058   case Intrinsic::x86_avx2_pmins_b:
12059   case Intrinsic::x86_avx2_pmins_w:
12060   case Intrinsic::x86_avx2_pmins_d: {
12061     unsigned Opcode;
12062     switch (IntNo) {
12063     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12064     case Intrinsic::x86_sse2_pmaxu_b:
12065     case Intrinsic::x86_sse41_pmaxuw:
12066     case Intrinsic::x86_sse41_pmaxud:
12067     case Intrinsic::x86_avx2_pmaxu_b:
12068     case Intrinsic::x86_avx2_pmaxu_w:
12069     case Intrinsic::x86_avx2_pmaxu_d:
12070       Opcode = X86ISD::UMAX;
12071       break;
12072     case Intrinsic::x86_sse2_pminu_b:
12073     case Intrinsic::x86_sse41_pminuw:
12074     case Intrinsic::x86_sse41_pminud:
12075     case Intrinsic::x86_avx2_pminu_b:
12076     case Intrinsic::x86_avx2_pminu_w:
12077     case Intrinsic::x86_avx2_pminu_d:
12078       Opcode = X86ISD::UMIN;
12079       break;
12080     case Intrinsic::x86_sse41_pmaxsb:
12081     case Intrinsic::x86_sse2_pmaxs_w:
12082     case Intrinsic::x86_sse41_pmaxsd:
12083     case Intrinsic::x86_avx2_pmaxs_b:
12084     case Intrinsic::x86_avx2_pmaxs_w:
12085     case Intrinsic::x86_avx2_pmaxs_d:
12086       Opcode = X86ISD::SMAX;
12087       break;
12088     case Intrinsic::x86_sse41_pminsb:
12089     case Intrinsic::x86_sse2_pmins_w:
12090     case Intrinsic::x86_sse41_pminsd:
12091     case Intrinsic::x86_avx2_pmins_b:
12092     case Intrinsic::x86_avx2_pmins_w:
12093     case Intrinsic::x86_avx2_pmins_d:
12094       Opcode = X86ISD::SMIN;
12095       break;
12096     }
12097     return DAG.getNode(Opcode, dl, Op.getValueType(),
12098                        Op.getOperand(1), Op.getOperand(2));
12099   }
12100
12101   // SSE/SSE2/AVX floating point max/min intrinsics.
12102   case Intrinsic::x86_sse_max_ps:
12103   case Intrinsic::x86_sse2_max_pd:
12104   case Intrinsic::x86_avx_max_ps_256:
12105   case Intrinsic::x86_avx_max_pd_256:
12106   case Intrinsic::x86_sse_min_ps:
12107   case Intrinsic::x86_sse2_min_pd:
12108   case Intrinsic::x86_avx_min_ps_256:
12109   case Intrinsic::x86_avx_min_pd_256: {
12110     unsigned Opcode;
12111     switch (IntNo) {
12112     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12113     case Intrinsic::x86_sse_max_ps:
12114     case Intrinsic::x86_sse2_max_pd:
12115     case Intrinsic::x86_avx_max_ps_256:
12116     case Intrinsic::x86_avx_max_pd_256:
12117       Opcode = X86ISD::FMAX;
12118       break;
12119     case Intrinsic::x86_sse_min_ps:
12120     case Intrinsic::x86_sse2_min_pd:
12121     case Intrinsic::x86_avx_min_ps_256:
12122     case Intrinsic::x86_avx_min_pd_256:
12123       Opcode = X86ISD::FMIN;
12124       break;
12125     }
12126     return DAG.getNode(Opcode, dl, Op.getValueType(),
12127                        Op.getOperand(1), Op.getOperand(2));
12128   }
12129
12130   // AVX2 variable shift intrinsics
12131   case Intrinsic::x86_avx2_psllv_d:
12132   case Intrinsic::x86_avx2_psllv_q:
12133   case Intrinsic::x86_avx2_psllv_d_256:
12134   case Intrinsic::x86_avx2_psllv_q_256:
12135   case Intrinsic::x86_avx2_psrlv_d:
12136   case Intrinsic::x86_avx2_psrlv_q:
12137   case Intrinsic::x86_avx2_psrlv_d_256:
12138   case Intrinsic::x86_avx2_psrlv_q_256:
12139   case Intrinsic::x86_avx2_psrav_d:
12140   case Intrinsic::x86_avx2_psrav_d_256: {
12141     unsigned Opcode;
12142     switch (IntNo) {
12143     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12144     case Intrinsic::x86_avx2_psllv_d:
12145     case Intrinsic::x86_avx2_psllv_q:
12146     case Intrinsic::x86_avx2_psllv_d_256:
12147     case Intrinsic::x86_avx2_psllv_q_256:
12148       Opcode = ISD::SHL;
12149       break;
12150     case Intrinsic::x86_avx2_psrlv_d:
12151     case Intrinsic::x86_avx2_psrlv_q:
12152     case Intrinsic::x86_avx2_psrlv_d_256:
12153     case Intrinsic::x86_avx2_psrlv_q_256:
12154       Opcode = ISD::SRL;
12155       break;
12156     case Intrinsic::x86_avx2_psrav_d:
12157     case Intrinsic::x86_avx2_psrav_d_256:
12158       Opcode = ISD::SRA;
12159       break;
12160     }
12161     return DAG.getNode(Opcode, dl, Op.getValueType(),
12162                        Op.getOperand(1), Op.getOperand(2));
12163   }
12164
12165   case Intrinsic::x86_ssse3_pshuf_b_128:
12166   case Intrinsic::x86_avx2_pshuf_b:
12167     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12168                        Op.getOperand(1), Op.getOperand(2));
12169
12170   case Intrinsic::x86_ssse3_psign_b_128:
12171   case Intrinsic::x86_ssse3_psign_w_128:
12172   case Intrinsic::x86_ssse3_psign_d_128:
12173   case Intrinsic::x86_avx2_psign_b:
12174   case Intrinsic::x86_avx2_psign_w:
12175   case Intrinsic::x86_avx2_psign_d:
12176     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12177                        Op.getOperand(1), Op.getOperand(2));
12178
12179   case Intrinsic::x86_sse41_insertps:
12180     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12181                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12182
12183   case Intrinsic::x86_avx_vperm2f128_ps_256:
12184   case Intrinsic::x86_avx_vperm2f128_pd_256:
12185   case Intrinsic::x86_avx_vperm2f128_si_256:
12186   case Intrinsic::x86_avx2_vperm2i128:
12187     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12188                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12189
12190   case Intrinsic::x86_avx2_permd:
12191   case Intrinsic::x86_avx2_permps:
12192     // Operands intentionally swapped. Mask is last operand to intrinsic,
12193     // but second operand for node/instruction.
12194     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12195                        Op.getOperand(2), Op.getOperand(1));
12196
12197   case Intrinsic::x86_sse_sqrt_ps:
12198   case Intrinsic::x86_sse2_sqrt_pd:
12199   case Intrinsic::x86_avx_sqrt_ps_256:
12200   case Intrinsic::x86_avx_sqrt_pd_256:
12201     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12202
12203   // ptest and testp intrinsics. The intrinsic these come from are designed to
12204   // return an integer value, not just an instruction so lower it to the ptest
12205   // or testp pattern and a setcc for the result.
12206   case Intrinsic::x86_sse41_ptestz:
12207   case Intrinsic::x86_sse41_ptestc:
12208   case Intrinsic::x86_sse41_ptestnzc:
12209   case Intrinsic::x86_avx_ptestz_256:
12210   case Intrinsic::x86_avx_ptestc_256:
12211   case Intrinsic::x86_avx_ptestnzc_256:
12212   case Intrinsic::x86_avx_vtestz_ps:
12213   case Intrinsic::x86_avx_vtestc_ps:
12214   case Intrinsic::x86_avx_vtestnzc_ps:
12215   case Intrinsic::x86_avx_vtestz_pd:
12216   case Intrinsic::x86_avx_vtestc_pd:
12217   case Intrinsic::x86_avx_vtestnzc_pd:
12218   case Intrinsic::x86_avx_vtestz_ps_256:
12219   case Intrinsic::x86_avx_vtestc_ps_256:
12220   case Intrinsic::x86_avx_vtestnzc_ps_256:
12221   case Intrinsic::x86_avx_vtestz_pd_256:
12222   case Intrinsic::x86_avx_vtestc_pd_256:
12223   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12224     bool IsTestPacked = false;
12225     unsigned X86CC;
12226     switch (IntNo) {
12227     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12228     case Intrinsic::x86_avx_vtestz_ps:
12229     case Intrinsic::x86_avx_vtestz_pd:
12230     case Intrinsic::x86_avx_vtestz_ps_256:
12231     case Intrinsic::x86_avx_vtestz_pd_256:
12232       IsTestPacked = true; // Fallthrough
12233     case Intrinsic::x86_sse41_ptestz:
12234     case Intrinsic::x86_avx_ptestz_256:
12235       // ZF = 1
12236       X86CC = X86::COND_E;
12237       break;
12238     case Intrinsic::x86_avx_vtestc_ps:
12239     case Intrinsic::x86_avx_vtestc_pd:
12240     case Intrinsic::x86_avx_vtestc_ps_256:
12241     case Intrinsic::x86_avx_vtestc_pd_256:
12242       IsTestPacked = true; // Fallthrough
12243     case Intrinsic::x86_sse41_ptestc:
12244     case Intrinsic::x86_avx_ptestc_256:
12245       // CF = 1
12246       X86CC = X86::COND_B;
12247       break;
12248     case Intrinsic::x86_avx_vtestnzc_ps:
12249     case Intrinsic::x86_avx_vtestnzc_pd:
12250     case Intrinsic::x86_avx_vtestnzc_ps_256:
12251     case Intrinsic::x86_avx_vtestnzc_pd_256:
12252       IsTestPacked = true; // Fallthrough
12253     case Intrinsic::x86_sse41_ptestnzc:
12254     case Intrinsic::x86_avx_ptestnzc_256:
12255       // ZF and CF = 0
12256       X86CC = X86::COND_A;
12257       break;
12258     }
12259
12260     SDValue LHS = Op.getOperand(1);
12261     SDValue RHS = Op.getOperand(2);
12262     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12263     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12264     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12265     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12266     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12267   }
12268   case Intrinsic::x86_avx512_kortestz_w:
12269   case Intrinsic::x86_avx512_kortestc_w: {
12270     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12271     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12272     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12273     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12274     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12275     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12276     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12277   }
12278
12279   // SSE/AVX shift intrinsics
12280   case Intrinsic::x86_sse2_psll_w:
12281   case Intrinsic::x86_sse2_psll_d:
12282   case Intrinsic::x86_sse2_psll_q:
12283   case Intrinsic::x86_avx2_psll_w:
12284   case Intrinsic::x86_avx2_psll_d:
12285   case Intrinsic::x86_avx2_psll_q:
12286   case Intrinsic::x86_sse2_psrl_w:
12287   case Intrinsic::x86_sse2_psrl_d:
12288   case Intrinsic::x86_sse2_psrl_q:
12289   case Intrinsic::x86_avx2_psrl_w:
12290   case Intrinsic::x86_avx2_psrl_d:
12291   case Intrinsic::x86_avx2_psrl_q:
12292   case Intrinsic::x86_sse2_psra_w:
12293   case Intrinsic::x86_sse2_psra_d:
12294   case Intrinsic::x86_avx2_psra_w:
12295   case Intrinsic::x86_avx2_psra_d: {
12296     unsigned Opcode;
12297     switch (IntNo) {
12298     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12299     case Intrinsic::x86_sse2_psll_w:
12300     case Intrinsic::x86_sse2_psll_d:
12301     case Intrinsic::x86_sse2_psll_q:
12302     case Intrinsic::x86_avx2_psll_w:
12303     case Intrinsic::x86_avx2_psll_d:
12304     case Intrinsic::x86_avx2_psll_q:
12305       Opcode = X86ISD::VSHL;
12306       break;
12307     case Intrinsic::x86_sse2_psrl_w:
12308     case Intrinsic::x86_sse2_psrl_d:
12309     case Intrinsic::x86_sse2_psrl_q:
12310     case Intrinsic::x86_avx2_psrl_w:
12311     case Intrinsic::x86_avx2_psrl_d:
12312     case Intrinsic::x86_avx2_psrl_q:
12313       Opcode = X86ISD::VSRL;
12314       break;
12315     case Intrinsic::x86_sse2_psra_w:
12316     case Intrinsic::x86_sse2_psra_d:
12317     case Intrinsic::x86_avx2_psra_w:
12318     case Intrinsic::x86_avx2_psra_d:
12319       Opcode = X86ISD::VSRA;
12320       break;
12321     }
12322     return DAG.getNode(Opcode, dl, Op.getValueType(),
12323                        Op.getOperand(1), Op.getOperand(2));
12324   }
12325
12326   // SSE/AVX immediate shift intrinsics
12327   case Intrinsic::x86_sse2_pslli_w:
12328   case Intrinsic::x86_sse2_pslli_d:
12329   case Intrinsic::x86_sse2_pslli_q:
12330   case Intrinsic::x86_avx2_pslli_w:
12331   case Intrinsic::x86_avx2_pslli_d:
12332   case Intrinsic::x86_avx2_pslli_q:
12333   case Intrinsic::x86_sse2_psrli_w:
12334   case Intrinsic::x86_sse2_psrli_d:
12335   case Intrinsic::x86_sse2_psrli_q:
12336   case Intrinsic::x86_avx2_psrli_w:
12337   case Intrinsic::x86_avx2_psrli_d:
12338   case Intrinsic::x86_avx2_psrli_q:
12339   case Intrinsic::x86_sse2_psrai_w:
12340   case Intrinsic::x86_sse2_psrai_d:
12341   case Intrinsic::x86_avx2_psrai_w:
12342   case Intrinsic::x86_avx2_psrai_d: {
12343     unsigned Opcode;
12344     switch (IntNo) {
12345     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12346     case Intrinsic::x86_sse2_pslli_w:
12347     case Intrinsic::x86_sse2_pslli_d:
12348     case Intrinsic::x86_sse2_pslli_q:
12349     case Intrinsic::x86_avx2_pslli_w:
12350     case Intrinsic::x86_avx2_pslli_d:
12351     case Intrinsic::x86_avx2_pslli_q:
12352       Opcode = X86ISD::VSHLI;
12353       break;
12354     case Intrinsic::x86_sse2_psrli_w:
12355     case Intrinsic::x86_sse2_psrli_d:
12356     case Intrinsic::x86_sse2_psrli_q:
12357     case Intrinsic::x86_avx2_psrli_w:
12358     case Intrinsic::x86_avx2_psrli_d:
12359     case Intrinsic::x86_avx2_psrli_q:
12360       Opcode = X86ISD::VSRLI;
12361       break;
12362     case Intrinsic::x86_sse2_psrai_w:
12363     case Intrinsic::x86_sse2_psrai_d:
12364     case Intrinsic::x86_avx2_psrai_w:
12365     case Intrinsic::x86_avx2_psrai_d:
12366       Opcode = X86ISD::VSRAI;
12367       break;
12368     }
12369     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12370                                Op.getOperand(1), Op.getOperand(2), DAG);
12371   }
12372
12373   case Intrinsic::x86_sse42_pcmpistria128:
12374   case Intrinsic::x86_sse42_pcmpestria128:
12375   case Intrinsic::x86_sse42_pcmpistric128:
12376   case Intrinsic::x86_sse42_pcmpestric128:
12377   case Intrinsic::x86_sse42_pcmpistrio128:
12378   case Intrinsic::x86_sse42_pcmpestrio128:
12379   case Intrinsic::x86_sse42_pcmpistris128:
12380   case Intrinsic::x86_sse42_pcmpestris128:
12381   case Intrinsic::x86_sse42_pcmpistriz128:
12382   case Intrinsic::x86_sse42_pcmpestriz128: {
12383     unsigned Opcode;
12384     unsigned X86CC;
12385     switch (IntNo) {
12386     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12387     case Intrinsic::x86_sse42_pcmpistria128:
12388       Opcode = X86ISD::PCMPISTRI;
12389       X86CC = X86::COND_A;
12390       break;
12391     case Intrinsic::x86_sse42_pcmpestria128:
12392       Opcode = X86ISD::PCMPESTRI;
12393       X86CC = X86::COND_A;
12394       break;
12395     case Intrinsic::x86_sse42_pcmpistric128:
12396       Opcode = X86ISD::PCMPISTRI;
12397       X86CC = X86::COND_B;
12398       break;
12399     case Intrinsic::x86_sse42_pcmpestric128:
12400       Opcode = X86ISD::PCMPESTRI;
12401       X86CC = X86::COND_B;
12402       break;
12403     case Intrinsic::x86_sse42_pcmpistrio128:
12404       Opcode = X86ISD::PCMPISTRI;
12405       X86CC = X86::COND_O;
12406       break;
12407     case Intrinsic::x86_sse42_pcmpestrio128:
12408       Opcode = X86ISD::PCMPESTRI;
12409       X86CC = X86::COND_O;
12410       break;
12411     case Intrinsic::x86_sse42_pcmpistris128:
12412       Opcode = X86ISD::PCMPISTRI;
12413       X86CC = X86::COND_S;
12414       break;
12415     case Intrinsic::x86_sse42_pcmpestris128:
12416       Opcode = X86ISD::PCMPESTRI;
12417       X86CC = X86::COND_S;
12418       break;
12419     case Intrinsic::x86_sse42_pcmpistriz128:
12420       Opcode = X86ISD::PCMPISTRI;
12421       X86CC = X86::COND_E;
12422       break;
12423     case Intrinsic::x86_sse42_pcmpestriz128:
12424       Opcode = X86ISD::PCMPESTRI;
12425       X86CC = X86::COND_E;
12426       break;
12427     }
12428     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12429     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12430     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12431     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12432                                 DAG.getConstant(X86CC, MVT::i8),
12433                                 SDValue(PCMP.getNode(), 1));
12434     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12435   }
12436
12437   case Intrinsic::x86_sse42_pcmpistri128:
12438   case Intrinsic::x86_sse42_pcmpestri128: {
12439     unsigned Opcode;
12440     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12441       Opcode = X86ISD::PCMPISTRI;
12442     else
12443       Opcode = X86ISD::PCMPESTRI;
12444
12445     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12446     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12447     return DAG.getNode(Opcode, dl, VTs, NewOps);
12448   }
12449   case Intrinsic::x86_fma_vfmadd_ps:
12450   case Intrinsic::x86_fma_vfmadd_pd:
12451   case Intrinsic::x86_fma_vfmsub_ps:
12452   case Intrinsic::x86_fma_vfmsub_pd:
12453   case Intrinsic::x86_fma_vfnmadd_ps:
12454   case Intrinsic::x86_fma_vfnmadd_pd:
12455   case Intrinsic::x86_fma_vfnmsub_ps:
12456   case Intrinsic::x86_fma_vfnmsub_pd:
12457   case Intrinsic::x86_fma_vfmaddsub_ps:
12458   case Intrinsic::x86_fma_vfmaddsub_pd:
12459   case Intrinsic::x86_fma_vfmsubadd_ps:
12460   case Intrinsic::x86_fma_vfmsubadd_pd:
12461   case Intrinsic::x86_fma_vfmadd_ps_256:
12462   case Intrinsic::x86_fma_vfmadd_pd_256:
12463   case Intrinsic::x86_fma_vfmsub_ps_256:
12464   case Intrinsic::x86_fma_vfmsub_pd_256:
12465   case Intrinsic::x86_fma_vfnmadd_ps_256:
12466   case Intrinsic::x86_fma_vfnmadd_pd_256:
12467   case Intrinsic::x86_fma_vfnmsub_ps_256:
12468   case Intrinsic::x86_fma_vfnmsub_pd_256:
12469   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12470   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12471   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12472   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12473   case Intrinsic::x86_fma_vfmadd_ps_512:
12474   case Intrinsic::x86_fma_vfmadd_pd_512:
12475   case Intrinsic::x86_fma_vfmsub_ps_512:
12476   case Intrinsic::x86_fma_vfmsub_pd_512:
12477   case Intrinsic::x86_fma_vfnmadd_ps_512:
12478   case Intrinsic::x86_fma_vfnmadd_pd_512:
12479   case Intrinsic::x86_fma_vfnmsub_ps_512:
12480   case Intrinsic::x86_fma_vfnmsub_pd_512:
12481   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12482   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12483   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12484   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12485     unsigned Opc;
12486     switch (IntNo) {
12487     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12488     case Intrinsic::x86_fma_vfmadd_ps:
12489     case Intrinsic::x86_fma_vfmadd_pd:
12490     case Intrinsic::x86_fma_vfmadd_ps_256:
12491     case Intrinsic::x86_fma_vfmadd_pd_256:
12492     case Intrinsic::x86_fma_vfmadd_ps_512:
12493     case Intrinsic::x86_fma_vfmadd_pd_512:
12494       Opc = X86ISD::FMADD;
12495       break;
12496     case Intrinsic::x86_fma_vfmsub_ps:
12497     case Intrinsic::x86_fma_vfmsub_pd:
12498     case Intrinsic::x86_fma_vfmsub_ps_256:
12499     case Intrinsic::x86_fma_vfmsub_pd_256:
12500     case Intrinsic::x86_fma_vfmsub_ps_512:
12501     case Intrinsic::x86_fma_vfmsub_pd_512:
12502       Opc = X86ISD::FMSUB;
12503       break;
12504     case Intrinsic::x86_fma_vfnmadd_ps:
12505     case Intrinsic::x86_fma_vfnmadd_pd:
12506     case Intrinsic::x86_fma_vfnmadd_ps_256:
12507     case Intrinsic::x86_fma_vfnmadd_pd_256:
12508     case Intrinsic::x86_fma_vfnmadd_ps_512:
12509     case Intrinsic::x86_fma_vfnmadd_pd_512:
12510       Opc = X86ISD::FNMADD;
12511       break;
12512     case Intrinsic::x86_fma_vfnmsub_ps:
12513     case Intrinsic::x86_fma_vfnmsub_pd:
12514     case Intrinsic::x86_fma_vfnmsub_ps_256:
12515     case Intrinsic::x86_fma_vfnmsub_pd_256:
12516     case Intrinsic::x86_fma_vfnmsub_ps_512:
12517     case Intrinsic::x86_fma_vfnmsub_pd_512:
12518       Opc = X86ISD::FNMSUB;
12519       break;
12520     case Intrinsic::x86_fma_vfmaddsub_ps:
12521     case Intrinsic::x86_fma_vfmaddsub_pd:
12522     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12523     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12524     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12525     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12526       Opc = X86ISD::FMADDSUB;
12527       break;
12528     case Intrinsic::x86_fma_vfmsubadd_ps:
12529     case Intrinsic::x86_fma_vfmsubadd_pd:
12530     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12531     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12532     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12533     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12534       Opc = X86ISD::FMSUBADD;
12535       break;
12536     }
12537
12538     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12539                        Op.getOperand(2), Op.getOperand(3));
12540   }
12541   }
12542 }
12543
12544 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12545                               SDValue Src, SDValue Mask, SDValue Base,
12546                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12547                               const X86Subtarget * Subtarget) {
12548   SDLoc dl(Op);
12549   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12550   assert(C && "Invalid scale type");
12551   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12552   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12553                              Index.getSimpleValueType().getVectorNumElements());
12554   SDValue MaskInReg;
12555   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12556   if (MaskC)
12557     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12558   else
12559     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12560   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12561   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12562   SDValue Segment = DAG.getRegister(0, MVT::i32);
12563   if (Src.getOpcode() == ISD::UNDEF)
12564     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12565   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12566   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12567   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12568   return DAG.getMergeValues(RetOps, dl);
12569 }
12570
12571 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12572                                SDValue Src, SDValue Mask, SDValue Base,
12573                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12574   SDLoc dl(Op);
12575   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12576   assert(C && "Invalid scale type");
12577   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12578   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12579   SDValue Segment = DAG.getRegister(0, MVT::i32);
12580   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12581                              Index.getSimpleValueType().getVectorNumElements());
12582   SDValue MaskInReg;
12583   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12584   if (MaskC)
12585     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12586   else
12587     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12588   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12589   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12590   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12591   return SDValue(Res, 1);
12592 }
12593
12594 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12595                                SDValue Mask, SDValue Base, SDValue Index,
12596                                SDValue ScaleOp, SDValue Chain) {
12597   SDLoc dl(Op);
12598   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12599   assert(C && "Invalid scale type");
12600   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12601   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12602   SDValue Segment = DAG.getRegister(0, MVT::i32);
12603   EVT MaskVT =
12604     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12605   SDValue MaskInReg;
12606   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12607   if (MaskC)
12608     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12609   else
12610     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12611   //SDVTList VTs = DAG.getVTList(MVT::Other);
12612   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12613   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12614   return SDValue(Res, 0);
12615 }
12616
12617 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12618 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12619 // also used to custom lower READCYCLECOUNTER nodes.
12620 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12621                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12622                               SmallVectorImpl<SDValue> &Results) {
12623   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12624   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12625   SDValue LO, HI;
12626
12627   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12628   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12629   // and the EAX register is loaded with the low-order 32 bits.
12630   if (Subtarget->is64Bit()) {
12631     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12632     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12633                             LO.getValue(2));
12634   } else {
12635     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12636     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12637                             LO.getValue(2));
12638   }
12639   SDValue Chain = HI.getValue(1);
12640
12641   if (Opcode == X86ISD::RDTSCP_DAG) {
12642     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12643
12644     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12645     // the ECX register. Add 'ecx' explicitly to the chain.
12646     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12647                                      HI.getValue(2));
12648     // Explicitly store the content of ECX at the location passed in input
12649     // to the 'rdtscp' intrinsic.
12650     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12651                          MachinePointerInfo(), false, false, 0);
12652   }
12653
12654   if (Subtarget->is64Bit()) {
12655     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12656     // the EAX register is loaded with the low-order 32 bits.
12657     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12658                               DAG.getConstant(32, MVT::i8));
12659     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12660     Results.push_back(Chain);
12661     return;
12662   }
12663
12664   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12665   SDValue Ops[] = { LO, HI };
12666   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12667   Results.push_back(Pair);
12668   Results.push_back(Chain);
12669 }
12670
12671 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12672                                      SelectionDAG &DAG) {
12673   SmallVector<SDValue, 2> Results;
12674   SDLoc DL(Op);
12675   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12676                           Results);
12677   return DAG.getMergeValues(Results, DL);
12678 }
12679
12680 enum IntrinsicType {
12681   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12682 };
12683
12684 struct IntrinsicData {
12685   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12686     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12687   IntrinsicType Type;
12688   unsigned      Opc0;
12689   unsigned      Opc1;
12690 };
12691
12692 std::map < unsigned, IntrinsicData> IntrMap;
12693 static void InitIntinsicsMap() {
12694   static bool Initialized = false;
12695   if (Initialized) 
12696     return;
12697   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12698                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12699   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12700                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12701   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12702                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12703   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12704                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12705   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12706                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12707   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12708                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12709   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12710                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12711   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12712                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12713   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12714                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12715
12716   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12717                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12718   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12719                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12720   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12721                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12722   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12723                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12724   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12725                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12726   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12727                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12728   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
12729                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12730   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
12731                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12732    
12733   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
12734                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12735                                                         X86::VGATHERPF1QPSm)));
12736   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
12737                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12738                                                         X86::VGATHERPF1QPDm)));
12739   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
12740                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12741                                                         X86::VGATHERPF1DPDm)));
12742   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
12743                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12744                                                         X86::VGATHERPF1DPSm)));
12745   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
12746                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12747                                                         X86::VSCATTERPF1QPSm)));
12748   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
12749                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12750                                                         X86::VSCATTERPF1QPDm)));
12751   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
12752                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12753                                                         X86::VSCATTERPF1DPDm)));
12754   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
12755                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12756                                                         X86::VSCATTERPF1DPSm)));
12757   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12758                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12759   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12760                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12761   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12762                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12763   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12764                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12765   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12766                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12767   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12768                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12769   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12770                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
12771   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12772                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
12773   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12774                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
12775   Initialized = true;
12776 }
12777
12778 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12779                                       SelectionDAG &DAG) {
12780   InitIntinsicsMap();
12781   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12782   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12783   if (itr == IntrMap.end())
12784     return SDValue();
12785
12786   SDLoc dl(Op);
12787   IntrinsicData Intr = itr->second;
12788   switch(Intr.Type) {
12789   case RDSEED:
12790   case RDRAND: {
12791     // Emit the node with the right value type.
12792     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12793     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12794
12795     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12796     // Otherwise return the value from Rand, which is always 0, casted to i32.
12797     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12798                       DAG.getConstant(1, Op->getValueType(1)),
12799                       DAG.getConstant(X86::COND_B, MVT::i32),
12800                       SDValue(Result.getNode(), 1) };
12801     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12802                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12803                                   Ops);
12804
12805     // Return { result, isValid, chain }.
12806     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12807                        SDValue(Result.getNode(), 2));
12808   }
12809   case GATHER: {
12810   //gather(v1, mask, index, base, scale);
12811     SDValue Chain = Op.getOperand(0);
12812     SDValue Src   = Op.getOperand(2);
12813     SDValue Base  = Op.getOperand(3);
12814     SDValue Index = Op.getOperand(4);
12815     SDValue Mask  = Op.getOperand(5);
12816     SDValue Scale = Op.getOperand(6);
12817     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12818                           Subtarget);
12819   }
12820   case SCATTER: {
12821   //scatter(base, mask, index, v1, scale);
12822     SDValue Chain = Op.getOperand(0);
12823     SDValue Base  = Op.getOperand(2);
12824     SDValue Mask  = Op.getOperand(3);
12825     SDValue Index = Op.getOperand(4);
12826     SDValue Src   = Op.getOperand(5);
12827     SDValue Scale = Op.getOperand(6);
12828     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12829   }
12830   case PREFETCH: {
12831     SDValue Hint = Op.getOperand(6);
12832     unsigned HintVal;
12833     if (dyn_cast<ConstantSDNode> (Hint) == 0 ||
12834         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12835       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12836     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12837     SDValue Chain = Op.getOperand(0);
12838     SDValue Mask  = Op.getOperand(2);
12839     SDValue Index = Op.getOperand(3);
12840     SDValue Base  = Op.getOperand(4);
12841     SDValue Scale = Op.getOperand(5);
12842     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12843   }
12844   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12845   case RDTSC: {
12846     SmallVector<SDValue, 2> Results;
12847     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12848     return DAG.getMergeValues(Results, dl);
12849   }
12850   // XTEST intrinsics.
12851   case XTEST: {
12852     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12853     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12854     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12855                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12856                                 InTrans);
12857     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12858     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12859                        Ret, SDValue(InTrans.getNode(), 1));
12860   }
12861   }
12862   llvm_unreachable("Unknown Intrinsic Type");
12863 }
12864
12865 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12866                                            SelectionDAG &DAG) const {
12867   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12868   MFI->setReturnAddressIsTaken(true);
12869
12870   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12871     return SDValue();
12872
12873   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12874   SDLoc dl(Op);
12875   EVT PtrVT = getPointerTy();
12876
12877   if (Depth > 0) {
12878     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12879     const X86RegisterInfo *RegInfo =
12880       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12881     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12882     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12883                        DAG.getNode(ISD::ADD, dl, PtrVT,
12884                                    FrameAddr, Offset),
12885                        MachinePointerInfo(), false, false, false, 0);
12886   }
12887
12888   // Just load the return address.
12889   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12890   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12891                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12892 }
12893
12894 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12895   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12896   MFI->setFrameAddressIsTaken(true);
12897
12898   EVT VT = Op.getValueType();
12899   SDLoc dl(Op);  // FIXME probably not meaningful
12900   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12901   const X86RegisterInfo *RegInfo =
12902     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12903   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12904   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12905           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12906          "Invalid Frame Register!");
12907   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12908   while (Depth--)
12909     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12910                             MachinePointerInfo(),
12911                             false, false, false, 0);
12912   return FrameAddr;
12913 }
12914
12915 // FIXME? Maybe this could be a TableGen attribute on some registers and
12916 // this table could be generated automatically from RegInfo.
12917 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12918                                               EVT VT) const {
12919   unsigned Reg = StringSwitch<unsigned>(RegName)
12920                        .Case("esp", X86::ESP)
12921                        .Case("rsp", X86::RSP)
12922                        .Default(0);
12923   if (Reg)
12924     return Reg;
12925   report_fatal_error("Invalid register name global variable");
12926 }
12927
12928 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12929                                                      SelectionDAG &DAG) const {
12930   const X86RegisterInfo *RegInfo =
12931     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12932   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12933 }
12934
12935 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12936   SDValue Chain     = Op.getOperand(0);
12937   SDValue Offset    = Op.getOperand(1);
12938   SDValue Handler   = Op.getOperand(2);
12939   SDLoc dl      (Op);
12940
12941   EVT PtrVT = getPointerTy();
12942   const X86RegisterInfo *RegInfo =
12943     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12944   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12945   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12946           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12947          "Invalid Frame Register!");
12948   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12949   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12950
12951   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12952                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12953   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12954   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12955                        false, false, 0);
12956   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12957
12958   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12959                      DAG.getRegister(StoreAddrReg, PtrVT));
12960 }
12961
12962 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12963                                                SelectionDAG &DAG) const {
12964   SDLoc DL(Op);
12965   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12966                      DAG.getVTList(MVT::i32, MVT::Other),
12967                      Op.getOperand(0), Op.getOperand(1));
12968 }
12969
12970 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12971                                                 SelectionDAG &DAG) const {
12972   SDLoc DL(Op);
12973   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12974                      Op.getOperand(0), Op.getOperand(1));
12975 }
12976
12977 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12978   return Op.getOperand(0);
12979 }
12980
12981 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12982                                                 SelectionDAG &DAG) const {
12983   SDValue Root = Op.getOperand(0);
12984   SDValue Trmp = Op.getOperand(1); // trampoline
12985   SDValue FPtr = Op.getOperand(2); // nested function
12986   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12987   SDLoc dl (Op);
12988
12989   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12990   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12991
12992   if (Subtarget->is64Bit()) {
12993     SDValue OutChains[6];
12994
12995     // Large code-model.
12996     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12997     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12998
12999     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13000     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13001
13002     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13003
13004     // Load the pointer to the nested function into R11.
13005     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13006     SDValue Addr = Trmp;
13007     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13008                                 Addr, MachinePointerInfo(TrmpAddr),
13009                                 false, false, 0);
13010
13011     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13012                        DAG.getConstant(2, MVT::i64));
13013     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13014                                 MachinePointerInfo(TrmpAddr, 2),
13015                                 false, false, 2);
13016
13017     // Load the 'nest' parameter value into R10.
13018     // R10 is specified in X86CallingConv.td
13019     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13020     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13021                        DAG.getConstant(10, MVT::i64));
13022     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13023                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13024                                 false, false, 0);
13025
13026     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13027                        DAG.getConstant(12, MVT::i64));
13028     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13029                                 MachinePointerInfo(TrmpAddr, 12),
13030                                 false, false, 2);
13031
13032     // Jump to the nested function.
13033     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13034     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13035                        DAG.getConstant(20, MVT::i64));
13036     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13037                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13038                                 false, false, 0);
13039
13040     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13041     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13042                        DAG.getConstant(22, MVT::i64));
13043     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13044                                 MachinePointerInfo(TrmpAddr, 22),
13045                                 false, false, 0);
13046
13047     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13048   } else {
13049     const Function *Func =
13050       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13051     CallingConv::ID CC = Func->getCallingConv();
13052     unsigned NestReg;
13053
13054     switch (CC) {
13055     default:
13056       llvm_unreachable("Unsupported calling convention");
13057     case CallingConv::C:
13058     case CallingConv::X86_StdCall: {
13059       // Pass 'nest' parameter in ECX.
13060       // Must be kept in sync with X86CallingConv.td
13061       NestReg = X86::ECX;
13062
13063       // Check that ECX wasn't needed by an 'inreg' parameter.
13064       FunctionType *FTy = Func->getFunctionType();
13065       const AttributeSet &Attrs = Func->getAttributes();
13066
13067       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13068         unsigned InRegCount = 0;
13069         unsigned Idx = 1;
13070
13071         for (FunctionType::param_iterator I = FTy->param_begin(),
13072              E = FTy->param_end(); I != E; ++I, ++Idx)
13073           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13074             // FIXME: should only count parameters that are lowered to integers.
13075             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13076
13077         if (InRegCount > 2) {
13078           report_fatal_error("Nest register in use - reduce number of inreg"
13079                              " parameters!");
13080         }
13081       }
13082       break;
13083     }
13084     case CallingConv::X86_FastCall:
13085     case CallingConv::X86_ThisCall:
13086     case CallingConv::Fast:
13087       // Pass 'nest' parameter in EAX.
13088       // Must be kept in sync with X86CallingConv.td
13089       NestReg = X86::EAX;
13090       break;
13091     }
13092
13093     SDValue OutChains[4];
13094     SDValue Addr, Disp;
13095
13096     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13097                        DAG.getConstant(10, MVT::i32));
13098     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13099
13100     // This is storing the opcode for MOV32ri.
13101     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13102     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13103     OutChains[0] = DAG.getStore(Root, dl,
13104                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13105                                 Trmp, MachinePointerInfo(TrmpAddr),
13106                                 false, false, 0);
13107
13108     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13109                        DAG.getConstant(1, MVT::i32));
13110     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13111                                 MachinePointerInfo(TrmpAddr, 1),
13112                                 false, false, 1);
13113
13114     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13115     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13116                        DAG.getConstant(5, MVT::i32));
13117     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13118                                 MachinePointerInfo(TrmpAddr, 5),
13119                                 false, false, 1);
13120
13121     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13122                        DAG.getConstant(6, MVT::i32));
13123     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13124                                 MachinePointerInfo(TrmpAddr, 6),
13125                                 false, false, 1);
13126
13127     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13128   }
13129 }
13130
13131 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13132                                             SelectionDAG &DAG) const {
13133   /*
13134    The rounding mode is in bits 11:10 of FPSR, and has the following
13135    settings:
13136      00 Round to nearest
13137      01 Round to -inf
13138      10 Round to +inf
13139      11 Round to 0
13140
13141   FLT_ROUNDS, on the other hand, expects the following:
13142     -1 Undefined
13143      0 Round to 0
13144      1 Round to nearest
13145      2 Round to +inf
13146      3 Round to -inf
13147
13148   To perform the conversion, we do:
13149     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13150   */
13151
13152   MachineFunction &MF = DAG.getMachineFunction();
13153   const TargetMachine &TM = MF.getTarget();
13154   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13155   unsigned StackAlignment = TFI.getStackAlignment();
13156   MVT VT = Op.getSimpleValueType();
13157   SDLoc DL(Op);
13158
13159   // Save FP Control Word to stack slot
13160   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13161   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13162
13163   MachineMemOperand *MMO =
13164    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13165                            MachineMemOperand::MOStore, 2, 2);
13166
13167   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13168   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13169                                           DAG.getVTList(MVT::Other),
13170                                           Ops, MVT::i16, MMO);
13171
13172   // Load FP Control Word from stack slot
13173   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13174                             MachinePointerInfo(), false, false, false, 0);
13175
13176   // Transform as necessary
13177   SDValue CWD1 =
13178     DAG.getNode(ISD::SRL, DL, MVT::i16,
13179                 DAG.getNode(ISD::AND, DL, MVT::i16,
13180                             CWD, DAG.getConstant(0x800, MVT::i16)),
13181                 DAG.getConstant(11, MVT::i8));
13182   SDValue CWD2 =
13183     DAG.getNode(ISD::SRL, DL, MVT::i16,
13184                 DAG.getNode(ISD::AND, DL, MVT::i16,
13185                             CWD, DAG.getConstant(0x400, MVT::i16)),
13186                 DAG.getConstant(9, MVT::i8));
13187
13188   SDValue RetVal =
13189     DAG.getNode(ISD::AND, DL, MVT::i16,
13190                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13191                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13192                             DAG.getConstant(1, MVT::i16)),
13193                 DAG.getConstant(3, MVT::i16));
13194
13195   return DAG.getNode((VT.getSizeInBits() < 16 ?
13196                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13197 }
13198
13199 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13200   MVT VT = Op.getSimpleValueType();
13201   EVT OpVT = VT;
13202   unsigned NumBits = VT.getSizeInBits();
13203   SDLoc dl(Op);
13204
13205   Op = Op.getOperand(0);
13206   if (VT == MVT::i8) {
13207     // Zero extend to i32 since there is not an i8 bsr.
13208     OpVT = MVT::i32;
13209     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13210   }
13211
13212   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13213   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13214   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13215
13216   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13217   SDValue Ops[] = {
13218     Op,
13219     DAG.getConstant(NumBits+NumBits-1, OpVT),
13220     DAG.getConstant(X86::COND_E, MVT::i8),
13221     Op.getValue(1)
13222   };
13223   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13224
13225   // Finally xor with NumBits-1.
13226   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13227
13228   if (VT == MVT::i8)
13229     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13230   return Op;
13231 }
13232
13233 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13234   MVT VT = Op.getSimpleValueType();
13235   EVT OpVT = VT;
13236   unsigned NumBits = VT.getSizeInBits();
13237   SDLoc dl(Op);
13238
13239   Op = Op.getOperand(0);
13240   if (VT == MVT::i8) {
13241     // Zero extend to i32 since there is not an i8 bsr.
13242     OpVT = MVT::i32;
13243     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13244   }
13245
13246   // Issue a bsr (scan bits in reverse).
13247   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13248   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13249
13250   // And xor with NumBits-1.
13251   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13252
13253   if (VT == MVT::i8)
13254     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13255   return Op;
13256 }
13257
13258 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13259   MVT VT = Op.getSimpleValueType();
13260   unsigned NumBits = VT.getSizeInBits();
13261   SDLoc dl(Op);
13262   Op = Op.getOperand(0);
13263
13264   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13265   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13266   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13267
13268   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13269   SDValue Ops[] = {
13270     Op,
13271     DAG.getConstant(NumBits, VT),
13272     DAG.getConstant(X86::COND_E, MVT::i8),
13273     Op.getValue(1)
13274   };
13275   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13276 }
13277
13278 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13279 // ones, and then concatenate the result back.
13280 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13281   MVT VT = Op.getSimpleValueType();
13282
13283   assert(VT.is256BitVector() && VT.isInteger() &&
13284          "Unsupported value type for operation");
13285
13286   unsigned NumElems = VT.getVectorNumElements();
13287   SDLoc dl(Op);
13288
13289   // Extract the LHS vectors
13290   SDValue LHS = Op.getOperand(0);
13291   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13292   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13293
13294   // Extract the RHS vectors
13295   SDValue RHS = Op.getOperand(1);
13296   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13297   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13298
13299   MVT EltVT = VT.getVectorElementType();
13300   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13301
13302   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13303                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13304                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13305 }
13306
13307 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13308   assert(Op.getSimpleValueType().is256BitVector() &&
13309          Op.getSimpleValueType().isInteger() &&
13310          "Only handle AVX 256-bit vector integer operation");
13311   return Lower256IntArith(Op, DAG);
13312 }
13313
13314 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13315   assert(Op.getSimpleValueType().is256BitVector() &&
13316          Op.getSimpleValueType().isInteger() &&
13317          "Only handle AVX 256-bit vector integer operation");
13318   return Lower256IntArith(Op, DAG);
13319 }
13320
13321 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13322                         SelectionDAG &DAG) {
13323   SDLoc dl(Op);
13324   MVT VT = Op.getSimpleValueType();
13325
13326   // Decompose 256-bit ops into smaller 128-bit ops.
13327   if (VT.is256BitVector() && !Subtarget->hasInt256())
13328     return Lower256IntArith(Op, DAG);
13329
13330   SDValue A = Op.getOperand(0);
13331   SDValue B = Op.getOperand(1);
13332
13333   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13334   if (VT == MVT::v4i32) {
13335     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13336            "Should not custom lower when pmuldq is available!");
13337
13338     // Extract the odd parts.
13339     static const int UnpackMask[] = { 1, -1, 3, -1 };
13340     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13341     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13342
13343     // Multiply the even parts.
13344     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13345     // Now multiply odd parts.
13346     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13347
13348     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13349     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13350
13351     // Merge the two vectors back together with a shuffle. This expands into 2
13352     // shuffles.
13353     static const int ShufMask[] = { 0, 4, 2, 6 };
13354     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13355   }
13356
13357   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13358          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13359
13360   //  Ahi = psrlqi(a, 32);
13361   //  Bhi = psrlqi(b, 32);
13362   //
13363   //  AloBlo = pmuludq(a, b);
13364   //  AloBhi = pmuludq(a, Bhi);
13365   //  AhiBlo = pmuludq(Ahi, b);
13366
13367   //  AloBhi = psllqi(AloBhi, 32);
13368   //  AhiBlo = psllqi(AhiBlo, 32);
13369   //  return AloBlo + AloBhi + AhiBlo;
13370
13371   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13372   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13373
13374   // Bit cast to 32-bit vectors for MULUDQ
13375   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13376                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13377   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13378   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13379   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13380   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13381
13382   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13383   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13384   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13385
13386   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13387   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13388
13389   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13390   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13391 }
13392
13393 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13394   assert(Subtarget->isTargetWin64() && "Unexpected target");
13395   EVT VT = Op.getValueType();
13396   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13397          "Unexpected return type for lowering");
13398
13399   RTLIB::Libcall LC;
13400   bool isSigned;
13401   switch (Op->getOpcode()) {
13402   default: llvm_unreachable("Unexpected request for libcall!");
13403   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13404   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13405   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13406   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13407   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13408   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13409   }
13410
13411   SDLoc dl(Op);
13412   SDValue InChain = DAG.getEntryNode();
13413
13414   TargetLowering::ArgListTy Args;
13415   TargetLowering::ArgListEntry Entry;
13416   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13417     EVT ArgVT = Op->getOperand(i).getValueType();
13418     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13419            "Unexpected argument type for lowering");
13420     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13421     Entry.Node = StackPtr;
13422     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13423                            false, false, 16);
13424     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13425     Entry.Ty = PointerType::get(ArgTy,0);
13426     Entry.isSExt = false;
13427     Entry.isZExt = false;
13428     Args.push_back(Entry);
13429   }
13430
13431   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13432                                          getPointerTy());
13433
13434   TargetLowering::CallLoweringInfo CLI(DAG);
13435   CLI.setDebugLoc(dl).setChain(InChain)
13436     .setCallee(getLibcallCallingConv(LC),
13437                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13438                Callee, &Args, 0)
13439     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13440
13441   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13442   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13443 }
13444
13445 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13446                              SelectionDAG &DAG) {
13447   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13448   EVT VT = Op0.getValueType();
13449   SDLoc dl(Op);
13450
13451   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13452          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13453
13454   // Get the high parts.
13455   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13456   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13457   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13458
13459   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13460   // ints.
13461   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13462   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13463   unsigned Opcode =
13464       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13465   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13466                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13467   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13468                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13469
13470   // Shuffle it back into the right order.
13471   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13472   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13473   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13474   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13475
13476   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13477   // unsigned multiply.
13478   if (IsSigned && !Subtarget->hasSSE41()) {
13479     SDValue ShAmt =
13480         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13481     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13482                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13483     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13484                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13485
13486     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13487     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13488   }
13489
13490   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13491 }
13492
13493 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13494                                          const X86Subtarget *Subtarget) {
13495   MVT VT = Op.getSimpleValueType();
13496   SDLoc dl(Op);
13497   SDValue R = Op.getOperand(0);
13498   SDValue Amt = Op.getOperand(1);
13499
13500   // Optimize shl/srl/sra with constant shift amount.
13501   if (isSplatVector(Amt.getNode())) {
13502     SDValue SclrAmt = Amt->getOperand(0);
13503     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13504       uint64_t ShiftAmt = C->getZExtValue();
13505
13506       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13507           (Subtarget->hasInt256() &&
13508            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13509           (Subtarget->hasAVX512() &&
13510            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13511         if (Op.getOpcode() == ISD::SHL)
13512           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13513                                             DAG);
13514         if (Op.getOpcode() == ISD::SRL)
13515           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13516                                             DAG);
13517         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13518           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13519                                             DAG);
13520       }
13521
13522       if (VT == MVT::v16i8) {
13523         if (Op.getOpcode() == ISD::SHL) {
13524           // Make a large shift.
13525           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13526                                                    MVT::v8i16, R, ShiftAmt,
13527                                                    DAG);
13528           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13529           // Zero out the rightmost bits.
13530           SmallVector<SDValue, 16> V(16,
13531                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13532                                                      MVT::i8));
13533           return DAG.getNode(ISD::AND, dl, VT, SHL,
13534                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13535         }
13536         if (Op.getOpcode() == ISD::SRL) {
13537           // Make a large shift.
13538           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13539                                                    MVT::v8i16, R, ShiftAmt,
13540                                                    DAG);
13541           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13542           // Zero out the leftmost bits.
13543           SmallVector<SDValue, 16> V(16,
13544                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13545                                                      MVT::i8));
13546           return DAG.getNode(ISD::AND, dl, VT, SRL,
13547                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13548         }
13549         if (Op.getOpcode() == ISD::SRA) {
13550           if (ShiftAmt == 7) {
13551             // R s>> 7  ===  R s< 0
13552             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13553             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13554           }
13555
13556           // R s>> a === ((R u>> a) ^ m) - m
13557           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13558           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13559                                                          MVT::i8));
13560           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13561           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13562           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13563           return Res;
13564         }
13565         llvm_unreachable("Unknown shift opcode.");
13566       }
13567
13568       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13569         if (Op.getOpcode() == ISD::SHL) {
13570           // Make a large shift.
13571           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13572                                                    MVT::v16i16, R, ShiftAmt,
13573                                                    DAG);
13574           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13575           // Zero out the rightmost bits.
13576           SmallVector<SDValue, 32> V(32,
13577                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13578                                                      MVT::i8));
13579           return DAG.getNode(ISD::AND, dl, VT, SHL,
13580                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13581         }
13582         if (Op.getOpcode() == ISD::SRL) {
13583           // Make a large shift.
13584           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13585                                                    MVT::v16i16, R, ShiftAmt,
13586                                                    DAG);
13587           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13588           // Zero out the leftmost bits.
13589           SmallVector<SDValue, 32> V(32,
13590                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13591                                                      MVT::i8));
13592           return DAG.getNode(ISD::AND, dl, VT, SRL,
13593                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13594         }
13595         if (Op.getOpcode() == ISD::SRA) {
13596           if (ShiftAmt == 7) {
13597             // R s>> 7  ===  R s< 0
13598             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13599             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13600           }
13601
13602           // R s>> a === ((R u>> a) ^ m) - m
13603           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13604           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13605                                                          MVT::i8));
13606           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13607           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13608           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13609           return Res;
13610         }
13611         llvm_unreachable("Unknown shift opcode.");
13612       }
13613     }
13614   }
13615
13616   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13617   if (!Subtarget->is64Bit() &&
13618       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13619       Amt.getOpcode() == ISD::BITCAST &&
13620       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13621     Amt = Amt.getOperand(0);
13622     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13623                      VT.getVectorNumElements();
13624     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13625     uint64_t ShiftAmt = 0;
13626     for (unsigned i = 0; i != Ratio; ++i) {
13627       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13628       if (!C)
13629         return SDValue();
13630       // 6 == Log2(64)
13631       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13632     }
13633     // Check remaining shift amounts.
13634     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13635       uint64_t ShAmt = 0;
13636       for (unsigned j = 0; j != Ratio; ++j) {
13637         ConstantSDNode *C =
13638           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13639         if (!C)
13640           return SDValue();
13641         // 6 == Log2(64)
13642         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13643       }
13644       if (ShAmt != ShiftAmt)
13645         return SDValue();
13646     }
13647     switch (Op.getOpcode()) {
13648     default:
13649       llvm_unreachable("Unknown shift opcode!");
13650     case ISD::SHL:
13651       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13652                                         DAG);
13653     case ISD::SRL:
13654       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13655                                         DAG);
13656     case ISD::SRA:
13657       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13658                                         DAG);
13659     }
13660   }
13661
13662   return SDValue();
13663 }
13664
13665 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13666                                         const X86Subtarget* Subtarget) {
13667   MVT VT = Op.getSimpleValueType();
13668   SDLoc dl(Op);
13669   SDValue R = Op.getOperand(0);
13670   SDValue Amt = Op.getOperand(1);
13671
13672   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13673       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13674       (Subtarget->hasInt256() &&
13675        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13676         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13677        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13678     SDValue BaseShAmt;
13679     EVT EltVT = VT.getVectorElementType();
13680
13681     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13682       unsigned NumElts = VT.getVectorNumElements();
13683       unsigned i, j;
13684       for (i = 0; i != NumElts; ++i) {
13685         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13686           continue;
13687         break;
13688       }
13689       for (j = i; j != NumElts; ++j) {
13690         SDValue Arg = Amt.getOperand(j);
13691         if (Arg.getOpcode() == ISD::UNDEF) continue;
13692         if (Arg != Amt.getOperand(i))
13693           break;
13694       }
13695       if (i != NumElts && j == NumElts)
13696         BaseShAmt = Amt.getOperand(i);
13697     } else {
13698       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13699         Amt = Amt.getOperand(0);
13700       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13701                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13702         SDValue InVec = Amt.getOperand(0);
13703         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13704           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13705           unsigned i = 0;
13706           for (; i != NumElts; ++i) {
13707             SDValue Arg = InVec.getOperand(i);
13708             if (Arg.getOpcode() == ISD::UNDEF) continue;
13709             BaseShAmt = Arg;
13710             break;
13711           }
13712         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13713            if (ConstantSDNode *C =
13714                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13715              unsigned SplatIdx =
13716                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13717              if (C->getZExtValue() == SplatIdx)
13718                BaseShAmt = InVec.getOperand(1);
13719            }
13720         }
13721         if (!BaseShAmt.getNode())
13722           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13723                                   DAG.getIntPtrConstant(0));
13724       }
13725     }
13726
13727     if (BaseShAmt.getNode()) {
13728       if (EltVT.bitsGT(MVT::i32))
13729         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13730       else if (EltVT.bitsLT(MVT::i32))
13731         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13732
13733       switch (Op.getOpcode()) {
13734       default:
13735         llvm_unreachable("Unknown shift opcode!");
13736       case ISD::SHL:
13737         switch (VT.SimpleTy) {
13738         default: return SDValue();
13739         case MVT::v2i64:
13740         case MVT::v4i32:
13741         case MVT::v8i16:
13742         case MVT::v4i64:
13743         case MVT::v8i32:
13744         case MVT::v16i16:
13745         case MVT::v16i32:
13746         case MVT::v8i64:
13747           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13748         }
13749       case ISD::SRA:
13750         switch (VT.SimpleTy) {
13751         default: return SDValue();
13752         case MVT::v4i32:
13753         case MVT::v8i16:
13754         case MVT::v8i32:
13755         case MVT::v16i16:
13756         case MVT::v16i32:
13757         case MVT::v8i64:
13758           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13759         }
13760       case ISD::SRL:
13761         switch (VT.SimpleTy) {
13762         default: return SDValue();
13763         case MVT::v2i64:
13764         case MVT::v4i32:
13765         case MVT::v8i16:
13766         case MVT::v4i64:
13767         case MVT::v8i32:
13768         case MVT::v16i16:
13769         case MVT::v16i32:
13770         case MVT::v8i64:
13771           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13772         }
13773       }
13774     }
13775   }
13776
13777   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13778   if (!Subtarget->is64Bit() &&
13779       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13780       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13781       Amt.getOpcode() == ISD::BITCAST &&
13782       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13783     Amt = Amt.getOperand(0);
13784     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13785                      VT.getVectorNumElements();
13786     std::vector<SDValue> Vals(Ratio);
13787     for (unsigned i = 0; i != Ratio; ++i)
13788       Vals[i] = Amt.getOperand(i);
13789     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13790       for (unsigned j = 0; j != Ratio; ++j)
13791         if (Vals[j] != Amt.getOperand(i + j))
13792           return SDValue();
13793     }
13794     switch (Op.getOpcode()) {
13795     default:
13796       llvm_unreachable("Unknown shift opcode!");
13797     case ISD::SHL:
13798       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13799     case ISD::SRL:
13800       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13801     case ISD::SRA:
13802       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13803     }
13804   }
13805
13806   return SDValue();
13807 }
13808
13809 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13810                           SelectionDAG &DAG) {
13811
13812   MVT VT = Op.getSimpleValueType();
13813   SDLoc dl(Op);
13814   SDValue R = Op.getOperand(0);
13815   SDValue Amt = Op.getOperand(1);
13816   SDValue V;
13817
13818   if (!Subtarget->hasSSE2())
13819     return SDValue();
13820
13821   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13822   if (V.getNode())
13823     return V;
13824
13825   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13826   if (V.getNode())
13827       return V;
13828
13829   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13830     return Op;
13831   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13832   if (Subtarget->hasInt256()) {
13833     if (Op.getOpcode() == ISD::SRL &&
13834         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13835          VT == MVT::v4i64 || VT == MVT::v8i32))
13836       return Op;
13837     if (Op.getOpcode() == ISD::SHL &&
13838         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13839          VT == MVT::v4i64 || VT == MVT::v8i32))
13840       return Op;
13841     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13842       return Op;
13843   }
13844
13845   // If possible, lower this packed shift into a vector multiply instead of
13846   // expanding it into a sequence of scalar shifts.
13847   // Do this only if the vector shift count is a constant build_vector.
13848   if (Op.getOpcode() == ISD::SHL && 
13849       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13850        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13851       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13852     SmallVector<SDValue, 8> Elts;
13853     EVT SVT = VT.getScalarType();
13854     unsigned SVTBits = SVT.getSizeInBits();
13855     const APInt &One = APInt(SVTBits, 1);
13856     unsigned NumElems = VT.getVectorNumElements();
13857
13858     for (unsigned i=0; i !=NumElems; ++i) {
13859       SDValue Op = Amt->getOperand(i);
13860       if (Op->getOpcode() == ISD::UNDEF) {
13861         Elts.push_back(Op);
13862         continue;
13863       }
13864
13865       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13866       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13867       uint64_t ShAmt = C.getZExtValue();
13868       if (ShAmt >= SVTBits) {
13869         Elts.push_back(DAG.getUNDEF(SVT));
13870         continue;
13871       }
13872       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13873     }
13874     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13875     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13876   }
13877
13878   // Lower SHL with variable shift amount.
13879   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13880     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13881
13882     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13883     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13884     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13885     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13886   }
13887
13888   // If possible, lower this shift as a sequence of two shifts by
13889   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13890   // Example:
13891   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13892   //
13893   // Could be rewritten as:
13894   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13895   //
13896   // The advantage is that the two shifts from the example would be
13897   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13898   // the vector shift into four scalar shifts plus four pairs of vector
13899   // insert/extract.
13900   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13901       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13902     unsigned TargetOpcode = X86ISD::MOVSS;
13903     bool CanBeSimplified;
13904     // The splat value for the first packed shift (the 'X' from the example).
13905     SDValue Amt1 = Amt->getOperand(0);
13906     // The splat value for the second packed shift (the 'Y' from the example).
13907     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13908                                         Amt->getOperand(2);
13909
13910     // See if it is possible to replace this node with a sequence of
13911     // two shifts followed by a MOVSS/MOVSD
13912     if (VT == MVT::v4i32) {
13913       // Check if it is legal to use a MOVSS.
13914       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13915                         Amt2 == Amt->getOperand(3);
13916       if (!CanBeSimplified) {
13917         // Otherwise, check if we can still simplify this node using a MOVSD.
13918         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13919                           Amt->getOperand(2) == Amt->getOperand(3);
13920         TargetOpcode = X86ISD::MOVSD;
13921         Amt2 = Amt->getOperand(2);
13922       }
13923     } else {
13924       // Do similar checks for the case where the machine value type
13925       // is MVT::v8i16.
13926       CanBeSimplified = Amt1 == Amt->getOperand(1);
13927       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13928         CanBeSimplified = Amt2 == Amt->getOperand(i);
13929
13930       if (!CanBeSimplified) {
13931         TargetOpcode = X86ISD::MOVSD;
13932         CanBeSimplified = true;
13933         Amt2 = Amt->getOperand(4);
13934         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13935           CanBeSimplified = Amt1 == Amt->getOperand(i);
13936         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13937           CanBeSimplified = Amt2 == Amt->getOperand(j);
13938       }
13939     }
13940     
13941     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13942         isa<ConstantSDNode>(Amt2)) {
13943       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13944       EVT CastVT = MVT::v4i32;
13945       SDValue Splat1 = 
13946         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13947       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13948       SDValue Splat2 = 
13949         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13950       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13951       if (TargetOpcode == X86ISD::MOVSD)
13952         CastVT = MVT::v2i64;
13953       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13954       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13955       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13956                                             BitCast1, DAG);
13957       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13958     }
13959   }
13960
13961   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13962     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13963
13964     // a = a << 5;
13965     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13966     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13967
13968     // Turn 'a' into a mask suitable for VSELECT
13969     SDValue VSelM = DAG.getConstant(0x80, VT);
13970     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13971     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13972
13973     SDValue CM1 = DAG.getConstant(0x0f, VT);
13974     SDValue CM2 = DAG.getConstant(0x3f, VT);
13975
13976     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13977     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13978     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13979     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13980     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13981
13982     // a += a
13983     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13984     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13985     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13986
13987     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13988     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13989     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13990     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13991     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13992
13993     // a += a
13994     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13995     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13996     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13997
13998     // return VSELECT(r, r+r, a);
13999     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14000                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14001     return R;
14002   }
14003
14004   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14005   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14006   // solution better.
14007   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14008     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14009     unsigned ExtOpc =
14010         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14011     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14012     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14013     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14014                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14015     }
14016
14017   // Decompose 256-bit shifts into smaller 128-bit shifts.
14018   if (VT.is256BitVector()) {
14019     unsigned NumElems = VT.getVectorNumElements();
14020     MVT EltVT = VT.getVectorElementType();
14021     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14022
14023     // Extract the two vectors
14024     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14025     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14026
14027     // Recreate the shift amount vectors
14028     SDValue Amt1, Amt2;
14029     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14030       // Constant shift amount
14031       SmallVector<SDValue, 4> Amt1Csts;
14032       SmallVector<SDValue, 4> Amt2Csts;
14033       for (unsigned i = 0; i != NumElems/2; ++i)
14034         Amt1Csts.push_back(Amt->getOperand(i));
14035       for (unsigned i = NumElems/2; i != NumElems; ++i)
14036         Amt2Csts.push_back(Amt->getOperand(i));
14037
14038       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14039       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14040     } else {
14041       // Variable shift amount
14042       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14043       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14044     }
14045
14046     // Issue new vector shifts for the smaller types
14047     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14048     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14049
14050     // Concatenate the result back
14051     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14052   }
14053
14054   return SDValue();
14055 }
14056
14057 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14058   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14059   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14060   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14061   // has only one use.
14062   SDNode *N = Op.getNode();
14063   SDValue LHS = N->getOperand(0);
14064   SDValue RHS = N->getOperand(1);
14065   unsigned BaseOp = 0;
14066   unsigned Cond = 0;
14067   SDLoc DL(Op);
14068   switch (Op.getOpcode()) {
14069   default: llvm_unreachable("Unknown ovf instruction!");
14070   case ISD::SADDO:
14071     // A subtract of one will be selected as a INC. Note that INC doesn't
14072     // set CF, so we can't do this for UADDO.
14073     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14074       if (C->isOne()) {
14075         BaseOp = X86ISD::INC;
14076         Cond = X86::COND_O;
14077         break;
14078       }
14079     BaseOp = X86ISD::ADD;
14080     Cond = X86::COND_O;
14081     break;
14082   case ISD::UADDO:
14083     BaseOp = X86ISD::ADD;
14084     Cond = X86::COND_B;
14085     break;
14086   case ISD::SSUBO:
14087     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14088     // set CF, so we can't do this for USUBO.
14089     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14090       if (C->isOne()) {
14091         BaseOp = X86ISD::DEC;
14092         Cond = X86::COND_O;
14093         break;
14094       }
14095     BaseOp = X86ISD::SUB;
14096     Cond = X86::COND_O;
14097     break;
14098   case ISD::USUBO:
14099     BaseOp = X86ISD::SUB;
14100     Cond = X86::COND_B;
14101     break;
14102   case ISD::SMULO:
14103     BaseOp = X86ISD::SMUL;
14104     Cond = X86::COND_O;
14105     break;
14106   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14107     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14108                                  MVT::i32);
14109     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14110
14111     SDValue SetCC =
14112       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14113                   DAG.getConstant(X86::COND_O, MVT::i32),
14114                   SDValue(Sum.getNode(), 2));
14115
14116     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14117   }
14118   }
14119
14120   // Also sets EFLAGS.
14121   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14122   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14123
14124   SDValue SetCC =
14125     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14126                 DAG.getConstant(Cond, MVT::i32),
14127                 SDValue(Sum.getNode(), 1));
14128
14129   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14130 }
14131
14132 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14133                                                   SelectionDAG &DAG) const {
14134   SDLoc dl(Op);
14135   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14136   MVT VT = Op.getSimpleValueType();
14137
14138   if (!Subtarget->hasSSE2() || !VT.isVector())
14139     return SDValue();
14140
14141   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14142                       ExtraVT.getScalarType().getSizeInBits();
14143
14144   switch (VT.SimpleTy) {
14145     default: return SDValue();
14146     case MVT::v8i32:
14147     case MVT::v16i16:
14148       if (!Subtarget->hasFp256())
14149         return SDValue();
14150       if (!Subtarget->hasInt256()) {
14151         // needs to be split
14152         unsigned NumElems = VT.getVectorNumElements();
14153
14154         // Extract the LHS vectors
14155         SDValue LHS = Op.getOperand(0);
14156         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14157         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14158
14159         MVT EltVT = VT.getVectorElementType();
14160         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14161
14162         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14163         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14164         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14165                                    ExtraNumElems/2);
14166         SDValue Extra = DAG.getValueType(ExtraVT);
14167
14168         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14169         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14170
14171         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14172       }
14173       // fall through
14174     case MVT::v4i32:
14175     case MVT::v8i16: {
14176       SDValue Op0 = Op.getOperand(0);
14177       SDValue Op00 = Op0.getOperand(0);
14178       SDValue Tmp1;
14179       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14180       if (Op0.getOpcode() == ISD::BITCAST &&
14181           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14182         // (sext (vzext x)) -> (vsext x)
14183         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14184         if (Tmp1.getNode()) {
14185           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14186           // This folding is only valid when the in-reg type is a vector of i8,
14187           // i16, or i32.
14188           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14189               ExtraEltVT == MVT::i32) {
14190             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14191             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14192                    "This optimization is invalid without a VZEXT.");
14193             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14194           }
14195           Op0 = Tmp1;
14196         }
14197       }
14198
14199       // If the above didn't work, then just use Shift-Left + Shift-Right.
14200       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14201                                         DAG);
14202       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14203                                         DAG);
14204     }
14205   }
14206 }
14207
14208 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14209                                  SelectionDAG &DAG) {
14210   SDLoc dl(Op);
14211   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14212     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14213   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14214     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14215
14216   // The only fence that needs an instruction is a sequentially-consistent
14217   // cross-thread fence.
14218   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14219     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14220     // no-sse2). There isn't any reason to disable it if the target processor
14221     // supports it.
14222     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14223       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14224
14225     SDValue Chain = Op.getOperand(0);
14226     SDValue Zero = DAG.getConstant(0, MVT::i32);
14227     SDValue Ops[] = {
14228       DAG.getRegister(X86::ESP, MVT::i32), // Base
14229       DAG.getTargetConstant(1, MVT::i8),   // Scale
14230       DAG.getRegister(0, MVT::i32),        // Index
14231       DAG.getTargetConstant(0, MVT::i32),  // Disp
14232       DAG.getRegister(0, MVT::i32),        // Segment.
14233       Zero,
14234       Chain
14235     };
14236     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14237     return SDValue(Res, 0);
14238   }
14239
14240   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14241   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14242 }
14243
14244 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14245                              SelectionDAG &DAG) {
14246   MVT T = Op.getSimpleValueType();
14247   SDLoc DL(Op);
14248   unsigned Reg = 0;
14249   unsigned size = 0;
14250   switch(T.SimpleTy) {
14251   default: llvm_unreachable("Invalid value type!");
14252   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14253   case MVT::i16: Reg = X86::AX;  size = 2; break;
14254   case MVT::i32: Reg = X86::EAX; size = 4; break;
14255   case MVT::i64:
14256     assert(Subtarget->is64Bit() && "Node not type legal!");
14257     Reg = X86::RAX; size = 8;
14258     break;
14259   }
14260   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14261                                     Op.getOperand(2), SDValue());
14262   SDValue Ops[] = { cpIn.getValue(0),
14263                     Op.getOperand(1),
14264                     Op.getOperand(3),
14265                     DAG.getTargetConstant(size, MVT::i8),
14266                     cpIn.getValue(1) };
14267   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14268   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14269   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14270                                            Ops, T, MMO);
14271   SDValue cpOut =
14272     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14273   return cpOut;
14274 }
14275
14276 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14277                             SelectionDAG &DAG) {
14278   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14279   MVT DstVT = Op.getSimpleValueType();
14280
14281   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14282     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14283     if (DstVT != MVT::f64)
14284       // This conversion needs to be expanded.
14285       return SDValue();
14286
14287     SDValue InVec = Op->getOperand(0);
14288     SDLoc dl(Op);
14289     unsigned NumElts = SrcVT.getVectorNumElements();
14290     EVT SVT = SrcVT.getVectorElementType();
14291
14292     // Widen the vector in input in the case of MVT::v2i32.
14293     // Example: from MVT::v2i32 to MVT::v4i32.
14294     SmallVector<SDValue, 16> Elts;
14295     for (unsigned i = 0, e = NumElts; i != e; ++i)
14296       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14297                                  DAG.getIntPtrConstant(i)));
14298
14299     // Explicitly mark the extra elements as Undef.
14300     SDValue Undef = DAG.getUNDEF(SVT);
14301     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14302       Elts.push_back(Undef);
14303
14304     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14305     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14306     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14307     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14308                        DAG.getIntPtrConstant(0));
14309   }
14310
14311   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14312          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14313   assert((DstVT == MVT::i64 ||
14314           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14315          "Unexpected custom BITCAST");
14316   // i64 <=> MMX conversions are Legal.
14317   if (SrcVT==MVT::i64 && DstVT.isVector())
14318     return Op;
14319   if (DstVT==MVT::i64 && SrcVT.isVector())
14320     return Op;
14321   // MMX <=> MMX conversions are Legal.
14322   if (SrcVT.isVector() && DstVT.isVector())
14323     return Op;
14324   // All other conversions need to be expanded.
14325   return SDValue();
14326 }
14327
14328 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14329   SDNode *Node = Op.getNode();
14330   SDLoc dl(Node);
14331   EVT T = Node->getValueType(0);
14332   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14333                               DAG.getConstant(0, T), Node->getOperand(2));
14334   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14335                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14336                        Node->getOperand(0),
14337                        Node->getOperand(1), negOp,
14338                        cast<AtomicSDNode>(Node)->getMemOperand(),
14339                        cast<AtomicSDNode>(Node)->getOrdering(),
14340                        cast<AtomicSDNode>(Node)->getSynchScope());
14341 }
14342
14343 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14344   SDNode *Node = Op.getNode();
14345   SDLoc dl(Node);
14346   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14347
14348   // Convert seq_cst store -> xchg
14349   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14350   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14351   //        (The only way to get a 16-byte store is cmpxchg16b)
14352   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14353   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14354       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14355     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14356                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14357                                  Node->getOperand(0),
14358                                  Node->getOperand(1), Node->getOperand(2),
14359                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14360                                  cast<AtomicSDNode>(Node)->getOrdering(),
14361                                  cast<AtomicSDNode>(Node)->getSynchScope());
14362     return Swap.getValue(1);
14363   }
14364   // Other atomic stores have a simple pattern.
14365   return Op;
14366 }
14367
14368 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14369   EVT VT = Op.getNode()->getSimpleValueType(0);
14370
14371   // Let legalize expand this if it isn't a legal type yet.
14372   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14373     return SDValue();
14374
14375   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14376
14377   unsigned Opc;
14378   bool ExtraOp = false;
14379   switch (Op.getOpcode()) {
14380   default: llvm_unreachable("Invalid code");
14381   case ISD::ADDC: Opc = X86ISD::ADD; break;
14382   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14383   case ISD::SUBC: Opc = X86ISD::SUB; break;
14384   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14385   }
14386
14387   if (!ExtraOp)
14388     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14389                        Op.getOperand(1));
14390   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14391                      Op.getOperand(1), Op.getOperand(2));
14392 }
14393
14394 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14395                             SelectionDAG &DAG) {
14396   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14397
14398   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14399   // which returns the values as { float, float } (in XMM0) or
14400   // { double, double } (which is returned in XMM0, XMM1).
14401   SDLoc dl(Op);
14402   SDValue Arg = Op.getOperand(0);
14403   EVT ArgVT = Arg.getValueType();
14404   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14405
14406   TargetLowering::ArgListTy Args;
14407   TargetLowering::ArgListEntry Entry;
14408
14409   Entry.Node = Arg;
14410   Entry.Ty = ArgTy;
14411   Entry.isSExt = false;
14412   Entry.isZExt = false;
14413   Args.push_back(Entry);
14414
14415   bool isF64 = ArgVT == MVT::f64;
14416   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14417   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14418   // the results are returned via SRet in memory.
14419   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14420   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14421   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14422
14423   Type *RetTy = isF64
14424     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14425     : (Type*)VectorType::get(ArgTy, 4);
14426
14427   TargetLowering::CallLoweringInfo CLI(DAG);
14428   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14429     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14430
14431   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14432
14433   if (isF64)
14434     // Returned in xmm0 and xmm1.
14435     return CallResult.first;
14436
14437   // Returned in bits 0:31 and 32:64 xmm0.
14438   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14439                                CallResult.first, DAG.getIntPtrConstant(0));
14440   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14441                                CallResult.first, DAG.getIntPtrConstant(1));
14442   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14443   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14444 }
14445
14446 /// LowerOperation - Provide custom lowering hooks for some operations.
14447 ///
14448 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14449   switch (Op.getOpcode()) {
14450   default: llvm_unreachable("Should not custom lower this!");
14451   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14452   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14453   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14454   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14455   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14456   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14457   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14458   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14459   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14460   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14461   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14462   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14463   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14464   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14465   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14466   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14467   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14468   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14469   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14470   case ISD::SHL_PARTS:
14471   case ISD::SRA_PARTS:
14472   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14473   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14474   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14475   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14476   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14477   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14478   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14479   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14480   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14481   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14482   case ISD::FABS:               return LowerFABS(Op, DAG);
14483   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14484   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14485   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14486   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14487   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14488   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14489   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14490   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14491   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14492   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14493   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14494   case ISD::INTRINSIC_VOID:
14495   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14496   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14497   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14498   case ISD::FRAME_TO_ARGS_OFFSET:
14499                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14500   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14501   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14502   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14503   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14504   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14505   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14506   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14507   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14508   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14509   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14510   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14511   case ISD::UMUL_LOHI:
14512   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14513   case ISD::SRA:
14514   case ISD::SRL:
14515   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14516   case ISD::SADDO:
14517   case ISD::UADDO:
14518   case ISD::SSUBO:
14519   case ISD::USUBO:
14520   case ISD::SMULO:
14521   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14522   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14523   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14524   case ISD::ADDC:
14525   case ISD::ADDE:
14526   case ISD::SUBC:
14527   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14528   case ISD::ADD:                return LowerADD(Op, DAG);
14529   case ISD::SUB:                return LowerSUB(Op, DAG);
14530   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14531   }
14532 }
14533
14534 static void ReplaceATOMIC_LOAD(SDNode *Node,
14535                                   SmallVectorImpl<SDValue> &Results,
14536                                   SelectionDAG &DAG) {
14537   SDLoc dl(Node);
14538   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14539
14540   // Convert wide load -> cmpxchg8b/cmpxchg16b
14541   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14542   //        (The only way to get a 16-byte load is cmpxchg16b)
14543   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14544   SDValue Zero = DAG.getConstant(0, VT);
14545   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14546                                Node->getOperand(0),
14547                                Node->getOperand(1), Zero, Zero,
14548                                cast<AtomicSDNode>(Node)->getMemOperand(),
14549                                cast<AtomicSDNode>(Node)->getOrdering(),
14550                                cast<AtomicSDNode>(Node)->getOrdering(),
14551                                cast<AtomicSDNode>(Node)->getSynchScope());
14552   Results.push_back(Swap.getValue(0));
14553   Results.push_back(Swap.getValue(1));
14554 }
14555
14556 static void
14557 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14558                         SelectionDAG &DAG, unsigned NewOp) {
14559   SDLoc dl(Node);
14560   assert (Node->getValueType(0) == MVT::i64 &&
14561           "Only know how to expand i64 atomics");
14562
14563   SDValue Chain = Node->getOperand(0);
14564   SDValue In1 = Node->getOperand(1);
14565   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14566                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14567   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14568                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14569   SDValue Ops[] = { Chain, In1, In2L, In2H };
14570   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14571   SDValue Result =
14572     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14573                             cast<MemSDNode>(Node)->getMemOperand());
14574   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14575   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14576   Results.push_back(Result.getValue(2));
14577 }
14578
14579 /// ReplaceNodeResults - Replace a node with an illegal result type
14580 /// with a new node built out of custom code.
14581 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14582                                            SmallVectorImpl<SDValue>&Results,
14583                                            SelectionDAG &DAG) const {
14584   SDLoc dl(N);
14585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14586   switch (N->getOpcode()) {
14587   default:
14588     llvm_unreachable("Do not know how to custom type legalize this operation!");
14589   case ISD::SIGN_EXTEND_INREG:
14590   case ISD::ADDC:
14591   case ISD::ADDE:
14592   case ISD::SUBC:
14593   case ISD::SUBE:
14594     // We don't want to expand or promote these.
14595     return;
14596   case ISD::SDIV:
14597   case ISD::UDIV:
14598   case ISD::SREM:
14599   case ISD::UREM:
14600   case ISD::SDIVREM:
14601   case ISD::UDIVREM: {
14602     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14603     Results.push_back(V);
14604     return;
14605   }
14606   case ISD::FP_TO_SINT:
14607   case ISD::FP_TO_UINT: {
14608     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14609
14610     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14611       return;
14612
14613     std::pair<SDValue,SDValue> Vals =
14614         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14615     SDValue FIST = Vals.first, StackSlot = Vals.second;
14616     if (FIST.getNode()) {
14617       EVT VT = N->getValueType(0);
14618       // Return a load from the stack slot.
14619       if (StackSlot.getNode())
14620         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14621                                       MachinePointerInfo(),
14622                                       false, false, false, 0));
14623       else
14624         Results.push_back(FIST);
14625     }
14626     return;
14627   }
14628   case ISD::UINT_TO_FP: {
14629     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14630     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14631         N->getValueType(0) != MVT::v2f32)
14632       return;
14633     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14634                                  N->getOperand(0));
14635     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14636                                      MVT::f64);
14637     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14638     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14639                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14640     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14641     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14642     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14643     return;
14644   }
14645   case ISD::FP_ROUND: {
14646     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14647         return;
14648     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14649     Results.push_back(V);
14650     return;
14651   }
14652   case ISD::INTRINSIC_W_CHAIN: {
14653     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14654     switch (IntNo) {
14655     default : llvm_unreachable("Do not know how to custom type "
14656                                "legalize this intrinsic operation!");
14657     case Intrinsic::x86_rdtsc:
14658       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14659                                      Results);
14660     case Intrinsic::x86_rdtscp:
14661       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14662                                      Results);
14663     }
14664   }
14665   case ISD::READCYCLECOUNTER: {
14666     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14667                                    Results);
14668   }
14669   case ISD::ATOMIC_CMP_SWAP: {
14670     EVT T = N->getValueType(0);
14671     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14672     bool Regs64bit = T == MVT::i128;
14673     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14674     SDValue cpInL, cpInH;
14675     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14676                         DAG.getConstant(0, HalfT));
14677     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14678                         DAG.getConstant(1, HalfT));
14679     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14680                              Regs64bit ? X86::RAX : X86::EAX,
14681                              cpInL, SDValue());
14682     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14683                              Regs64bit ? X86::RDX : X86::EDX,
14684                              cpInH, cpInL.getValue(1));
14685     SDValue swapInL, swapInH;
14686     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14687                           DAG.getConstant(0, HalfT));
14688     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14689                           DAG.getConstant(1, HalfT));
14690     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14691                                Regs64bit ? X86::RBX : X86::EBX,
14692                                swapInL, cpInH.getValue(1));
14693     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14694                                Regs64bit ? X86::RCX : X86::ECX,
14695                                swapInH, swapInL.getValue(1));
14696     SDValue Ops[] = { swapInH.getValue(0),
14697                       N->getOperand(1),
14698                       swapInH.getValue(1) };
14699     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14700     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14701     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14702                                   X86ISD::LCMPXCHG8_DAG;
14703     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14704     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14705                                         Regs64bit ? X86::RAX : X86::EAX,
14706                                         HalfT, Result.getValue(1));
14707     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14708                                         Regs64bit ? X86::RDX : X86::EDX,
14709                                         HalfT, cpOutL.getValue(2));
14710     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14711     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14712     Results.push_back(cpOutH.getValue(1));
14713     return;
14714   }
14715   case ISD::ATOMIC_LOAD_ADD:
14716   case ISD::ATOMIC_LOAD_AND:
14717   case ISD::ATOMIC_LOAD_NAND:
14718   case ISD::ATOMIC_LOAD_OR:
14719   case ISD::ATOMIC_LOAD_SUB:
14720   case ISD::ATOMIC_LOAD_XOR:
14721   case ISD::ATOMIC_LOAD_MAX:
14722   case ISD::ATOMIC_LOAD_MIN:
14723   case ISD::ATOMIC_LOAD_UMAX:
14724   case ISD::ATOMIC_LOAD_UMIN:
14725   case ISD::ATOMIC_SWAP: {
14726     unsigned Opc;
14727     switch (N->getOpcode()) {
14728     default: llvm_unreachable("Unexpected opcode");
14729     case ISD::ATOMIC_LOAD_ADD:
14730       Opc = X86ISD::ATOMADD64_DAG;
14731       break;
14732     case ISD::ATOMIC_LOAD_AND:
14733       Opc = X86ISD::ATOMAND64_DAG;
14734       break;
14735     case ISD::ATOMIC_LOAD_NAND:
14736       Opc = X86ISD::ATOMNAND64_DAG;
14737       break;
14738     case ISD::ATOMIC_LOAD_OR:
14739       Opc = X86ISD::ATOMOR64_DAG;
14740       break;
14741     case ISD::ATOMIC_LOAD_SUB:
14742       Opc = X86ISD::ATOMSUB64_DAG;
14743       break;
14744     case ISD::ATOMIC_LOAD_XOR:
14745       Opc = X86ISD::ATOMXOR64_DAG;
14746       break;
14747     case ISD::ATOMIC_LOAD_MAX:
14748       Opc = X86ISD::ATOMMAX64_DAG;
14749       break;
14750     case ISD::ATOMIC_LOAD_MIN:
14751       Opc = X86ISD::ATOMMIN64_DAG;
14752       break;
14753     case ISD::ATOMIC_LOAD_UMAX:
14754       Opc = X86ISD::ATOMUMAX64_DAG;
14755       break;
14756     case ISD::ATOMIC_LOAD_UMIN:
14757       Opc = X86ISD::ATOMUMIN64_DAG;
14758       break;
14759     case ISD::ATOMIC_SWAP:
14760       Opc = X86ISD::ATOMSWAP64_DAG;
14761       break;
14762     }
14763     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14764     return;
14765   }
14766   case ISD::ATOMIC_LOAD: {
14767     ReplaceATOMIC_LOAD(N, Results, DAG);
14768     return;
14769   }
14770   case ISD::BITCAST: {
14771     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14772     EVT DstVT = N->getValueType(0);
14773     EVT SrcVT = N->getOperand(0)->getValueType(0);
14774
14775     if (SrcVT != MVT::f64 ||
14776         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14777       return;
14778
14779     unsigned NumElts = DstVT.getVectorNumElements();
14780     EVT SVT = DstVT.getVectorElementType();
14781     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14782     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14783                                    MVT::v2f64, N->getOperand(0));
14784     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14785
14786     SmallVector<SDValue, 8> Elts;
14787     for (unsigned i = 0, e = NumElts; i != e; ++i)
14788       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14789                                    ToVecInt, DAG.getIntPtrConstant(i)));
14790
14791     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14792   }
14793   }
14794 }
14795
14796 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14797   switch (Opcode) {
14798   default: return nullptr;
14799   case X86ISD::BSF:                return "X86ISD::BSF";
14800   case X86ISD::BSR:                return "X86ISD::BSR";
14801   case X86ISD::SHLD:               return "X86ISD::SHLD";
14802   case X86ISD::SHRD:               return "X86ISD::SHRD";
14803   case X86ISD::FAND:               return "X86ISD::FAND";
14804   case X86ISD::FANDN:              return "X86ISD::FANDN";
14805   case X86ISD::FOR:                return "X86ISD::FOR";
14806   case X86ISD::FXOR:               return "X86ISD::FXOR";
14807   case X86ISD::FSRL:               return "X86ISD::FSRL";
14808   case X86ISD::FILD:               return "X86ISD::FILD";
14809   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14810   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14811   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14812   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14813   case X86ISD::FLD:                return "X86ISD::FLD";
14814   case X86ISD::FST:                return "X86ISD::FST";
14815   case X86ISD::CALL:               return "X86ISD::CALL";
14816   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14817   case X86ISD::BT:                 return "X86ISD::BT";
14818   case X86ISD::CMP:                return "X86ISD::CMP";
14819   case X86ISD::COMI:               return "X86ISD::COMI";
14820   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14821   case X86ISD::CMPM:               return "X86ISD::CMPM";
14822   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14823   case X86ISD::SETCC:              return "X86ISD::SETCC";
14824   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14825   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14826   case X86ISD::CMOV:               return "X86ISD::CMOV";
14827   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14828   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14829   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14830   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14831   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14832   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14833   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14834   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14835   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14836   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14837   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14838   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14839   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14840   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14841   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14842   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14843   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14844   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14845   case X86ISD::HADD:               return "X86ISD::HADD";
14846   case X86ISD::HSUB:               return "X86ISD::HSUB";
14847   case X86ISD::FHADD:              return "X86ISD::FHADD";
14848   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14849   case X86ISD::UMAX:               return "X86ISD::UMAX";
14850   case X86ISD::UMIN:               return "X86ISD::UMIN";
14851   case X86ISD::SMAX:               return "X86ISD::SMAX";
14852   case X86ISD::SMIN:               return "X86ISD::SMIN";
14853   case X86ISD::FMAX:               return "X86ISD::FMAX";
14854   case X86ISD::FMIN:               return "X86ISD::FMIN";
14855   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14856   case X86ISD::FMINC:              return "X86ISD::FMINC";
14857   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14858   case X86ISD::FRCP:               return "X86ISD::FRCP";
14859   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14860   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14861   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14862   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14863   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14864   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14865   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14866   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14867   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14868   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14869   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14870   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14871   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14872   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14873   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14874   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14875   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14876   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14877   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14878   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14879   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14880   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14881   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14882   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14883   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14884   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14885   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14886   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14887   case X86ISD::VSHL:               return "X86ISD::VSHL";
14888   case X86ISD::VSRL:               return "X86ISD::VSRL";
14889   case X86ISD::VSRA:               return "X86ISD::VSRA";
14890   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14891   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14892   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14893   case X86ISD::CMPP:               return "X86ISD::CMPP";
14894   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14895   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14896   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14897   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14898   case X86ISD::ADD:                return "X86ISD::ADD";
14899   case X86ISD::SUB:                return "X86ISD::SUB";
14900   case X86ISD::ADC:                return "X86ISD::ADC";
14901   case X86ISD::SBB:                return "X86ISD::SBB";
14902   case X86ISD::SMUL:               return "X86ISD::SMUL";
14903   case X86ISD::UMUL:               return "X86ISD::UMUL";
14904   case X86ISD::INC:                return "X86ISD::INC";
14905   case X86ISD::DEC:                return "X86ISD::DEC";
14906   case X86ISD::OR:                 return "X86ISD::OR";
14907   case X86ISD::XOR:                return "X86ISD::XOR";
14908   case X86ISD::AND:                return "X86ISD::AND";
14909   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14910   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14911   case X86ISD::PTEST:              return "X86ISD::PTEST";
14912   case X86ISD::TESTP:              return "X86ISD::TESTP";
14913   case X86ISD::TESTM:              return "X86ISD::TESTM";
14914   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14915   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14916   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14917   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14918   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14919   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14920   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14921   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14922   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14923   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14924   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14925   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14926   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14927   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14928   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14929   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14930   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14931   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14932   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14933   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14934   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14935   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14936   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14937   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14938   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14939   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14940   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14941   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14942   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14943   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14944   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14945   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14946   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14947   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14948   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14949   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14950   case X86ISD::SAHF:               return "X86ISD::SAHF";
14951   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14952   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14953   case X86ISD::FMADD:              return "X86ISD::FMADD";
14954   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14955   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14956   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14957   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14958   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14959   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14960   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14961   case X86ISD::XTEST:              return "X86ISD::XTEST";
14962   }
14963 }
14964
14965 // isLegalAddressingMode - Return true if the addressing mode represented
14966 // by AM is legal for this target, for a load/store of the specified type.
14967 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14968                                               Type *Ty) const {
14969   // X86 supports extremely general addressing modes.
14970   CodeModel::Model M = getTargetMachine().getCodeModel();
14971   Reloc::Model R = getTargetMachine().getRelocationModel();
14972
14973   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14974   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14975     return false;
14976
14977   if (AM.BaseGV) {
14978     unsigned GVFlags =
14979       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14980
14981     // If a reference to this global requires an extra load, we can't fold it.
14982     if (isGlobalStubReference(GVFlags))
14983       return false;
14984
14985     // If BaseGV requires a register for the PIC base, we cannot also have a
14986     // BaseReg specified.
14987     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14988       return false;
14989
14990     // If lower 4G is not available, then we must use rip-relative addressing.
14991     if ((M != CodeModel::Small || R != Reloc::Static) &&
14992         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14993       return false;
14994   }
14995
14996   switch (AM.Scale) {
14997   case 0:
14998   case 1:
14999   case 2:
15000   case 4:
15001   case 8:
15002     // These scales always work.
15003     break;
15004   case 3:
15005   case 5:
15006   case 9:
15007     // These scales are formed with basereg+scalereg.  Only accept if there is
15008     // no basereg yet.
15009     if (AM.HasBaseReg)
15010       return false;
15011     break;
15012   default:  // Other stuff never works.
15013     return false;
15014   }
15015
15016   return true;
15017 }
15018
15019 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15020   unsigned Bits = Ty->getScalarSizeInBits();
15021
15022   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15023   // particularly cheaper than those without.
15024   if (Bits == 8)
15025     return false;
15026
15027   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15028   // variable shifts just as cheap as scalar ones.
15029   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15030     return false;
15031
15032   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15033   // fully general vector.
15034   return true;
15035 }
15036
15037 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15038   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15039     return false;
15040   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15041   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15042   return NumBits1 > NumBits2;
15043 }
15044
15045 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15046   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15047     return false;
15048
15049   if (!isTypeLegal(EVT::getEVT(Ty1)))
15050     return false;
15051
15052   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15053
15054   // Assuming the caller doesn't have a zeroext or signext return parameter,
15055   // truncation all the way down to i1 is valid.
15056   return true;
15057 }
15058
15059 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15060   return isInt<32>(Imm);
15061 }
15062
15063 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15064   // Can also use sub to handle negated immediates.
15065   return isInt<32>(Imm);
15066 }
15067
15068 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15069   if (!VT1.isInteger() || !VT2.isInteger())
15070     return false;
15071   unsigned NumBits1 = VT1.getSizeInBits();
15072   unsigned NumBits2 = VT2.getSizeInBits();
15073   return NumBits1 > NumBits2;
15074 }
15075
15076 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15077   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15078   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15079 }
15080
15081 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15082   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15083   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15084 }
15085
15086 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15087   EVT VT1 = Val.getValueType();
15088   if (isZExtFree(VT1, VT2))
15089     return true;
15090
15091   if (Val.getOpcode() != ISD::LOAD)
15092     return false;
15093
15094   if (!VT1.isSimple() || !VT1.isInteger() ||
15095       !VT2.isSimple() || !VT2.isInteger())
15096     return false;
15097
15098   switch (VT1.getSimpleVT().SimpleTy) {
15099   default: break;
15100   case MVT::i8:
15101   case MVT::i16:
15102   case MVT::i32:
15103     // X86 has 8, 16, and 32-bit zero-extending loads.
15104     return true;
15105   }
15106
15107   return false;
15108 }
15109
15110 bool
15111 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15112   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15113     return false;
15114
15115   VT = VT.getScalarType();
15116
15117   if (!VT.isSimple())
15118     return false;
15119
15120   switch (VT.getSimpleVT().SimpleTy) {
15121   case MVT::f32:
15122   case MVT::f64:
15123     return true;
15124   default:
15125     break;
15126   }
15127
15128   return false;
15129 }
15130
15131 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15132   // i16 instructions are longer (0x66 prefix) and potentially slower.
15133   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15134 }
15135
15136 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15137 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15138 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15139 /// are assumed to be legal.
15140 bool
15141 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15142                                       EVT VT) const {
15143   if (!VT.isSimple())
15144     return false;
15145
15146   MVT SVT = VT.getSimpleVT();
15147
15148   // Very little shuffling can be done for 64-bit vectors right now.
15149   if (VT.getSizeInBits() == 64)
15150     return false;
15151
15152   // If this is a single-input shuffle with no 128 bit lane crossings we can
15153   // lower it into pshufb.
15154   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15155       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15156     bool isLegal = true;
15157     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15158       if (M[I] >= (int)SVT.getVectorNumElements() ||
15159           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15160         isLegal = false;
15161         break;
15162       }
15163     }
15164     if (isLegal)
15165       return true;
15166   }
15167
15168   // FIXME: blends, shifts.
15169   return (SVT.getVectorNumElements() == 2 ||
15170           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15171           isMOVLMask(M, SVT) ||
15172           isSHUFPMask(M, SVT) ||
15173           isPSHUFDMask(M, SVT) ||
15174           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15175           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15176           isPALIGNRMask(M, SVT, Subtarget) ||
15177           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15178           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15179           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15180           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
15181 }
15182
15183 bool
15184 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15185                                           EVT VT) const {
15186   if (!VT.isSimple())
15187     return false;
15188
15189   MVT SVT = VT.getSimpleVT();
15190   unsigned NumElts = SVT.getVectorNumElements();
15191   // FIXME: This collection of masks seems suspect.
15192   if (NumElts == 2)
15193     return true;
15194   if (NumElts == 4 && SVT.is128BitVector()) {
15195     return (isMOVLMask(Mask, SVT)  ||
15196             isCommutedMOVLMask(Mask, SVT, true) ||
15197             isSHUFPMask(Mask, SVT) ||
15198             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15199   }
15200   return false;
15201 }
15202
15203 //===----------------------------------------------------------------------===//
15204 //                           X86 Scheduler Hooks
15205 //===----------------------------------------------------------------------===//
15206
15207 /// Utility function to emit xbegin specifying the start of an RTM region.
15208 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15209                                      const TargetInstrInfo *TII) {
15210   DebugLoc DL = MI->getDebugLoc();
15211
15212   const BasicBlock *BB = MBB->getBasicBlock();
15213   MachineFunction::iterator I = MBB;
15214   ++I;
15215
15216   // For the v = xbegin(), we generate
15217   //
15218   // thisMBB:
15219   //  xbegin sinkMBB
15220   //
15221   // mainMBB:
15222   //  eax = -1
15223   //
15224   // sinkMBB:
15225   //  v = eax
15226
15227   MachineBasicBlock *thisMBB = MBB;
15228   MachineFunction *MF = MBB->getParent();
15229   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15230   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15231   MF->insert(I, mainMBB);
15232   MF->insert(I, sinkMBB);
15233
15234   // Transfer the remainder of BB and its successor edges to sinkMBB.
15235   sinkMBB->splice(sinkMBB->begin(), MBB,
15236                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15237   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15238
15239   // thisMBB:
15240   //  xbegin sinkMBB
15241   //  # fallthrough to mainMBB
15242   //  # abortion to sinkMBB
15243   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15244   thisMBB->addSuccessor(mainMBB);
15245   thisMBB->addSuccessor(sinkMBB);
15246
15247   // mainMBB:
15248   //  EAX = -1
15249   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15250   mainMBB->addSuccessor(sinkMBB);
15251
15252   // sinkMBB:
15253   // EAX is live into the sinkMBB
15254   sinkMBB->addLiveIn(X86::EAX);
15255   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15256           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15257     .addReg(X86::EAX);
15258
15259   MI->eraseFromParent();
15260   return sinkMBB;
15261 }
15262
15263 // Get CMPXCHG opcode for the specified data type.
15264 static unsigned getCmpXChgOpcode(EVT VT) {
15265   switch (VT.getSimpleVT().SimpleTy) {
15266   case MVT::i8:  return X86::LCMPXCHG8;
15267   case MVT::i16: return X86::LCMPXCHG16;
15268   case MVT::i32: return X86::LCMPXCHG32;
15269   case MVT::i64: return X86::LCMPXCHG64;
15270   default:
15271     break;
15272   }
15273   llvm_unreachable("Invalid operand size!");
15274 }
15275
15276 // Get LOAD opcode for the specified data type.
15277 static unsigned getLoadOpcode(EVT VT) {
15278   switch (VT.getSimpleVT().SimpleTy) {
15279   case MVT::i8:  return X86::MOV8rm;
15280   case MVT::i16: return X86::MOV16rm;
15281   case MVT::i32: return X86::MOV32rm;
15282   case MVT::i64: return X86::MOV64rm;
15283   default:
15284     break;
15285   }
15286   llvm_unreachable("Invalid operand size!");
15287 }
15288
15289 // Get opcode of the non-atomic one from the specified atomic instruction.
15290 static unsigned getNonAtomicOpcode(unsigned Opc) {
15291   switch (Opc) {
15292   case X86::ATOMAND8:  return X86::AND8rr;
15293   case X86::ATOMAND16: return X86::AND16rr;
15294   case X86::ATOMAND32: return X86::AND32rr;
15295   case X86::ATOMAND64: return X86::AND64rr;
15296   case X86::ATOMOR8:   return X86::OR8rr;
15297   case X86::ATOMOR16:  return X86::OR16rr;
15298   case X86::ATOMOR32:  return X86::OR32rr;
15299   case X86::ATOMOR64:  return X86::OR64rr;
15300   case X86::ATOMXOR8:  return X86::XOR8rr;
15301   case X86::ATOMXOR16: return X86::XOR16rr;
15302   case X86::ATOMXOR32: return X86::XOR32rr;
15303   case X86::ATOMXOR64: return X86::XOR64rr;
15304   }
15305   llvm_unreachable("Unhandled atomic-load-op opcode!");
15306 }
15307
15308 // Get opcode of the non-atomic one from the specified atomic instruction with
15309 // extra opcode.
15310 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15311                                                unsigned &ExtraOpc) {
15312   switch (Opc) {
15313   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15314   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15315   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15316   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15317   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15318   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15319   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15320   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15321   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15322   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15323   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15324   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15325   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15326   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15327   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15328   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15329   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15330   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15331   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15332   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15333   }
15334   llvm_unreachable("Unhandled atomic-load-op opcode!");
15335 }
15336
15337 // Get opcode of the non-atomic one from the specified atomic instruction for
15338 // 64-bit data type on 32-bit target.
15339 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15340   switch (Opc) {
15341   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15342   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15343   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15344   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15345   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15346   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15347   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15348   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15349   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15350   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15351   }
15352   llvm_unreachable("Unhandled atomic-load-op opcode!");
15353 }
15354
15355 // Get opcode of the non-atomic one from the specified atomic instruction for
15356 // 64-bit data type on 32-bit target with extra opcode.
15357 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15358                                                    unsigned &HiOpc,
15359                                                    unsigned &ExtraOpc) {
15360   switch (Opc) {
15361   case X86::ATOMNAND6432:
15362     ExtraOpc = X86::NOT32r;
15363     HiOpc = X86::AND32rr;
15364     return X86::AND32rr;
15365   }
15366   llvm_unreachable("Unhandled atomic-load-op opcode!");
15367 }
15368
15369 // Get pseudo CMOV opcode from the specified data type.
15370 static unsigned getPseudoCMOVOpc(EVT VT) {
15371   switch (VT.getSimpleVT().SimpleTy) {
15372   case MVT::i8:  return X86::CMOV_GR8;
15373   case MVT::i16: return X86::CMOV_GR16;
15374   case MVT::i32: return X86::CMOV_GR32;
15375   default:
15376     break;
15377   }
15378   llvm_unreachable("Unknown CMOV opcode!");
15379 }
15380
15381 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15382 // They will be translated into a spin-loop or compare-exchange loop from
15383 //
15384 //    ...
15385 //    dst = atomic-fetch-op MI.addr, MI.val
15386 //    ...
15387 //
15388 // to
15389 //
15390 //    ...
15391 //    t1 = LOAD MI.addr
15392 // loop:
15393 //    t4 = phi(t1, t3 / loop)
15394 //    t2 = OP MI.val, t4
15395 //    EAX = t4
15396 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15397 //    t3 = EAX
15398 //    JNE loop
15399 // sink:
15400 //    dst = t3
15401 //    ...
15402 MachineBasicBlock *
15403 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15404                                        MachineBasicBlock *MBB) const {
15405   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15406   DebugLoc DL = MI->getDebugLoc();
15407
15408   MachineFunction *MF = MBB->getParent();
15409   MachineRegisterInfo &MRI = MF->getRegInfo();
15410
15411   const BasicBlock *BB = MBB->getBasicBlock();
15412   MachineFunction::iterator I = MBB;
15413   ++I;
15414
15415   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15416          "Unexpected number of operands");
15417
15418   assert(MI->hasOneMemOperand() &&
15419          "Expected atomic-load-op to have one memoperand");
15420
15421   // Memory Reference
15422   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15423   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15424
15425   unsigned DstReg, SrcReg;
15426   unsigned MemOpndSlot;
15427
15428   unsigned CurOp = 0;
15429
15430   DstReg = MI->getOperand(CurOp++).getReg();
15431   MemOpndSlot = CurOp;
15432   CurOp += X86::AddrNumOperands;
15433   SrcReg = MI->getOperand(CurOp++).getReg();
15434
15435   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15436   MVT::SimpleValueType VT = *RC->vt_begin();
15437   unsigned t1 = MRI.createVirtualRegister(RC);
15438   unsigned t2 = MRI.createVirtualRegister(RC);
15439   unsigned t3 = MRI.createVirtualRegister(RC);
15440   unsigned t4 = MRI.createVirtualRegister(RC);
15441   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15442
15443   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15444   unsigned LOADOpc = getLoadOpcode(VT);
15445
15446   // For the atomic load-arith operator, we generate
15447   //
15448   //  thisMBB:
15449   //    t1 = LOAD [MI.addr]
15450   //  mainMBB:
15451   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15452   //    t1 = OP MI.val, EAX
15453   //    EAX = t4
15454   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15455   //    t3 = EAX
15456   //    JNE mainMBB
15457   //  sinkMBB:
15458   //    dst = t3
15459
15460   MachineBasicBlock *thisMBB = MBB;
15461   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15462   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15463   MF->insert(I, mainMBB);
15464   MF->insert(I, sinkMBB);
15465
15466   MachineInstrBuilder MIB;
15467
15468   // Transfer the remainder of BB and its successor edges to sinkMBB.
15469   sinkMBB->splice(sinkMBB->begin(), MBB,
15470                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15471   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15472
15473   // thisMBB:
15474   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15475   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15476     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15477     if (NewMO.isReg())
15478       NewMO.setIsKill(false);
15479     MIB.addOperand(NewMO);
15480   }
15481   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15482     unsigned flags = (*MMOI)->getFlags();
15483     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15484     MachineMemOperand *MMO =
15485       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15486                                (*MMOI)->getSize(),
15487                                (*MMOI)->getBaseAlignment(),
15488                                (*MMOI)->getTBAAInfo(),
15489                                (*MMOI)->getRanges());
15490     MIB.addMemOperand(MMO);
15491   }
15492
15493   thisMBB->addSuccessor(mainMBB);
15494
15495   // mainMBB:
15496   MachineBasicBlock *origMainMBB = mainMBB;
15497
15498   // Add a PHI.
15499   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15500                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15501
15502   unsigned Opc = MI->getOpcode();
15503   switch (Opc) {
15504   default:
15505     llvm_unreachable("Unhandled atomic-load-op opcode!");
15506   case X86::ATOMAND8:
15507   case X86::ATOMAND16:
15508   case X86::ATOMAND32:
15509   case X86::ATOMAND64:
15510   case X86::ATOMOR8:
15511   case X86::ATOMOR16:
15512   case X86::ATOMOR32:
15513   case X86::ATOMOR64:
15514   case X86::ATOMXOR8:
15515   case X86::ATOMXOR16:
15516   case X86::ATOMXOR32:
15517   case X86::ATOMXOR64: {
15518     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15519     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15520       .addReg(t4);
15521     break;
15522   }
15523   case X86::ATOMNAND8:
15524   case X86::ATOMNAND16:
15525   case X86::ATOMNAND32:
15526   case X86::ATOMNAND64: {
15527     unsigned Tmp = MRI.createVirtualRegister(RC);
15528     unsigned NOTOpc;
15529     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15530     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15531       .addReg(t4);
15532     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15533     break;
15534   }
15535   case X86::ATOMMAX8:
15536   case X86::ATOMMAX16:
15537   case X86::ATOMMAX32:
15538   case X86::ATOMMAX64:
15539   case X86::ATOMMIN8:
15540   case X86::ATOMMIN16:
15541   case X86::ATOMMIN32:
15542   case X86::ATOMMIN64:
15543   case X86::ATOMUMAX8:
15544   case X86::ATOMUMAX16:
15545   case X86::ATOMUMAX32:
15546   case X86::ATOMUMAX64:
15547   case X86::ATOMUMIN8:
15548   case X86::ATOMUMIN16:
15549   case X86::ATOMUMIN32:
15550   case X86::ATOMUMIN64: {
15551     unsigned CMPOpc;
15552     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15553
15554     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15555       .addReg(SrcReg)
15556       .addReg(t4);
15557
15558     if (Subtarget->hasCMov()) {
15559       if (VT != MVT::i8) {
15560         // Native support
15561         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15562           .addReg(SrcReg)
15563           .addReg(t4);
15564       } else {
15565         // Promote i8 to i32 to use CMOV32
15566         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15567         const TargetRegisterClass *RC32 =
15568           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15569         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15570         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15571         unsigned Tmp = MRI.createVirtualRegister(RC32);
15572
15573         unsigned Undef = MRI.createVirtualRegister(RC32);
15574         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15575
15576         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15577           .addReg(Undef)
15578           .addReg(SrcReg)
15579           .addImm(X86::sub_8bit);
15580         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15581           .addReg(Undef)
15582           .addReg(t4)
15583           .addImm(X86::sub_8bit);
15584
15585         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15586           .addReg(SrcReg32)
15587           .addReg(AccReg32);
15588
15589         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15590           .addReg(Tmp, 0, X86::sub_8bit);
15591       }
15592     } else {
15593       // Use pseudo select and lower them.
15594       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15595              "Invalid atomic-load-op transformation!");
15596       unsigned SelOpc = getPseudoCMOVOpc(VT);
15597       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15598       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15599       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15600               .addReg(SrcReg).addReg(t4)
15601               .addImm(CC);
15602       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15603       // Replace the original PHI node as mainMBB is changed after CMOV
15604       // lowering.
15605       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15606         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15607       Phi->eraseFromParent();
15608     }
15609     break;
15610   }
15611   }
15612
15613   // Copy PhyReg back from virtual register.
15614   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15615     .addReg(t4);
15616
15617   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15618   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15619     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15620     if (NewMO.isReg())
15621       NewMO.setIsKill(false);
15622     MIB.addOperand(NewMO);
15623   }
15624   MIB.addReg(t2);
15625   MIB.setMemRefs(MMOBegin, MMOEnd);
15626
15627   // Copy PhyReg back to virtual register.
15628   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15629     .addReg(PhyReg);
15630
15631   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15632
15633   mainMBB->addSuccessor(origMainMBB);
15634   mainMBB->addSuccessor(sinkMBB);
15635
15636   // sinkMBB:
15637   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15638           TII->get(TargetOpcode::COPY), DstReg)
15639     .addReg(t3);
15640
15641   MI->eraseFromParent();
15642   return sinkMBB;
15643 }
15644
15645 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15646 // instructions. They will be translated into a spin-loop or compare-exchange
15647 // loop from
15648 //
15649 //    ...
15650 //    dst = atomic-fetch-op MI.addr, MI.val
15651 //    ...
15652 //
15653 // to
15654 //
15655 //    ...
15656 //    t1L = LOAD [MI.addr + 0]
15657 //    t1H = LOAD [MI.addr + 4]
15658 // loop:
15659 //    t4L = phi(t1L, t3L / loop)
15660 //    t4H = phi(t1H, t3H / loop)
15661 //    t2L = OP MI.val.lo, t4L
15662 //    t2H = OP MI.val.hi, t4H
15663 //    EAX = t4L
15664 //    EDX = t4H
15665 //    EBX = t2L
15666 //    ECX = t2H
15667 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15668 //    t3L = EAX
15669 //    t3H = EDX
15670 //    JNE loop
15671 // sink:
15672 //    dstL = t3L
15673 //    dstH = t3H
15674 //    ...
15675 MachineBasicBlock *
15676 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15677                                            MachineBasicBlock *MBB) const {
15678   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15679   DebugLoc DL = MI->getDebugLoc();
15680
15681   MachineFunction *MF = MBB->getParent();
15682   MachineRegisterInfo &MRI = MF->getRegInfo();
15683
15684   const BasicBlock *BB = MBB->getBasicBlock();
15685   MachineFunction::iterator I = MBB;
15686   ++I;
15687
15688   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15689          "Unexpected number of operands");
15690
15691   assert(MI->hasOneMemOperand() &&
15692          "Expected atomic-load-op32 to have one memoperand");
15693
15694   // Memory Reference
15695   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15696   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15697
15698   unsigned DstLoReg, DstHiReg;
15699   unsigned SrcLoReg, SrcHiReg;
15700   unsigned MemOpndSlot;
15701
15702   unsigned CurOp = 0;
15703
15704   DstLoReg = MI->getOperand(CurOp++).getReg();
15705   DstHiReg = MI->getOperand(CurOp++).getReg();
15706   MemOpndSlot = CurOp;
15707   CurOp += X86::AddrNumOperands;
15708   SrcLoReg = MI->getOperand(CurOp++).getReg();
15709   SrcHiReg = MI->getOperand(CurOp++).getReg();
15710
15711   const TargetRegisterClass *RC = &X86::GR32RegClass;
15712   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15713
15714   unsigned t1L = MRI.createVirtualRegister(RC);
15715   unsigned t1H = MRI.createVirtualRegister(RC);
15716   unsigned t2L = MRI.createVirtualRegister(RC);
15717   unsigned t2H = MRI.createVirtualRegister(RC);
15718   unsigned t3L = MRI.createVirtualRegister(RC);
15719   unsigned t3H = MRI.createVirtualRegister(RC);
15720   unsigned t4L = MRI.createVirtualRegister(RC);
15721   unsigned t4H = MRI.createVirtualRegister(RC);
15722
15723   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15724   unsigned LOADOpc = X86::MOV32rm;
15725
15726   // For the atomic load-arith operator, we generate
15727   //
15728   //  thisMBB:
15729   //    t1L = LOAD [MI.addr + 0]
15730   //    t1H = LOAD [MI.addr + 4]
15731   //  mainMBB:
15732   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15733   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15734   //    t2L = OP MI.val.lo, t4L
15735   //    t2H = OP MI.val.hi, t4H
15736   //    EBX = t2L
15737   //    ECX = t2H
15738   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15739   //    t3L = EAX
15740   //    t3H = EDX
15741   //    JNE loop
15742   //  sinkMBB:
15743   //    dstL = t3L
15744   //    dstH = t3H
15745
15746   MachineBasicBlock *thisMBB = MBB;
15747   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15748   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15749   MF->insert(I, mainMBB);
15750   MF->insert(I, sinkMBB);
15751
15752   MachineInstrBuilder MIB;
15753
15754   // Transfer the remainder of BB and its successor edges to sinkMBB.
15755   sinkMBB->splice(sinkMBB->begin(), MBB,
15756                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15757   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15758
15759   // thisMBB:
15760   // Lo
15761   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15762   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15763     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15764     if (NewMO.isReg())
15765       NewMO.setIsKill(false);
15766     MIB.addOperand(NewMO);
15767   }
15768   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15769     unsigned flags = (*MMOI)->getFlags();
15770     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15771     MachineMemOperand *MMO =
15772       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15773                                (*MMOI)->getSize(),
15774                                (*MMOI)->getBaseAlignment(),
15775                                (*MMOI)->getTBAAInfo(),
15776                                (*MMOI)->getRanges());
15777     MIB.addMemOperand(MMO);
15778   };
15779   MachineInstr *LowMI = MIB;
15780
15781   // Hi
15782   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15783   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15784     if (i == X86::AddrDisp) {
15785       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15786     } else {
15787       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15788       if (NewMO.isReg())
15789         NewMO.setIsKill(false);
15790       MIB.addOperand(NewMO);
15791     }
15792   }
15793   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15794
15795   thisMBB->addSuccessor(mainMBB);
15796
15797   // mainMBB:
15798   MachineBasicBlock *origMainMBB = mainMBB;
15799
15800   // Add PHIs.
15801   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15802                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15803   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15804                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15805
15806   unsigned Opc = MI->getOpcode();
15807   switch (Opc) {
15808   default:
15809     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15810   case X86::ATOMAND6432:
15811   case X86::ATOMOR6432:
15812   case X86::ATOMXOR6432:
15813   case X86::ATOMADD6432:
15814   case X86::ATOMSUB6432: {
15815     unsigned HiOpc;
15816     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15817     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15818       .addReg(SrcLoReg);
15819     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15820       .addReg(SrcHiReg);
15821     break;
15822   }
15823   case X86::ATOMNAND6432: {
15824     unsigned HiOpc, NOTOpc;
15825     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15826     unsigned TmpL = MRI.createVirtualRegister(RC);
15827     unsigned TmpH = MRI.createVirtualRegister(RC);
15828     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15829       .addReg(t4L);
15830     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15831       .addReg(t4H);
15832     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15833     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15834     break;
15835   }
15836   case X86::ATOMMAX6432:
15837   case X86::ATOMMIN6432:
15838   case X86::ATOMUMAX6432:
15839   case X86::ATOMUMIN6432: {
15840     unsigned HiOpc;
15841     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15842     unsigned cL = MRI.createVirtualRegister(RC8);
15843     unsigned cH = MRI.createVirtualRegister(RC8);
15844     unsigned cL32 = MRI.createVirtualRegister(RC);
15845     unsigned cH32 = MRI.createVirtualRegister(RC);
15846     unsigned cc = MRI.createVirtualRegister(RC);
15847     // cl := cmp src_lo, lo
15848     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15849       .addReg(SrcLoReg).addReg(t4L);
15850     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15851     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15852     // ch := cmp src_hi, hi
15853     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15854       .addReg(SrcHiReg).addReg(t4H);
15855     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15856     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15857     // cc := if (src_hi == hi) ? cl : ch;
15858     if (Subtarget->hasCMov()) {
15859       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15860         .addReg(cH32).addReg(cL32);
15861     } else {
15862       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15863               .addReg(cH32).addReg(cL32)
15864               .addImm(X86::COND_E);
15865       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15866     }
15867     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15868     if (Subtarget->hasCMov()) {
15869       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15870         .addReg(SrcLoReg).addReg(t4L);
15871       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15872         .addReg(SrcHiReg).addReg(t4H);
15873     } else {
15874       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15875               .addReg(SrcLoReg).addReg(t4L)
15876               .addImm(X86::COND_NE);
15877       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15878       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15879       // 2nd CMOV lowering.
15880       mainMBB->addLiveIn(X86::EFLAGS);
15881       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15882               .addReg(SrcHiReg).addReg(t4H)
15883               .addImm(X86::COND_NE);
15884       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15885       // Replace the original PHI node as mainMBB is changed after CMOV
15886       // lowering.
15887       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15888         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15889       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15890         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15891       PhiL->eraseFromParent();
15892       PhiH->eraseFromParent();
15893     }
15894     break;
15895   }
15896   case X86::ATOMSWAP6432: {
15897     unsigned HiOpc;
15898     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15899     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15900     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15901     break;
15902   }
15903   }
15904
15905   // Copy EDX:EAX back from HiReg:LoReg
15906   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15907   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15908   // Copy ECX:EBX from t1H:t1L
15909   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15910   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15911
15912   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15913   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15914     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15915     if (NewMO.isReg())
15916       NewMO.setIsKill(false);
15917     MIB.addOperand(NewMO);
15918   }
15919   MIB.setMemRefs(MMOBegin, MMOEnd);
15920
15921   // Copy EDX:EAX back to t3H:t3L
15922   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15923   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15924
15925   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15926
15927   mainMBB->addSuccessor(origMainMBB);
15928   mainMBB->addSuccessor(sinkMBB);
15929
15930   // sinkMBB:
15931   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15932           TII->get(TargetOpcode::COPY), DstLoReg)
15933     .addReg(t3L);
15934   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15935           TII->get(TargetOpcode::COPY), DstHiReg)
15936     .addReg(t3H);
15937
15938   MI->eraseFromParent();
15939   return sinkMBB;
15940 }
15941
15942 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15943 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15944 // in the .td file.
15945 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15946                                        const TargetInstrInfo *TII) {
15947   unsigned Opc;
15948   switch (MI->getOpcode()) {
15949   default: llvm_unreachable("illegal opcode!");
15950   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15951   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15952   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15953   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15954   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15955   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15956   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15957   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15958   }
15959
15960   DebugLoc dl = MI->getDebugLoc();
15961   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15962
15963   unsigned NumArgs = MI->getNumOperands();
15964   for (unsigned i = 1; i < NumArgs; ++i) {
15965     MachineOperand &Op = MI->getOperand(i);
15966     if (!(Op.isReg() && Op.isImplicit()))
15967       MIB.addOperand(Op);
15968   }
15969   if (MI->hasOneMemOperand())
15970     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15971
15972   BuildMI(*BB, MI, dl,
15973     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15974     .addReg(X86::XMM0);
15975
15976   MI->eraseFromParent();
15977   return BB;
15978 }
15979
15980 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15981 // defs in an instruction pattern
15982 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15983                                        const TargetInstrInfo *TII) {
15984   unsigned Opc;
15985   switch (MI->getOpcode()) {
15986   default: llvm_unreachable("illegal opcode!");
15987   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15988   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15989   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15990   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15991   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15992   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15993   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15994   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15995   }
15996
15997   DebugLoc dl = MI->getDebugLoc();
15998   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15999
16000   unsigned NumArgs = MI->getNumOperands(); // remove the results
16001   for (unsigned i = 1; i < NumArgs; ++i) {
16002     MachineOperand &Op = MI->getOperand(i);
16003     if (!(Op.isReg() && Op.isImplicit()))
16004       MIB.addOperand(Op);
16005   }
16006   if (MI->hasOneMemOperand())
16007     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16008
16009   BuildMI(*BB, MI, dl,
16010     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16011     .addReg(X86::ECX);
16012
16013   MI->eraseFromParent();
16014   return BB;
16015 }
16016
16017 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16018                                        const TargetInstrInfo *TII,
16019                                        const X86Subtarget* Subtarget) {
16020   DebugLoc dl = MI->getDebugLoc();
16021
16022   // Address into RAX/EAX, other two args into ECX, EDX.
16023   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16024   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16025   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16026   for (int i = 0; i < X86::AddrNumOperands; ++i)
16027     MIB.addOperand(MI->getOperand(i));
16028
16029   unsigned ValOps = X86::AddrNumOperands;
16030   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16031     .addReg(MI->getOperand(ValOps).getReg());
16032   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16033     .addReg(MI->getOperand(ValOps+1).getReg());
16034
16035   // The instruction doesn't actually take any operands though.
16036   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16037
16038   MI->eraseFromParent(); // The pseudo is gone now.
16039   return BB;
16040 }
16041
16042 MachineBasicBlock *
16043 X86TargetLowering::EmitVAARG64WithCustomInserter(
16044                    MachineInstr *MI,
16045                    MachineBasicBlock *MBB) const {
16046   // Emit va_arg instruction on X86-64.
16047
16048   // Operands to this pseudo-instruction:
16049   // 0  ) Output        : destination address (reg)
16050   // 1-5) Input         : va_list address (addr, i64mem)
16051   // 6  ) ArgSize       : Size (in bytes) of vararg type
16052   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16053   // 8  ) Align         : Alignment of type
16054   // 9  ) EFLAGS (implicit-def)
16055
16056   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16057   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16058
16059   unsigned DestReg = MI->getOperand(0).getReg();
16060   MachineOperand &Base = MI->getOperand(1);
16061   MachineOperand &Scale = MI->getOperand(2);
16062   MachineOperand &Index = MI->getOperand(3);
16063   MachineOperand &Disp = MI->getOperand(4);
16064   MachineOperand &Segment = MI->getOperand(5);
16065   unsigned ArgSize = MI->getOperand(6).getImm();
16066   unsigned ArgMode = MI->getOperand(7).getImm();
16067   unsigned Align = MI->getOperand(8).getImm();
16068
16069   // Memory Reference
16070   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16071   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16072   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16073
16074   // Machine Information
16075   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16076   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16077   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16078   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16079   DebugLoc DL = MI->getDebugLoc();
16080
16081   // struct va_list {
16082   //   i32   gp_offset
16083   //   i32   fp_offset
16084   //   i64   overflow_area (address)
16085   //   i64   reg_save_area (address)
16086   // }
16087   // sizeof(va_list) = 24
16088   // alignment(va_list) = 8
16089
16090   unsigned TotalNumIntRegs = 6;
16091   unsigned TotalNumXMMRegs = 8;
16092   bool UseGPOffset = (ArgMode == 1);
16093   bool UseFPOffset = (ArgMode == 2);
16094   unsigned MaxOffset = TotalNumIntRegs * 8 +
16095                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16096
16097   /* Align ArgSize to a multiple of 8 */
16098   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16099   bool NeedsAlign = (Align > 8);
16100
16101   MachineBasicBlock *thisMBB = MBB;
16102   MachineBasicBlock *overflowMBB;
16103   MachineBasicBlock *offsetMBB;
16104   MachineBasicBlock *endMBB;
16105
16106   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16107   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16108   unsigned OffsetReg = 0;
16109
16110   if (!UseGPOffset && !UseFPOffset) {
16111     // If we only pull from the overflow region, we don't create a branch.
16112     // We don't need to alter control flow.
16113     OffsetDestReg = 0; // unused
16114     OverflowDestReg = DestReg;
16115
16116     offsetMBB = nullptr;
16117     overflowMBB = thisMBB;
16118     endMBB = thisMBB;
16119   } else {
16120     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16121     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16122     // If not, pull from overflow_area. (branch to overflowMBB)
16123     //
16124     //       thisMBB
16125     //         |     .
16126     //         |        .
16127     //     offsetMBB   overflowMBB
16128     //         |        .
16129     //         |     .
16130     //        endMBB
16131
16132     // Registers for the PHI in endMBB
16133     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16134     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16135
16136     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16137     MachineFunction *MF = MBB->getParent();
16138     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16139     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16140     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16141
16142     MachineFunction::iterator MBBIter = MBB;
16143     ++MBBIter;
16144
16145     // Insert the new basic blocks
16146     MF->insert(MBBIter, offsetMBB);
16147     MF->insert(MBBIter, overflowMBB);
16148     MF->insert(MBBIter, endMBB);
16149
16150     // Transfer the remainder of MBB and its successor edges to endMBB.
16151     endMBB->splice(endMBB->begin(), thisMBB,
16152                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16153     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16154
16155     // Make offsetMBB and overflowMBB successors of thisMBB
16156     thisMBB->addSuccessor(offsetMBB);
16157     thisMBB->addSuccessor(overflowMBB);
16158
16159     // endMBB is a successor of both offsetMBB and overflowMBB
16160     offsetMBB->addSuccessor(endMBB);
16161     overflowMBB->addSuccessor(endMBB);
16162
16163     // Load the offset value into a register
16164     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16165     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16166       .addOperand(Base)
16167       .addOperand(Scale)
16168       .addOperand(Index)
16169       .addDisp(Disp, UseFPOffset ? 4 : 0)
16170       .addOperand(Segment)
16171       .setMemRefs(MMOBegin, MMOEnd);
16172
16173     // Check if there is enough room left to pull this argument.
16174     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16175       .addReg(OffsetReg)
16176       .addImm(MaxOffset + 8 - ArgSizeA8);
16177
16178     // Branch to "overflowMBB" if offset >= max
16179     // Fall through to "offsetMBB" otherwise
16180     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16181       .addMBB(overflowMBB);
16182   }
16183
16184   // In offsetMBB, emit code to use the reg_save_area.
16185   if (offsetMBB) {
16186     assert(OffsetReg != 0);
16187
16188     // Read the reg_save_area address.
16189     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16190     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16191       .addOperand(Base)
16192       .addOperand(Scale)
16193       .addOperand(Index)
16194       .addDisp(Disp, 16)
16195       .addOperand(Segment)
16196       .setMemRefs(MMOBegin, MMOEnd);
16197
16198     // Zero-extend the offset
16199     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16200       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16201         .addImm(0)
16202         .addReg(OffsetReg)
16203         .addImm(X86::sub_32bit);
16204
16205     // Add the offset to the reg_save_area to get the final address.
16206     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16207       .addReg(OffsetReg64)
16208       .addReg(RegSaveReg);
16209
16210     // Compute the offset for the next argument
16211     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16212     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16213       .addReg(OffsetReg)
16214       .addImm(UseFPOffset ? 16 : 8);
16215
16216     // Store it back into the va_list.
16217     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16218       .addOperand(Base)
16219       .addOperand(Scale)
16220       .addOperand(Index)
16221       .addDisp(Disp, UseFPOffset ? 4 : 0)
16222       .addOperand(Segment)
16223       .addReg(NextOffsetReg)
16224       .setMemRefs(MMOBegin, MMOEnd);
16225
16226     // Jump to endMBB
16227     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16228       .addMBB(endMBB);
16229   }
16230
16231   //
16232   // Emit code to use overflow area
16233   //
16234
16235   // Load the overflow_area address into a register.
16236   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16237   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16238     .addOperand(Base)
16239     .addOperand(Scale)
16240     .addOperand(Index)
16241     .addDisp(Disp, 8)
16242     .addOperand(Segment)
16243     .setMemRefs(MMOBegin, MMOEnd);
16244
16245   // If we need to align it, do so. Otherwise, just copy the address
16246   // to OverflowDestReg.
16247   if (NeedsAlign) {
16248     // Align the overflow address
16249     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16250     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16251
16252     // aligned_addr = (addr + (align-1)) & ~(align-1)
16253     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16254       .addReg(OverflowAddrReg)
16255       .addImm(Align-1);
16256
16257     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16258       .addReg(TmpReg)
16259       .addImm(~(uint64_t)(Align-1));
16260   } else {
16261     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16262       .addReg(OverflowAddrReg);
16263   }
16264
16265   // Compute the next overflow address after this argument.
16266   // (the overflow address should be kept 8-byte aligned)
16267   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16268   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16269     .addReg(OverflowDestReg)
16270     .addImm(ArgSizeA8);
16271
16272   // Store the new overflow address.
16273   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16274     .addOperand(Base)
16275     .addOperand(Scale)
16276     .addOperand(Index)
16277     .addDisp(Disp, 8)
16278     .addOperand(Segment)
16279     .addReg(NextAddrReg)
16280     .setMemRefs(MMOBegin, MMOEnd);
16281
16282   // If we branched, emit the PHI to the front of endMBB.
16283   if (offsetMBB) {
16284     BuildMI(*endMBB, endMBB->begin(), DL,
16285             TII->get(X86::PHI), DestReg)
16286       .addReg(OffsetDestReg).addMBB(offsetMBB)
16287       .addReg(OverflowDestReg).addMBB(overflowMBB);
16288   }
16289
16290   // Erase the pseudo instruction
16291   MI->eraseFromParent();
16292
16293   return endMBB;
16294 }
16295
16296 MachineBasicBlock *
16297 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16298                                                  MachineInstr *MI,
16299                                                  MachineBasicBlock *MBB) const {
16300   // Emit code to save XMM registers to the stack. The ABI says that the
16301   // number of registers to save is given in %al, so it's theoretically
16302   // possible to do an indirect jump trick to avoid saving all of them,
16303   // however this code takes a simpler approach and just executes all
16304   // of the stores if %al is non-zero. It's less code, and it's probably
16305   // easier on the hardware branch predictor, and stores aren't all that
16306   // expensive anyway.
16307
16308   // Create the new basic blocks. One block contains all the XMM stores,
16309   // and one block is the final destination regardless of whether any
16310   // stores were performed.
16311   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16312   MachineFunction *F = MBB->getParent();
16313   MachineFunction::iterator MBBIter = MBB;
16314   ++MBBIter;
16315   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16316   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16317   F->insert(MBBIter, XMMSaveMBB);
16318   F->insert(MBBIter, EndMBB);
16319
16320   // Transfer the remainder of MBB and its successor edges to EndMBB.
16321   EndMBB->splice(EndMBB->begin(), MBB,
16322                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16323   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16324
16325   // The original block will now fall through to the XMM save block.
16326   MBB->addSuccessor(XMMSaveMBB);
16327   // The XMMSaveMBB will fall through to the end block.
16328   XMMSaveMBB->addSuccessor(EndMBB);
16329
16330   // Now add the instructions.
16331   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16332   DebugLoc DL = MI->getDebugLoc();
16333
16334   unsigned CountReg = MI->getOperand(0).getReg();
16335   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16336   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16337
16338   if (!Subtarget->isTargetWin64()) {
16339     // If %al is 0, branch around the XMM save block.
16340     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16341     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16342     MBB->addSuccessor(EndMBB);
16343   }
16344
16345   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16346   // that was just emitted, but clearly shouldn't be "saved".
16347   assert((MI->getNumOperands() <= 3 ||
16348           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16349           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16350          && "Expected last argument to be EFLAGS");
16351   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16352   // In the XMM save block, save all the XMM argument registers.
16353   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16354     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16355     MachineMemOperand *MMO =
16356       F->getMachineMemOperand(
16357           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16358         MachineMemOperand::MOStore,
16359         /*Size=*/16, /*Align=*/16);
16360     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16361       .addFrameIndex(RegSaveFrameIndex)
16362       .addImm(/*Scale=*/1)
16363       .addReg(/*IndexReg=*/0)
16364       .addImm(/*Disp=*/Offset)
16365       .addReg(/*Segment=*/0)
16366       .addReg(MI->getOperand(i).getReg())
16367       .addMemOperand(MMO);
16368   }
16369
16370   MI->eraseFromParent();   // The pseudo instruction is gone now.
16371
16372   return EndMBB;
16373 }
16374
16375 // The EFLAGS operand of SelectItr might be missing a kill marker
16376 // because there were multiple uses of EFLAGS, and ISel didn't know
16377 // which to mark. Figure out whether SelectItr should have had a
16378 // kill marker, and set it if it should. Returns the correct kill
16379 // marker value.
16380 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16381                                      MachineBasicBlock* BB,
16382                                      const TargetRegisterInfo* TRI) {
16383   // Scan forward through BB for a use/def of EFLAGS.
16384   MachineBasicBlock::iterator miI(std::next(SelectItr));
16385   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16386     const MachineInstr& mi = *miI;
16387     if (mi.readsRegister(X86::EFLAGS))
16388       return false;
16389     if (mi.definesRegister(X86::EFLAGS))
16390       break; // Should have kill-flag - update below.
16391   }
16392
16393   // If we hit the end of the block, check whether EFLAGS is live into a
16394   // successor.
16395   if (miI == BB->end()) {
16396     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16397                                           sEnd = BB->succ_end();
16398          sItr != sEnd; ++sItr) {
16399       MachineBasicBlock* succ = *sItr;
16400       if (succ->isLiveIn(X86::EFLAGS))
16401         return false;
16402     }
16403   }
16404
16405   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16406   // out. SelectMI should have a kill flag on EFLAGS.
16407   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16408   return true;
16409 }
16410
16411 MachineBasicBlock *
16412 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16413                                      MachineBasicBlock *BB) const {
16414   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16415   DebugLoc DL = MI->getDebugLoc();
16416
16417   // To "insert" a SELECT_CC instruction, we actually have to insert the
16418   // diamond control-flow pattern.  The incoming instruction knows the
16419   // destination vreg to set, the condition code register to branch on, the
16420   // true/false values to select between, and a branch opcode to use.
16421   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16422   MachineFunction::iterator It = BB;
16423   ++It;
16424
16425   //  thisMBB:
16426   //  ...
16427   //   TrueVal = ...
16428   //   cmpTY ccX, r1, r2
16429   //   bCC copy1MBB
16430   //   fallthrough --> copy0MBB
16431   MachineBasicBlock *thisMBB = BB;
16432   MachineFunction *F = BB->getParent();
16433   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16434   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16435   F->insert(It, copy0MBB);
16436   F->insert(It, sinkMBB);
16437
16438   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16439   // live into the sink and copy blocks.
16440   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16441   if (!MI->killsRegister(X86::EFLAGS) &&
16442       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16443     copy0MBB->addLiveIn(X86::EFLAGS);
16444     sinkMBB->addLiveIn(X86::EFLAGS);
16445   }
16446
16447   // Transfer the remainder of BB and its successor edges to sinkMBB.
16448   sinkMBB->splice(sinkMBB->begin(), BB,
16449                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16450   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16451
16452   // Add the true and fallthrough blocks as its successors.
16453   BB->addSuccessor(copy0MBB);
16454   BB->addSuccessor(sinkMBB);
16455
16456   // Create the conditional branch instruction.
16457   unsigned Opc =
16458     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16459   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16460
16461   //  copy0MBB:
16462   //   %FalseValue = ...
16463   //   # fallthrough to sinkMBB
16464   copy0MBB->addSuccessor(sinkMBB);
16465
16466   //  sinkMBB:
16467   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16468   //  ...
16469   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16470           TII->get(X86::PHI), MI->getOperand(0).getReg())
16471     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16472     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16473
16474   MI->eraseFromParent();   // The pseudo instruction is gone now.
16475   return sinkMBB;
16476 }
16477
16478 MachineBasicBlock *
16479 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16480                                         bool Is64Bit) const {
16481   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16482   DebugLoc DL = MI->getDebugLoc();
16483   MachineFunction *MF = BB->getParent();
16484   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16485
16486   assert(MF->shouldSplitStack());
16487
16488   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16489   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16490
16491   // BB:
16492   //  ... [Till the alloca]
16493   // If stacklet is not large enough, jump to mallocMBB
16494   //
16495   // bumpMBB:
16496   //  Allocate by subtracting from RSP
16497   //  Jump to continueMBB
16498   //
16499   // mallocMBB:
16500   //  Allocate by call to runtime
16501   //
16502   // continueMBB:
16503   //  ...
16504   //  [rest of original BB]
16505   //
16506
16507   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16508   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16509   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16510
16511   MachineRegisterInfo &MRI = MF->getRegInfo();
16512   const TargetRegisterClass *AddrRegClass =
16513     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16514
16515   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16516     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16517     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16518     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16519     sizeVReg = MI->getOperand(1).getReg(),
16520     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16521
16522   MachineFunction::iterator MBBIter = BB;
16523   ++MBBIter;
16524
16525   MF->insert(MBBIter, bumpMBB);
16526   MF->insert(MBBIter, mallocMBB);
16527   MF->insert(MBBIter, continueMBB);
16528
16529   continueMBB->splice(continueMBB->begin(), BB,
16530                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16531   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16532
16533   // Add code to the main basic block to check if the stack limit has been hit,
16534   // and if so, jump to mallocMBB otherwise to bumpMBB.
16535   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16536   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16537     .addReg(tmpSPVReg).addReg(sizeVReg);
16538   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16539     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16540     .addReg(SPLimitVReg);
16541   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16542
16543   // bumpMBB simply decreases the stack pointer, since we know the current
16544   // stacklet has enough space.
16545   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16546     .addReg(SPLimitVReg);
16547   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16548     .addReg(SPLimitVReg);
16549   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16550
16551   // Calls into a routine in libgcc to allocate more space from the heap.
16552   const uint32_t *RegMask =
16553     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16554   if (Is64Bit) {
16555     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16556       .addReg(sizeVReg);
16557     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16558       .addExternalSymbol("__morestack_allocate_stack_space")
16559       .addRegMask(RegMask)
16560       .addReg(X86::RDI, RegState::Implicit)
16561       .addReg(X86::RAX, RegState::ImplicitDefine);
16562   } else {
16563     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16564       .addImm(12);
16565     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16566     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16567       .addExternalSymbol("__morestack_allocate_stack_space")
16568       .addRegMask(RegMask)
16569       .addReg(X86::EAX, RegState::ImplicitDefine);
16570   }
16571
16572   if (!Is64Bit)
16573     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16574       .addImm(16);
16575
16576   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16577     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16578   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16579
16580   // Set up the CFG correctly.
16581   BB->addSuccessor(bumpMBB);
16582   BB->addSuccessor(mallocMBB);
16583   mallocMBB->addSuccessor(continueMBB);
16584   bumpMBB->addSuccessor(continueMBB);
16585
16586   // Take care of the PHI nodes.
16587   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16588           MI->getOperand(0).getReg())
16589     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16590     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16591
16592   // Delete the original pseudo instruction.
16593   MI->eraseFromParent();
16594
16595   // And we're done.
16596   return continueMBB;
16597 }
16598
16599 MachineBasicBlock *
16600 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16601                                           MachineBasicBlock *BB) const {
16602   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16603   DebugLoc DL = MI->getDebugLoc();
16604
16605   assert(!Subtarget->isTargetMacho());
16606
16607   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16608   // non-trivial part is impdef of ESP.
16609
16610   if (Subtarget->isTargetWin64()) {
16611     if (Subtarget->isTargetCygMing()) {
16612       // ___chkstk(Mingw64):
16613       // Clobbers R10, R11, RAX and EFLAGS.
16614       // Updates RSP.
16615       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16616         .addExternalSymbol("___chkstk")
16617         .addReg(X86::RAX, RegState::Implicit)
16618         .addReg(X86::RSP, RegState::Implicit)
16619         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16620         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16621         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16622     } else {
16623       // __chkstk(MSVCRT): does not update stack pointer.
16624       // Clobbers R10, R11 and EFLAGS.
16625       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16626         .addExternalSymbol("__chkstk")
16627         .addReg(X86::RAX, RegState::Implicit)
16628         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16629       // RAX has the offset to be subtracted from RSP.
16630       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16631         .addReg(X86::RSP)
16632         .addReg(X86::RAX);
16633     }
16634   } else {
16635     const char *StackProbeSymbol =
16636       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16637
16638     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16639       .addExternalSymbol(StackProbeSymbol)
16640       .addReg(X86::EAX, RegState::Implicit)
16641       .addReg(X86::ESP, RegState::Implicit)
16642       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16643       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16644       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16645   }
16646
16647   MI->eraseFromParent();   // The pseudo instruction is gone now.
16648   return BB;
16649 }
16650
16651 MachineBasicBlock *
16652 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16653                                       MachineBasicBlock *BB) const {
16654   // This is pretty easy.  We're taking the value that we received from
16655   // our load from the relocation, sticking it in either RDI (x86-64)
16656   // or EAX and doing an indirect call.  The return value will then
16657   // be in the normal return register.
16658   const X86InstrInfo *TII
16659     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16660   DebugLoc DL = MI->getDebugLoc();
16661   MachineFunction *F = BB->getParent();
16662
16663   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16664   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16665
16666   // Get a register mask for the lowered call.
16667   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16668   // proper register mask.
16669   const uint32_t *RegMask =
16670     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16671   if (Subtarget->is64Bit()) {
16672     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16673                                       TII->get(X86::MOV64rm), X86::RDI)
16674     .addReg(X86::RIP)
16675     .addImm(0).addReg(0)
16676     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16677                       MI->getOperand(3).getTargetFlags())
16678     .addReg(0);
16679     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16680     addDirectMem(MIB, X86::RDI);
16681     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16682   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16683     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16684                                       TII->get(X86::MOV32rm), X86::EAX)
16685     .addReg(0)
16686     .addImm(0).addReg(0)
16687     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16688                       MI->getOperand(3).getTargetFlags())
16689     .addReg(0);
16690     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16691     addDirectMem(MIB, X86::EAX);
16692     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16693   } else {
16694     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16695                                       TII->get(X86::MOV32rm), X86::EAX)
16696     .addReg(TII->getGlobalBaseReg(F))
16697     .addImm(0).addReg(0)
16698     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16699                       MI->getOperand(3).getTargetFlags())
16700     .addReg(0);
16701     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16702     addDirectMem(MIB, X86::EAX);
16703     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16704   }
16705
16706   MI->eraseFromParent(); // The pseudo instruction is gone now.
16707   return BB;
16708 }
16709
16710 MachineBasicBlock *
16711 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16712                                     MachineBasicBlock *MBB) const {
16713   DebugLoc DL = MI->getDebugLoc();
16714   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16715
16716   MachineFunction *MF = MBB->getParent();
16717   MachineRegisterInfo &MRI = MF->getRegInfo();
16718
16719   const BasicBlock *BB = MBB->getBasicBlock();
16720   MachineFunction::iterator I = MBB;
16721   ++I;
16722
16723   // Memory Reference
16724   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16725   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16726
16727   unsigned DstReg;
16728   unsigned MemOpndSlot = 0;
16729
16730   unsigned CurOp = 0;
16731
16732   DstReg = MI->getOperand(CurOp++).getReg();
16733   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16734   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16735   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16736   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16737
16738   MemOpndSlot = CurOp;
16739
16740   MVT PVT = getPointerTy();
16741   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16742          "Invalid Pointer Size!");
16743
16744   // For v = setjmp(buf), we generate
16745   //
16746   // thisMBB:
16747   //  buf[LabelOffset] = restoreMBB
16748   //  SjLjSetup restoreMBB
16749   //
16750   // mainMBB:
16751   //  v_main = 0
16752   //
16753   // sinkMBB:
16754   //  v = phi(main, restore)
16755   //
16756   // restoreMBB:
16757   //  v_restore = 1
16758
16759   MachineBasicBlock *thisMBB = MBB;
16760   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16761   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16762   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16763   MF->insert(I, mainMBB);
16764   MF->insert(I, sinkMBB);
16765   MF->push_back(restoreMBB);
16766
16767   MachineInstrBuilder MIB;
16768
16769   // Transfer the remainder of BB and its successor edges to sinkMBB.
16770   sinkMBB->splice(sinkMBB->begin(), MBB,
16771                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16772   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16773
16774   // thisMBB:
16775   unsigned PtrStoreOpc = 0;
16776   unsigned LabelReg = 0;
16777   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16778   Reloc::Model RM = getTargetMachine().getRelocationModel();
16779   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16780                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16781
16782   // Prepare IP either in reg or imm.
16783   if (!UseImmLabel) {
16784     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16785     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16786     LabelReg = MRI.createVirtualRegister(PtrRC);
16787     if (Subtarget->is64Bit()) {
16788       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16789               .addReg(X86::RIP)
16790               .addImm(0)
16791               .addReg(0)
16792               .addMBB(restoreMBB)
16793               .addReg(0);
16794     } else {
16795       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16796       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16797               .addReg(XII->getGlobalBaseReg(MF))
16798               .addImm(0)
16799               .addReg(0)
16800               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16801               .addReg(0);
16802     }
16803   } else
16804     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16805   // Store IP
16806   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16807   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16808     if (i == X86::AddrDisp)
16809       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16810     else
16811       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16812   }
16813   if (!UseImmLabel)
16814     MIB.addReg(LabelReg);
16815   else
16816     MIB.addMBB(restoreMBB);
16817   MIB.setMemRefs(MMOBegin, MMOEnd);
16818   // Setup
16819   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16820           .addMBB(restoreMBB);
16821
16822   const X86RegisterInfo *RegInfo =
16823     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16824   MIB.addRegMask(RegInfo->getNoPreservedMask());
16825   thisMBB->addSuccessor(mainMBB);
16826   thisMBB->addSuccessor(restoreMBB);
16827
16828   // mainMBB:
16829   //  EAX = 0
16830   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16831   mainMBB->addSuccessor(sinkMBB);
16832
16833   // sinkMBB:
16834   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16835           TII->get(X86::PHI), DstReg)
16836     .addReg(mainDstReg).addMBB(mainMBB)
16837     .addReg(restoreDstReg).addMBB(restoreMBB);
16838
16839   // restoreMBB:
16840   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16841   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16842   restoreMBB->addSuccessor(sinkMBB);
16843
16844   MI->eraseFromParent();
16845   return sinkMBB;
16846 }
16847
16848 MachineBasicBlock *
16849 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16850                                      MachineBasicBlock *MBB) const {
16851   DebugLoc DL = MI->getDebugLoc();
16852   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16853
16854   MachineFunction *MF = MBB->getParent();
16855   MachineRegisterInfo &MRI = MF->getRegInfo();
16856
16857   // Memory Reference
16858   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16859   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16860
16861   MVT PVT = getPointerTy();
16862   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16863          "Invalid Pointer Size!");
16864
16865   const TargetRegisterClass *RC =
16866     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16867   unsigned Tmp = MRI.createVirtualRegister(RC);
16868   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16869   const X86RegisterInfo *RegInfo =
16870     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16871   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16872   unsigned SP = RegInfo->getStackRegister();
16873
16874   MachineInstrBuilder MIB;
16875
16876   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16877   const int64_t SPOffset = 2 * PVT.getStoreSize();
16878
16879   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16880   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16881
16882   // Reload FP
16883   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16884   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16885     MIB.addOperand(MI->getOperand(i));
16886   MIB.setMemRefs(MMOBegin, MMOEnd);
16887   // Reload IP
16888   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16889   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16890     if (i == X86::AddrDisp)
16891       MIB.addDisp(MI->getOperand(i), LabelOffset);
16892     else
16893       MIB.addOperand(MI->getOperand(i));
16894   }
16895   MIB.setMemRefs(MMOBegin, MMOEnd);
16896   // Reload SP
16897   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16898   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16899     if (i == X86::AddrDisp)
16900       MIB.addDisp(MI->getOperand(i), SPOffset);
16901     else
16902       MIB.addOperand(MI->getOperand(i));
16903   }
16904   MIB.setMemRefs(MMOBegin, MMOEnd);
16905   // Jump
16906   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16907
16908   MI->eraseFromParent();
16909   return MBB;
16910 }
16911
16912 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16913 // accumulator loops. Writing back to the accumulator allows the coalescer
16914 // to remove extra copies in the loop.   
16915 MachineBasicBlock *
16916 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16917                                  MachineBasicBlock *MBB) const {
16918   MachineOperand &AddendOp = MI->getOperand(3);
16919
16920   // Bail out early if the addend isn't a register - we can't switch these.
16921   if (!AddendOp.isReg())
16922     return MBB;
16923
16924   MachineFunction &MF = *MBB->getParent();
16925   MachineRegisterInfo &MRI = MF.getRegInfo();
16926
16927   // Check whether the addend is defined by a PHI:
16928   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16929   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16930   if (!AddendDef.isPHI())
16931     return MBB;
16932
16933   // Look for the following pattern:
16934   // loop:
16935   //   %addend = phi [%entry, 0], [%loop, %result]
16936   //   ...
16937   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16938
16939   // Replace with:
16940   //   loop:
16941   //   %addend = phi [%entry, 0], [%loop, %result]
16942   //   ...
16943   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16944
16945   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16946     assert(AddendDef.getOperand(i).isReg());
16947     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16948     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16949     if (&PHISrcInst == MI) {
16950       // Found a matching instruction.
16951       unsigned NewFMAOpc = 0;
16952       switch (MI->getOpcode()) {
16953         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16954         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16955         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16956         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16957         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16958         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16959         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16960         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16961         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16962         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16963         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16964         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16965         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16966         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16967         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16968         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16969         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16970         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16971         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16972         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16973         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16974         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16975         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16976         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16977         default: llvm_unreachable("Unrecognized FMA variant.");
16978       }
16979
16980       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16981       MachineInstrBuilder MIB =
16982         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16983         .addOperand(MI->getOperand(0))
16984         .addOperand(MI->getOperand(3))
16985         .addOperand(MI->getOperand(2))
16986         .addOperand(MI->getOperand(1));
16987       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16988       MI->eraseFromParent();
16989     }
16990   }
16991
16992   return MBB;
16993 }
16994
16995 MachineBasicBlock *
16996 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16997                                                MachineBasicBlock *BB) const {
16998   switch (MI->getOpcode()) {
16999   default: llvm_unreachable("Unexpected instr type to insert");
17000   case X86::TAILJMPd64:
17001   case X86::TAILJMPr64:
17002   case X86::TAILJMPm64:
17003     llvm_unreachable("TAILJMP64 would not be touched here.");
17004   case X86::TCRETURNdi64:
17005   case X86::TCRETURNri64:
17006   case X86::TCRETURNmi64:
17007     return BB;
17008   case X86::WIN_ALLOCA:
17009     return EmitLoweredWinAlloca(MI, BB);
17010   case X86::SEG_ALLOCA_32:
17011     return EmitLoweredSegAlloca(MI, BB, false);
17012   case X86::SEG_ALLOCA_64:
17013     return EmitLoweredSegAlloca(MI, BB, true);
17014   case X86::TLSCall_32:
17015   case X86::TLSCall_64:
17016     return EmitLoweredTLSCall(MI, BB);
17017   case X86::CMOV_GR8:
17018   case X86::CMOV_FR32:
17019   case X86::CMOV_FR64:
17020   case X86::CMOV_V4F32:
17021   case X86::CMOV_V2F64:
17022   case X86::CMOV_V2I64:
17023   case X86::CMOV_V8F32:
17024   case X86::CMOV_V4F64:
17025   case X86::CMOV_V4I64:
17026   case X86::CMOV_V16F32:
17027   case X86::CMOV_V8F64:
17028   case X86::CMOV_V8I64:
17029   case X86::CMOV_GR16:
17030   case X86::CMOV_GR32:
17031   case X86::CMOV_RFP32:
17032   case X86::CMOV_RFP64:
17033   case X86::CMOV_RFP80:
17034     return EmitLoweredSelect(MI, BB);
17035
17036   case X86::FP32_TO_INT16_IN_MEM:
17037   case X86::FP32_TO_INT32_IN_MEM:
17038   case X86::FP32_TO_INT64_IN_MEM:
17039   case X86::FP64_TO_INT16_IN_MEM:
17040   case X86::FP64_TO_INT32_IN_MEM:
17041   case X86::FP64_TO_INT64_IN_MEM:
17042   case X86::FP80_TO_INT16_IN_MEM:
17043   case X86::FP80_TO_INT32_IN_MEM:
17044   case X86::FP80_TO_INT64_IN_MEM: {
17045     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17046     DebugLoc DL = MI->getDebugLoc();
17047
17048     // Change the floating point control register to use "round towards zero"
17049     // mode when truncating to an integer value.
17050     MachineFunction *F = BB->getParent();
17051     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17052     addFrameReference(BuildMI(*BB, MI, DL,
17053                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17054
17055     // Load the old value of the high byte of the control word...
17056     unsigned OldCW =
17057       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17058     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17059                       CWFrameIdx);
17060
17061     // Set the high part to be round to zero...
17062     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17063       .addImm(0xC7F);
17064
17065     // Reload the modified control word now...
17066     addFrameReference(BuildMI(*BB, MI, DL,
17067                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17068
17069     // Restore the memory image of control word to original value
17070     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17071       .addReg(OldCW);
17072
17073     // Get the X86 opcode to use.
17074     unsigned Opc;
17075     switch (MI->getOpcode()) {
17076     default: llvm_unreachable("illegal opcode!");
17077     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17078     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17079     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17080     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17081     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17082     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17083     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17084     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17085     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17086     }
17087
17088     X86AddressMode AM;
17089     MachineOperand &Op = MI->getOperand(0);
17090     if (Op.isReg()) {
17091       AM.BaseType = X86AddressMode::RegBase;
17092       AM.Base.Reg = Op.getReg();
17093     } else {
17094       AM.BaseType = X86AddressMode::FrameIndexBase;
17095       AM.Base.FrameIndex = Op.getIndex();
17096     }
17097     Op = MI->getOperand(1);
17098     if (Op.isImm())
17099       AM.Scale = Op.getImm();
17100     Op = MI->getOperand(2);
17101     if (Op.isImm())
17102       AM.IndexReg = Op.getImm();
17103     Op = MI->getOperand(3);
17104     if (Op.isGlobal()) {
17105       AM.GV = Op.getGlobal();
17106     } else {
17107       AM.Disp = Op.getImm();
17108     }
17109     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17110                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17111
17112     // Reload the original control word now.
17113     addFrameReference(BuildMI(*BB, MI, DL,
17114                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17115
17116     MI->eraseFromParent();   // The pseudo instruction is gone now.
17117     return BB;
17118   }
17119     // String/text processing lowering.
17120   case X86::PCMPISTRM128REG:
17121   case X86::VPCMPISTRM128REG:
17122   case X86::PCMPISTRM128MEM:
17123   case X86::VPCMPISTRM128MEM:
17124   case X86::PCMPESTRM128REG:
17125   case X86::VPCMPESTRM128REG:
17126   case X86::PCMPESTRM128MEM:
17127   case X86::VPCMPESTRM128MEM:
17128     assert(Subtarget->hasSSE42() &&
17129            "Target must have SSE4.2 or AVX features enabled");
17130     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17131
17132   // String/text processing lowering.
17133   case X86::PCMPISTRIREG:
17134   case X86::VPCMPISTRIREG:
17135   case X86::PCMPISTRIMEM:
17136   case X86::VPCMPISTRIMEM:
17137   case X86::PCMPESTRIREG:
17138   case X86::VPCMPESTRIREG:
17139   case X86::PCMPESTRIMEM:
17140   case X86::VPCMPESTRIMEM:
17141     assert(Subtarget->hasSSE42() &&
17142            "Target must have SSE4.2 or AVX features enabled");
17143     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17144
17145   // Thread synchronization.
17146   case X86::MONITOR:
17147     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17148
17149   // xbegin
17150   case X86::XBEGIN:
17151     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17152
17153   // Atomic Lowering.
17154   case X86::ATOMAND8:
17155   case X86::ATOMAND16:
17156   case X86::ATOMAND32:
17157   case X86::ATOMAND64:
17158     // Fall through
17159   case X86::ATOMOR8:
17160   case X86::ATOMOR16:
17161   case X86::ATOMOR32:
17162   case X86::ATOMOR64:
17163     // Fall through
17164   case X86::ATOMXOR16:
17165   case X86::ATOMXOR8:
17166   case X86::ATOMXOR32:
17167   case X86::ATOMXOR64:
17168     // Fall through
17169   case X86::ATOMNAND8:
17170   case X86::ATOMNAND16:
17171   case X86::ATOMNAND32:
17172   case X86::ATOMNAND64:
17173     // Fall through
17174   case X86::ATOMMAX8:
17175   case X86::ATOMMAX16:
17176   case X86::ATOMMAX32:
17177   case X86::ATOMMAX64:
17178     // Fall through
17179   case X86::ATOMMIN8:
17180   case X86::ATOMMIN16:
17181   case X86::ATOMMIN32:
17182   case X86::ATOMMIN64:
17183     // Fall through
17184   case X86::ATOMUMAX8:
17185   case X86::ATOMUMAX16:
17186   case X86::ATOMUMAX32:
17187   case X86::ATOMUMAX64:
17188     // Fall through
17189   case X86::ATOMUMIN8:
17190   case X86::ATOMUMIN16:
17191   case X86::ATOMUMIN32:
17192   case X86::ATOMUMIN64:
17193     return EmitAtomicLoadArith(MI, BB);
17194
17195   // This group does 64-bit operations on a 32-bit host.
17196   case X86::ATOMAND6432:
17197   case X86::ATOMOR6432:
17198   case X86::ATOMXOR6432:
17199   case X86::ATOMNAND6432:
17200   case X86::ATOMADD6432:
17201   case X86::ATOMSUB6432:
17202   case X86::ATOMMAX6432:
17203   case X86::ATOMMIN6432:
17204   case X86::ATOMUMAX6432:
17205   case X86::ATOMUMIN6432:
17206   case X86::ATOMSWAP6432:
17207     return EmitAtomicLoadArith6432(MI, BB);
17208
17209   case X86::VASTART_SAVE_XMM_REGS:
17210     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17211
17212   case X86::VAARG_64:
17213     return EmitVAARG64WithCustomInserter(MI, BB);
17214
17215   case X86::EH_SjLj_SetJmp32:
17216   case X86::EH_SjLj_SetJmp64:
17217     return emitEHSjLjSetJmp(MI, BB);
17218
17219   case X86::EH_SjLj_LongJmp32:
17220   case X86::EH_SjLj_LongJmp64:
17221     return emitEHSjLjLongJmp(MI, BB);
17222
17223   case TargetOpcode::STACKMAP:
17224   case TargetOpcode::PATCHPOINT:
17225     return emitPatchPoint(MI, BB);
17226
17227   case X86::VFMADDPDr213r:
17228   case X86::VFMADDPSr213r:
17229   case X86::VFMADDSDr213r:
17230   case X86::VFMADDSSr213r:
17231   case X86::VFMSUBPDr213r:
17232   case X86::VFMSUBPSr213r:
17233   case X86::VFMSUBSDr213r:
17234   case X86::VFMSUBSSr213r:
17235   case X86::VFNMADDPDr213r:
17236   case X86::VFNMADDPSr213r:
17237   case X86::VFNMADDSDr213r:
17238   case X86::VFNMADDSSr213r:
17239   case X86::VFNMSUBPDr213r:
17240   case X86::VFNMSUBPSr213r:
17241   case X86::VFNMSUBSDr213r:
17242   case X86::VFNMSUBSSr213r:
17243   case X86::VFMADDPDr213rY:
17244   case X86::VFMADDPSr213rY:
17245   case X86::VFMSUBPDr213rY:
17246   case X86::VFMSUBPSr213rY:
17247   case X86::VFNMADDPDr213rY:
17248   case X86::VFNMADDPSr213rY:
17249   case X86::VFNMSUBPDr213rY:
17250   case X86::VFNMSUBPSr213rY:
17251     return emitFMA3Instr(MI, BB);
17252   }
17253 }
17254
17255 //===----------------------------------------------------------------------===//
17256 //                           X86 Optimization Hooks
17257 //===----------------------------------------------------------------------===//
17258
17259 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17260                                                       APInt &KnownZero,
17261                                                       APInt &KnownOne,
17262                                                       const SelectionDAG &DAG,
17263                                                       unsigned Depth) const {
17264   unsigned BitWidth = KnownZero.getBitWidth();
17265   unsigned Opc = Op.getOpcode();
17266   assert((Opc >= ISD::BUILTIN_OP_END ||
17267           Opc == ISD::INTRINSIC_WO_CHAIN ||
17268           Opc == ISD::INTRINSIC_W_CHAIN ||
17269           Opc == ISD::INTRINSIC_VOID) &&
17270          "Should use MaskedValueIsZero if you don't know whether Op"
17271          " is a target node!");
17272
17273   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17274   switch (Opc) {
17275   default: break;
17276   case X86ISD::ADD:
17277   case X86ISD::SUB:
17278   case X86ISD::ADC:
17279   case X86ISD::SBB:
17280   case X86ISD::SMUL:
17281   case X86ISD::UMUL:
17282   case X86ISD::INC:
17283   case X86ISD::DEC:
17284   case X86ISD::OR:
17285   case X86ISD::XOR:
17286   case X86ISD::AND:
17287     // These nodes' second result is a boolean.
17288     if (Op.getResNo() == 0)
17289       break;
17290     // Fallthrough
17291   case X86ISD::SETCC:
17292     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17293     break;
17294   case ISD::INTRINSIC_WO_CHAIN: {
17295     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17296     unsigned NumLoBits = 0;
17297     switch (IntId) {
17298     default: break;
17299     case Intrinsic::x86_sse_movmsk_ps:
17300     case Intrinsic::x86_avx_movmsk_ps_256:
17301     case Intrinsic::x86_sse2_movmsk_pd:
17302     case Intrinsic::x86_avx_movmsk_pd_256:
17303     case Intrinsic::x86_mmx_pmovmskb:
17304     case Intrinsic::x86_sse2_pmovmskb_128:
17305     case Intrinsic::x86_avx2_pmovmskb: {
17306       // High bits of movmskp{s|d}, pmovmskb are known zero.
17307       switch (IntId) {
17308         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17309         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17310         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17311         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17312         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17313         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17314         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17315         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17316       }
17317       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17318       break;
17319     }
17320     }
17321     break;
17322   }
17323   }
17324 }
17325
17326 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17327   SDValue Op,
17328   const SelectionDAG &,
17329   unsigned Depth) const {
17330   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17331   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17332     return Op.getValueType().getScalarType().getSizeInBits();
17333
17334   // Fallback case.
17335   return 1;
17336 }
17337
17338 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17339 /// node is a GlobalAddress + offset.
17340 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17341                                        const GlobalValue* &GA,
17342                                        int64_t &Offset) const {
17343   if (N->getOpcode() == X86ISD::Wrapper) {
17344     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17345       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17346       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17347       return true;
17348     }
17349   }
17350   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17351 }
17352
17353 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17354 /// same as extracting the high 128-bit part of 256-bit vector and then
17355 /// inserting the result into the low part of a new 256-bit vector
17356 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17357   EVT VT = SVOp->getValueType(0);
17358   unsigned NumElems = VT.getVectorNumElements();
17359
17360   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17361   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17362     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17363         SVOp->getMaskElt(j) >= 0)
17364       return false;
17365
17366   return true;
17367 }
17368
17369 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17370 /// same as extracting the low 128-bit part of 256-bit vector and then
17371 /// inserting the result into the high part of a new 256-bit vector
17372 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17373   EVT VT = SVOp->getValueType(0);
17374   unsigned NumElems = VT.getVectorNumElements();
17375
17376   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17377   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17378     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17379         SVOp->getMaskElt(j) >= 0)
17380       return false;
17381
17382   return true;
17383 }
17384
17385 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17386 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17387                                         TargetLowering::DAGCombinerInfo &DCI,
17388                                         const X86Subtarget* Subtarget) {
17389   SDLoc dl(N);
17390   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17391   SDValue V1 = SVOp->getOperand(0);
17392   SDValue V2 = SVOp->getOperand(1);
17393   EVT VT = SVOp->getValueType(0);
17394   unsigned NumElems = VT.getVectorNumElements();
17395
17396   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17397       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17398     //
17399     //                   0,0,0,...
17400     //                      |
17401     //    V      UNDEF    BUILD_VECTOR    UNDEF
17402     //     \      /           \           /
17403     //  CONCAT_VECTOR         CONCAT_VECTOR
17404     //         \                  /
17405     //          \                /
17406     //          RESULT: V + zero extended
17407     //
17408     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17409         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17410         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17411       return SDValue();
17412
17413     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17414       return SDValue();
17415
17416     // To match the shuffle mask, the first half of the mask should
17417     // be exactly the first vector, and all the rest a splat with the
17418     // first element of the second one.
17419     for (unsigned i = 0; i != NumElems/2; ++i)
17420       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17421           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17422         return SDValue();
17423
17424     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17425     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17426       if (Ld->hasNUsesOfValue(1, 0)) {
17427         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17428         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17429         SDValue ResNode =
17430           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17431                                   Ld->getMemoryVT(),
17432                                   Ld->getPointerInfo(),
17433                                   Ld->getAlignment(),
17434                                   false/*isVolatile*/, true/*ReadMem*/,
17435                                   false/*WriteMem*/);
17436
17437         // Make sure the newly-created LOAD is in the same position as Ld in
17438         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17439         // and update uses of Ld's output chain to use the TokenFactor.
17440         if (Ld->hasAnyUseOfValue(1)) {
17441           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17442                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17443           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17444           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17445                                  SDValue(ResNode.getNode(), 1));
17446         }
17447
17448         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17449       }
17450     }
17451
17452     // Emit a zeroed vector and insert the desired subvector on its
17453     // first half.
17454     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17455     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17456     return DCI.CombineTo(N, InsV);
17457   }
17458
17459   //===--------------------------------------------------------------------===//
17460   // Combine some shuffles into subvector extracts and inserts:
17461   //
17462
17463   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17464   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17465     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17466     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17467     return DCI.CombineTo(N, InsV);
17468   }
17469
17470   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17471   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17472     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17473     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17474     return DCI.CombineTo(N, InsV);
17475   }
17476
17477   return SDValue();
17478 }
17479
17480 /// PerformShuffleCombine - Performs several different shuffle combines.
17481 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17482                                      TargetLowering::DAGCombinerInfo &DCI,
17483                                      const X86Subtarget *Subtarget) {
17484   SDLoc dl(N);
17485   EVT VT = N->getValueType(0);
17486
17487   // Don't create instructions with illegal types after legalize types has run.
17488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17489   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17490     return SDValue();
17491
17492   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17493   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17494       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17495     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17496
17497   // Only handle 128 wide vector from here on.
17498   if (!VT.is128BitVector())
17499     return SDValue();
17500
17501   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17502   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17503   // consecutive, non-overlapping, and in the right order.
17504   SmallVector<SDValue, 16> Elts;
17505   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17506     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17507
17508   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17509 }
17510
17511 /// PerformTruncateCombine - Converts truncate operation to
17512 /// a sequence of vector shuffle operations.
17513 /// It is possible when we truncate 256-bit vector to 128-bit vector
17514 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17515                                       TargetLowering::DAGCombinerInfo &DCI,
17516                                       const X86Subtarget *Subtarget)  {
17517   return SDValue();
17518 }
17519
17520 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17521 /// specific shuffle of a load can be folded into a single element load.
17522 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17523 /// shuffles have been customed lowered so we need to handle those here.
17524 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17525                                          TargetLowering::DAGCombinerInfo &DCI) {
17526   if (DCI.isBeforeLegalizeOps())
17527     return SDValue();
17528
17529   SDValue InVec = N->getOperand(0);
17530   SDValue EltNo = N->getOperand(1);
17531
17532   if (!isa<ConstantSDNode>(EltNo))
17533     return SDValue();
17534
17535   EVT VT = InVec.getValueType();
17536
17537   bool HasShuffleIntoBitcast = false;
17538   if (InVec.getOpcode() == ISD::BITCAST) {
17539     // Don't duplicate a load with other uses.
17540     if (!InVec.hasOneUse())
17541       return SDValue();
17542     EVT BCVT = InVec.getOperand(0).getValueType();
17543     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17544       return SDValue();
17545     InVec = InVec.getOperand(0);
17546     HasShuffleIntoBitcast = true;
17547   }
17548
17549   if (!isTargetShuffle(InVec.getOpcode()))
17550     return SDValue();
17551
17552   // Don't duplicate a load with other uses.
17553   if (!InVec.hasOneUse())
17554     return SDValue();
17555
17556   SmallVector<int, 16> ShuffleMask;
17557   bool UnaryShuffle;
17558   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17559                             UnaryShuffle))
17560     return SDValue();
17561
17562   // Select the input vector, guarding against out of range extract vector.
17563   unsigned NumElems = VT.getVectorNumElements();
17564   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17565   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17566   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17567                                          : InVec.getOperand(1);
17568
17569   // If inputs to shuffle are the same for both ops, then allow 2 uses
17570   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17571
17572   if (LdNode.getOpcode() == ISD::BITCAST) {
17573     // Don't duplicate a load with other uses.
17574     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17575       return SDValue();
17576
17577     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17578     LdNode = LdNode.getOperand(0);
17579   }
17580
17581   if (!ISD::isNormalLoad(LdNode.getNode()))
17582     return SDValue();
17583
17584   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17585
17586   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17587     return SDValue();
17588
17589   if (HasShuffleIntoBitcast) {
17590     // If there's a bitcast before the shuffle, check if the load type and
17591     // alignment is valid.
17592     unsigned Align = LN0->getAlignment();
17593     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17594     unsigned NewAlign = TLI.getDataLayout()->
17595       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17596
17597     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17598       return SDValue();
17599   }
17600
17601   // All checks match so transform back to vector_shuffle so that DAG combiner
17602   // can finish the job
17603   SDLoc dl(N);
17604
17605   // Create shuffle node taking into account the case that its a unary shuffle
17606   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17607   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17608                                  InVec.getOperand(0), Shuffle,
17609                                  &ShuffleMask[0]);
17610   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17611   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17612                      EltNo);
17613 }
17614
17615 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17616 /// generation and convert it from being a bunch of shuffles and extracts
17617 /// to a simple store and scalar loads to extract the elements.
17618 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17619                                          TargetLowering::DAGCombinerInfo &DCI) {
17620   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17621   if (NewOp.getNode())
17622     return NewOp;
17623
17624   SDValue InputVector = N->getOperand(0);
17625
17626   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17627   // from mmx to v2i32 has a single usage.
17628   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17629       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17630       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17631     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17632                        N->getValueType(0),
17633                        InputVector.getNode()->getOperand(0));
17634
17635   // Only operate on vectors of 4 elements, where the alternative shuffling
17636   // gets to be more expensive.
17637   if (InputVector.getValueType() != MVT::v4i32)
17638     return SDValue();
17639
17640   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17641   // single use which is a sign-extend or zero-extend, and all elements are
17642   // used.
17643   SmallVector<SDNode *, 4> Uses;
17644   unsigned ExtractedElements = 0;
17645   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17646        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17647     if (UI.getUse().getResNo() != InputVector.getResNo())
17648       return SDValue();
17649
17650     SDNode *Extract = *UI;
17651     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17652       return SDValue();
17653
17654     if (Extract->getValueType(0) != MVT::i32)
17655       return SDValue();
17656     if (!Extract->hasOneUse())
17657       return SDValue();
17658     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17659         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17660       return SDValue();
17661     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17662       return SDValue();
17663
17664     // Record which element was extracted.
17665     ExtractedElements |=
17666       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17667
17668     Uses.push_back(Extract);
17669   }
17670
17671   // If not all the elements were used, this may not be worthwhile.
17672   if (ExtractedElements != 15)
17673     return SDValue();
17674
17675   // Ok, we've now decided to do the transformation.
17676   SDLoc dl(InputVector);
17677
17678   // Store the value to a temporary stack slot.
17679   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17680   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17681                             MachinePointerInfo(), false, false, 0);
17682
17683   // Replace each use (extract) with a load of the appropriate element.
17684   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17685        UE = Uses.end(); UI != UE; ++UI) {
17686     SDNode *Extract = *UI;
17687
17688     // cOMpute the element's address.
17689     SDValue Idx = Extract->getOperand(1);
17690     unsigned EltSize =
17691         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17692     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17693     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17694     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17695
17696     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17697                                      StackPtr, OffsetVal);
17698
17699     // Load the scalar.
17700     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17701                                      ScalarAddr, MachinePointerInfo(),
17702                                      false, false, false, 0);
17703
17704     // Replace the exact with the load.
17705     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17706   }
17707
17708   // The replacement was made in place; don't return anything.
17709   return SDValue();
17710 }
17711
17712 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17713 static std::pair<unsigned, bool>
17714 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17715                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17716   if (!VT.isVector())
17717     return std::make_pair(0, false);
17718
17719   bool NeedSplit = false;
17720   switch (VT.getSimpleVT().SimpleTy) {
17721   default: return std::make_pair(0, false);
17722   case MVT::v32i8:
17723   case MVT::v16i16:
17724   case MVT::v8i32:
17725     if (!Subtarget->hasAVX2())
17726       NeedSplit = true;
17727     if (!Subtarget->hasAVX())
17728       return std::make_pair(0, false);
17729     break;
17730   case MVT::v16i8:
17731   case MVT::v8i16:
17732   case MVT::v4i32:
17733     if (!Subtarget->hasSSE2())
17734       return std::make_pair(0, false);
17735   }
17736
17737   // SSE2 has only a small subset of the operations.
17738   bool hasUnsigned = Subtarget->hasSSE41() ||
17739                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17740   bool hasSigned = Subtarget->hasSSE41() ||
17741                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17742
17743   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17744
17745   unsigned Opc = 0;
17746   // Check for x CC y ? x : y.
17747   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17748       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17749     switch (CC) {
17750     default: break;
17751     case ISD::SETULT:
17752     case ISD::SETULE:
17753       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17754     case ISD::SETUGT:
17755     case ISD::SETUGE:
17756       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17757     case ISD::SETLT:
17758     case ISD::SETLE:
17759       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17760     case ISD::SETGT:
17761     case ISD::SETGE:
17762       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17763     }
17764   // Check for x CC y ? y : x -- a min/max with reversed arms.
17765   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17766              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17767     switch (CC) {
17768     default: break;
17769     case ISD::SETULT:
17770     case ISD::SETULE:
17771       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17772     case ISD::SETUGT:
17773     case ISD::SETUGE:
17774       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17775     case ISD::SETLT:
17776     case ISD::SETLE:
17777       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17778     case ISD::SETGT:
17779     case ISD::SETGE:
17780       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17781     }
17782   }
17783
17784   return std::make_pair(Opc, NeedSplit);
17785 }
17786
17787 static SDValue
17788 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17789                                       const X86Subtarget *Subtarget) {
17790   SDLoc dl(N);
17791   SDValue Cond = N->getOperand(0);
17792   SDValue LHS = N->getOperand(1);
17793   SDValue RHS = N->getOperand(2);
17794
17795   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17796     SDValue CondSrc = Cond->getOperand(0);
17797     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17798       Cond = CondSrc->getOperand(0);
17799   }
17800
17801   MVT VT = N->getSimpleValueType(0);
17802   MVT EltVT = VT.getVectorElementType();
17803   unsigned NumElems = VT.getVectorNumElements();
17804   // There is no blend with immediate in AVX-512.
17805   if (VT.is512BitVector())
17806     return SDValue();
17807
17808   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17809     return SDValue();
17810   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17811     return SDValue();
17812
17813   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17814     return SDValue();
17815
17816   unsigned MaskValue = 0;
17817   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
17818     return SDValue();
17819
17820   SmallVector<int, 8> ShuffleMask(NumElems, -1);
17821   for (unsigned i = 0; i < NumElems; ++i) {
17822     // Be sure we emit undef where we can.
17823     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
17824       ShuffleMask[i] = -1;
17825     else
17826       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
17827   }
17828
17829   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
17830 }
17831
17832 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17833 /// nodes.
17834 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17835                                     TargetLowering::DAGCombinerInfo &DCI,
17836                                     const X86Subtarget *Subtarget) {
17837   SDLoc DL(N);
17838   SDValue Cond = N->getOperand(0);
17839   // Get the LHS/RHS of the select.
17840   SDValue LHS = N->getOperand(1);
17841   SDValue RHS = N->getOperand(2);
17842   EVT VT = LHS.getValueType();
17843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17844
17845   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17846   // instructions match the semantics of the common C idiom x<y?x:y but not
17847   // x<=y?x:y, because of how they handle negative zero (which can be
17848   // ignored in unsafe-math mode).
17849   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17850       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17851       (Subtarget->hasSSE2() ||
17852        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17853     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17854
17855     unsigned Opcode = 0;
17856     // Check for x CC y ? x : y.
17857     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17858         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17859       switch (CC) {
17860       default: break;
17861       case ISD::SETULT:
17862         // Converting this to a min would handle NaNs incorrectly, and swapping
17863         // the operands would cause it to handle comparisons between positive
17864         // and negative zero incorrectly.
17865         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17866           if (!DAG.getTarget().Options.UnsafeFPMath &&
17867               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17868             break;
17869           std::swap(LHS, RHS);
17870         }
17871         Opcode = X86ISD::FMIN;
17872         break;
17873       case ISD::SETOLE:
17874         // Converting this to a min would handle comparisons between positive
17875         // and negative zero incorrectly.
17876         if (!DAG.getTarget().Options.UnsafeFPMath &&
17877             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17878           break;
17879         Opcode = X86ISD::FMIN;
17880         break;
17881       case ISD::SETULE:
17882         // Converting this to a min would handle both negative zeros and NaNs
17883         // incorrectly, but we can swap the operands to fix both.
17884         std::swap(LHS, RHS);
17885       case ISD::SETOLT:
17886       case ISD::SETLT:
17887       case ISD::SETLE:
17888         Opcode = X86ISD::FMIN;
17889         break;
17890
17891       case ISD::SETOGE:
17892         // Converting this to a max would handle comparisons between positive
17893         // and negative zero incorrectly.
17894         if (!DAG.getTarget().Options.UnsafeFPMath &&
17895             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17896           break;
17897         Opcode = X86ISD::FMAX;
17898         break;
17899       case ISD::SETUGT:
17900         // Converting this to a max would handle NaNs incorrectly, and swapping
17901         // the operands would cause it to handle comparisons between positive
17902         // and negative zero incorrectly.
17903         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17904           if (!DAG.getTarget().Options.UnsafeFPMath &&
17905               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17906             break;
17907           std::swap(LHS, RHS);
17908         }
17909         Opcode = X86ISD::FMAX;
17910         break;
17911       case ISD::SETUGE:
17912         // Converting this to a max would handle both negative zeros and NaNs
17913         // incorrectly, but we can swap the operands to fix both.
17914         std::swap(LHS, RHS);
17915       case ISD::SETOGT:
17916       case ISD::SETGT:
17917       case ISD::SETGE:
17918         Opcode = X86ISD::FMAX;
17919         break;
17920       }
17921     // Check for x CC y ? y : x -- a min/max with reversed arms.
17922     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17923                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17924       switch (CC) {
17925       default: break;
17926       case ISD::SETOGE:
17927         // Converting this to a min would handle comparisons between positive
17928         // and negative zero incorrectly, and swapping the operands would
17929         // cause it to handle NaNs incorrectly.
17930         if (!DAG.getTarget().Options.UnsafeFPMath &&
17931             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17932           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17933             break;
17934           std::swap(LHS, RHS);
17935         }
17936         Opcode = X86ISD::FMIN;
17937         break;
17938       case ISD::SETUGT:
17939         // Converting this to a min would handle NaNs incorrectly.
17940         if (!DAG.getTarget().Options.UnsafeFPMath &&
17941             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17942           break;
17943         Opcode = X86ISD::FMIN;
17944         break;
17945       case ISD::SETUGE:
17946         // Converting this to a min would handle both negative zeros and NaNs
17947         // incorrectly, but we can swap the operands to fix both.
17948         std::swap(LHS, RHS);
17949       case ISD::SETOGT:
17950       case ISD::SETGT:
17951       case ISD::SETGE:
17952         Opcode = X86ISD::FMIN;
17953         break;
17954
17955       case ISD::SETULT:
17956         // Converting this to a max would handle NaNs incorrectly.
17957         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17958           break;
17959         Opcode = X86ISD::FMAX;
17960         break;
17961       case ISD::SETOLE:
17962         // Converting this to a max would handle comparisons between positive
17963         // and negative zero incorrectly, and swapping the operands would
17964         // cause it to handle NaNs incorrectly.
17965         if (!DAG.getTarget().Options.UnsafeFPMath &&
17966             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17967           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17968             break;
17969           std::swap(LHS, RHS);
17970         }
17971         Opcode = X86ISD::FMAX;
17972         break;
17973       case ISD::SETULE:
17974         // Converting this to a max would handle both negative zeros and NaNs
17975         // incorrectly, but we can swap the operands to fix both.
17976         std::swap(LHS, RHS);
17977       case ISD::SETOLT:
17978       case ISD::SETLT:
17979       case ISD::SETLE:
17980         Opcode = X86ISD::FMAX;
17981         break;
17982       }
17983     }
17984
17985     if (Opcode)
17986       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17987   }
17988
17989   EVT CondVT = Cond.getValueType();
17990   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17991       CondVT.getVectorElementType() == MVT::i1) {
17992     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17993     // lowering on AVX-512. In this case we convert it to
17994     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17995     // The same situation for all 128 and 256-bit vectors of i8 and i16
17996     EVT OpVT = LHS.getValueType();
17997     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17998         (OpVT.getVectorElementType() == MVT::i8 ||
17999          OpVT.getVectorElementType() == MVT::i16)) {
18000       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18001       DCI.AddToWorklist(Cond.getNode());
18002       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18003     }
18004   }
18005   // If this is a select between two integer constants, try to do some
18006   // optimizations.
18007   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18008     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18009       // Don't do this for crazy integer types.
18010       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18011         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18012         // so that TrueC (the true value) is larger than FalseC.
18013         bool NeedsCondInvert = false;
18014
18015         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18016             // Efficiently invertible.
18017             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
18018              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
18019               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18020           NeedsCondInvert = true;
18021           std::swap(TrueC, FalseC);
18022         }
18023
18024         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18025         if (FalseC->getAPIntValue() == 0 &&
18026             TrueC->getAPIntValue().isPowerOf2()) {
18027           if (NeedsCondInvert) // Invert the condition if needed.
18028             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18029                                DAG.getConstant(1, Cond.getValueType()));
18030
18031           // Zero extend the condition if needed.
18032           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18033
18034           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18035           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18036                              DAG.getConstant(ShAmt, MVT::i8));
18037         }
18038
18039         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18040         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18041           if (NeedsCondInvert) // Invert the condition if needed.
18042             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18043                                DAG.getConstant(1, Cond.getValueType()));
18044
18045           // Zero extend the condition if needed.
18046           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18047                              FalseC->getValueType(0), Cond);
18048           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18049                              SDValue(FalseC, 0));
18050         }
18051
18052         // Optimize cases that will turn into an LEA instruction.  This requires
18053         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18054         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18055           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18056           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18057
18058           bool isFastMultiplier = false;
18059           if (Diff < 10) {
18060             switch ((unsigned char)Diff) {
18061               default: break;
18062               case 1:  // result = add base, cond
18063               case 2:  // result = lea base(    , cond*2)
18064               case 3:  // result = lea base(cond, cond*2)
18065               case 4:  // result = lea base(    , cond*4)
18066               case 5:  // result = lea base(cond, cond*4)
18067               case 8:  // result = lea base(    , cond*8)
18068               case 9:  // result = lea base(cond, cond*8)
18069                 isFastMultiplier = true;
18070                 break;
18071             }
18072           }
18073
18074           if (isFastMultiplier) {
18075             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18076             if (NeedsCondInvert) // Invert the condition if needed.
18077               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18078                                  DAG.getConstant(1, Cond.getValueType()));
18079
18080             // Zero extend the condition if needed.
18081             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18082                                Cond);
18083             // Scale the condition by the difference.
18084             if (Diff != 1)
18085               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18086                                  DAG.getConstant(Diff, Cond.getValueType()));
18087
18088             // Add the base if non-zero.
18089             if (FalseC->getAPIntValue() != 0)
18090               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18091                                  SDValue(FalseC, 0));
18092             return Cond;
18093           }
18094         }
18095       }
18096   }
18097
18098   // Canonicalize max and min:
18099   // (x > y) ? x : y -> (x >= y) ? x : y
18100   // (x < y) ? x : y -> (x <= y) ? x : y
18101   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18102   // the need for an extra compare
18103   // against zero. e.g.
18104   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18105   // subl   %esi, %edi
18106   // testl  %edi, %edi
18107   // movl   $0, %eax
18108   // cmovgl %edi, %eax
18109   // =>
18110   // xorl   %eax, %eax
18111   // subl   %esi, $edi
18112   // cmovsl %eax, %edi
18113   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18114       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18115       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18116     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18117     switch (CC) {
18118     default: break;
18119     case ISD::SETLT:
18120     case ISD::SETGT: {
18121       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18122       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18123                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18124       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18125     }
18126     }
18127   }
18128
18129   // Early exit check
18130   if (!TLI.isTypeLegal(VT))
18131     return SDValue();
18132
18133   // Match VSELECTs into subs with unsigned saturation.
18134   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18135       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18136       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18137        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18138     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18139
18140     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18141     // left side invert the predicate to simplify logic below.
18142     SDValue Other;
18143     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18144       Other = RHS;
18145       CC = ISD::getSetCCInverse(CC, true);
18146     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18147       Other = LHS;
18148     }
18149
18150     if (Other.getNode() && Other->getNumOperands() == 2 &&
18151         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18152       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18153       SDValue CondRHS = Cond->getOperand(1);
18154
18155       // Look for a general sub with unsigned saturation first.
18156       // x >= y ? x-y : 0 --> subus x, y
18157       // x >  y ? x-y : 0 --> subus x, y
18158       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18159           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18160         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18161
18162       // If the RHS is a constant we have to reverse the const canonicalization.
18163       // x > C-1 ? x+-C : 0 --> subus x, C
18164       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18165           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18166         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18167         if (CondRHS.getConstantOperandVal(0) == -A-1)
18168           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18169                              DAG.getConstant(-A, VT));
18170       }
18171
18172       // Another special case: If C was a sign bit, the sub has been
18173       // canonicalized into a xor.
18174       // FIXME: Would it be better to use computeKnownBits to determine whether
18175       //        it's safe to decanonicalize the xor?
18176       // x s< 0 ? x^C : 0 --> subus x, C
18177       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18178           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18179           isSplatVector(OpRHS.getNode())) {
18180         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18181         if (A.isSignBit())
18182           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18183       }
18184     }
18185   }
18186
18187   // Try to match a min/max vector operation.
18188   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18189     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18190     unsigned Opc = ret.first;
18191     bool NeedSplit = ret.second;
18192
18193     if (Opc && NeedSplit) {
18194       unsigned NumElems = VT.getVectorNumElements();
18195       // Extract the LHS vectors
18196       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18197       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18198
18199       // Extract the RHS vectors
18200       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18201       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18202
18203       // Create min/max for each subvector
18204       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18205       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18206
18207       // Merge the result
18208       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18209     } else if (Opc)
18210       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18211   }
18212
18213   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18214   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18215       // Check if SETCC has already been promoted
18216       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18217       // Check that condition value type matches vselect operand type
18218       CondVT == VT) { 
18219
18220     assert(Cond.getValueType().isVector() &&
18221            "vector select expects a vector selector!");
18222
18223     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18224     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18225
18226     if (!TValIsAllOnes && !FValIsAllZeros) {
18227       // Try invert the condition if true value is not all 1s and false value
18228       // is not all 0s.
18229       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18230       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18231
18232       if (TValIsAllZeros || FValIsAllOnes) {
18233         SDValue CC = Cond.getOperand(2);
18234         ISD::CondCode NewCC =
18235           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18236                                Cond.getOperand(0).getValueType().isInteger());
18237         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18238         std::swap(LHS, RHS);
18239         TValIsAllOnes = FValIsAllOnes;
18240         FValIsAllZeros = TValIsAllZeros;
18241       }
18242     }
18243
18244     if (TValIsAllOnes || FValIsAllZeros) {
18245       SDValue Ret;
18246
18247       if (TValIsAllOnes && FValIsAllZeros)
18248         Ret = Cond;
18249       else if (TValIsAllOnes)
18250         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18251                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18252       else if (FValIsAllZeros)
18253         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18254                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18255
18256       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18257     }
18258   }
18259
18260   // Try to fold this VSELECT into a MOVSS/MOVSD
18261   if (N->getOpcode() == ISD::VSELECT &&
18262       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18263     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18264         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18265       bool CanFold = false;
18266       unsigned NumElems = Cond.getNumOperands();
18267       SDValue A = LHS;
18268       SDValue B = RHS;
18269       
18270       if (isZero(Cond.getOperand(0))) {
18271         CanFold = true;
18272
18273         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18274         // fold (vselect <0,-1> -> (movsd A, B)
18275         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18276           CanFold = isAllOnes(Cond.getOperand(i));
18277       } else if (isAllOnes(Cond.getOperand(0))) {
18278         CanFold = true;
18279         std::swap(A, B);
18280
18281         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18282         // fold (vselect <-1,0> -> (movsd B, A)
18283         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18284           CanFold = isZero(Cond.getOperand(i));
18285       }
18286
18287       if (CanFold) {
18288         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18289           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18290         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18291       }
18292
18293       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18294         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18295         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18296         //                             (v2i64 (bitcast B)))))
18297         //
18298         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18299         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18300         //                             (v2f64 (bitcast B)))))
18301         //
18302         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18303         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18304         //                             (v2i64 (bitcast A)))))
18305         //
18306         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18307         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18308         //                             (v2f64 (bitcast A)))))
18309
18310         CanFold = (isZero(Cond.getOperand(0)) &&
18311                    isZero(Cond.getOperand(1)) &&
18312                    isAllOnes(Cond.getOperand(2)) &&
18313                    isAllOnes(Cond.getOperand(3)));
18314
18315         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18316             isAllOnes(Cond.getOperand(1)) &&
18317             isZero(Cond.getOperand(2)) &&
18318             isZero(Cond.getOperand(3))) {
18319           CanFold = true;
18320           std::swap(LHS, RHS);
18321         }
18322
18323         if (CanFold) {
18324           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18325           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18326           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18327           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18328                                                 NewB, DAG);
18329           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18330         }
18331       }
18332     }
18333   }
18334
18335   // If we know that this node is legal then we know that it is going to be
18336   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18337   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18338   // to simplify previous instructions.
18339   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18340       !DCI.isBeforeLegalize() &&
18341       // We explicitly check against v8i16 and v16i16 because, although
18342       // they're marked as Custom, they might only be legal when Cond is a
18343       // build_vector of constants. This will be taken care in a later
18344       // condition.
18345       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18346        VT != MVT::v8i16)) {
18347     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18348
18349     // Don't optimize vector selects that map to mask-registers.
18350     if (BitWidth == 1)
18351       return SDValue();
18352
18353     // Check all uses of that condition operand to check whether it will be
18354     // consumed by non-BLEND instructions, which may depend on all bits are set
18355     // properly.
18356     for (SDNode::use_iterator I = Cond->use_begin(),
18357                               E = Cond->use_end(); I != E; ++I)
18358       if (I->getOpcode() != ISD::VSELECT)
18359         // TODO: Add other opcodes eventually lowered into BLEND.
18360         return SDValue();
18361
18362     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18363     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18364
18365     APInt KnownZero, KnownOne;
18366     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18367                                           DCI.isBeforeLegalizeOps());
18368     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18369         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18370       DCI.CommitTargetLoweringOpt(TLO);
18371   }
18372
18373   // We should generate an X86ISD::BLENDI from a vselect if its argument
18374   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18375   // constants. This specific pattern gets generated when we split a
18376   // selector for a 512 bit vector in a machine without AVX512 (but with
18377   // 256-bit vectors), during legalization:
18378   //
18379   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18380   //
18381   // Iff we find this pattern and the build_vectors are built from
18382   // constants, we translate the vselect into a shuffle_vector that we
18383   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18384   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18385     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18386     if (Shuffle.getNode())
18387       return Shuffle;
18388   }
18389
18390   return SDValue();
18391 }
18392
18393 // Check whether a boolean test is testing a boolean value generated by
18394 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18395 // code.
18396 //
18397 // Simplify the following patterns:
18398 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18399 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18400 // to (Op EFLAGS Cond)
18401 //
18402 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18403 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18404 // to (Op EFLAGS !Cond)
18405 //
18406 // where Op could be BRCOND or CMOV.
18407 //
18408 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18409   // Quit if not CMP and SUB with its value result used.
18410   if (Cmp.getOpcode() != X86ISD::CMP &&
18411       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18412       return SDValue();
18413
18414   // Quit if not used as a boolean value.
18415   if (CC != X86::COND_E && CC != X86::COND_NE)
18416     return SDValue();
18417
18418   // Check CMP operands. One of them should be 0 or 1 and the other should be
18419   // an SetCC or extended from it.
18420   SDValue Op1 = Cmp.getOperand(0);
18421   SDValue Op2 = Cmp.getOperand(1);
18422
18423   SDValue SetCC;
18424   const ConstantSDNode* C = nullptr;
18425   bool needOppositeCond = (CC == X86::COND_E);
18426   bool checkAgainstTrue = false; // Is it a comparison against 1?
18427
18428   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18429     SetCC = Op2;
18430   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18431     SetCC = Op1;
18432   else // Quit if all operands are not constants.
18433     return SDValue();
18434
18435   if (C->getZExtValue() == 1) {
18436     needOppositeCond = !needOppositeCond;
18437     checkAgainstTrue = true;
18438   } else if (C->getZExtValue() != 0)
18439     // Quit if the constant is neither 0 or 1.
18440     return SDValue();
18441
18442   bool truncatedToBoolWithAnd = false;
18443   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18444   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18445          SetCC.getOpcode() == ISD::TRUNCATE ||
18446          SetCC.getOpcode() == ISD::AND) {
18447     if (SetCC.getOpcode() == ISD::AND) {
18448       int OpIdx = -1;
18449       ConstantSDNode *CS;
18450       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18451           CS->getZExtValue() == 1)
18452         OpIdx = 1;
18453       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18454           CS->getZExtValue() == 1)
18455         OpIdx = 0;
18456       if (OpIdx == -1)
18457         break;
18458       SetCC = SetCC.getOperand(OpIdx);
18459       truncatedToBoolWithAnd = true;
18460     } else
18461       SetCC = SetCC.getOperand(0);
18462   }
18463
18464   switch (SetCC.getOpcode()) {
18465   case X86ISD::SETCC_CARRY:
18466     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18467     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18468     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18469     // truncated to i1 using 'and'.
18470     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18471       break;
18472     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18473            "Invalid use of SETCC_CARRY!");
18474     // FALL THROUGH
18475   case X86ISD::SETCC:
18476     // Set the condition code or opposite one if necessary.
18477     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18478     if (needOppositeCond)
18479       CC = X86::GetOppositeBranchCondition(CC);
18480     return SetCC.getOperand(1);
18481   case X86ISD::CMOV: {
18482     // Check whether false/true value has canonical one, i.e. 0 or 1.
18483     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18484     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18485     // Quit if true value is not a constant.
18486     if (!TVal)
18487       return SDValue();
18488     // Quit if false value is not a constant.
18489     if (!FVal) {
18490       SDValue Op = SetCC.getOperand(0);
18491       // Skip 'zext' or 'trunc' node.
18492       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18493           Op.getOpcode() == ISD::TRUNCATE)
18494         Op = Op.getOperand(0);
18495       // A special case for rdrand/rdseed, where 0 is set if false cond is
18496       // found.
18497       if ((Op.getOpcode() != X86ISD::RDRAND &&
18498            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18499         return SDValue();
18500     }
18501     // Quit if false value is not the constant 0 or 1.
18502     bool FValIsFalse = true;
18503     if (FVal && FVal->getZExtValue() != 0) {
18504       if (FVal->getZExtValue() != 1)
18505         return SDValue();
18506       // If FVal is 1, opposite cond is needed.
18507       needOppositeCond = !needOppositeCond;
18508       FValIsFalse = false;
18509     }
18510     // Quit if TVal is not the constant opposite of FVal.
18511     if (FValIsFalse && TVal->getZExtValue() != 1)
18512       return SDValue();
18513     if (!FValIsFalse && TVal->getZExtValue() != 0)
18514       return SDValue();
18515     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18516     if (needOppositeCond)
18517       CC = X86::GetOppositeBranchCondition(CC);
18518     return SetCC.getOperand(3);
18519   }
18520   }
18521
18522   return SDValue();
18523 }
18524
18525 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18526 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18527                                   TargetLowering::DAGCombinerInfo &DCI,
18528                                   const X86Subtarget *Subtarget) {
18529   SDLoc DL(N);
18530
18531   // If the flag operand isn't dead, don't touch this CMOV.
18532   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18533     return SDValue();
18534
18535   SDValue FalseOp = N->getOperand(0);
18536   SDValue TrueOp = N->getOperand(1);
18537   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18538   SDValue Cond = N->getOperand(3);
18539
18540   if (CC == X86::COND_E || CC == X86::COND_NE) {
18541     switch (Cond.getOpcode()) {
18542     default: break;
18543     case X86ISD::BSR:
18544     case X86ISD::BSF:
18545       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18546       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18547         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18548     }
18549   }
18550
18551   SDValue Flags;
18552
18553   Flags = checkBoolTestSetCCCombine(Cond, CC);
18554   if (Flags.getNode() &&
18555       // Extra check as FCMOV only supports a subset of X86 cond.
18556       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18557     SDValue Ops[] = { FalseOp, TrueOp,
18558                       DAG.getConstant(CC, MVT::i8), Flags };
18559     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18560   }
18561
18562   // If this is a select between two integer constants, try to do some
18563   // optimizations.  Note that the operands are ordered the opposite of SELECT
18564   // operands.
18565   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18566     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18567       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18568       // larger than FalseC (the false value).
18569       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18570         CC = X86::GetOppositeBranchCondition(CC);
18571         std::swap(TrueC, FalseC);
18572         std::swap(TrueOp, FalseOp);
18573       }
18574
18575       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18576       // This is efficient for any integer data type (including i8/i16) and
18577       // shift amount.
18578       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18579         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18580                            DAG.getConstant(CC, MVT::i8), Cond);
18581
18582         // Zero extend the condition if needed.
18583         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18584
18585         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18586         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18587                            DAG.getConstant(ShAmt, MVT::i8));
18588         if (N->getNumValues() == 2)  // Dead flag value?
18589           return DCI.CombineTo(N, Cond, SDValue());
18590         return Cond;
18591       }
18592
18593       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18594       // for any integer data type, including i8/i16.
18595       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18596         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18597                            DAG.getConstant(CC, MVT::i8), Cond);
18598
18599         // Zero extend the condition if needed.
18600         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18601                            FalseC->getValueType(0), Cond);
18602         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18603                            SDValue(FalseC, 0));
18604
18605         if (N->getNumValues() == 2)  // Dead flag value?
18606           return DCI.CombineTo(N, Cond, SDValue());
18607         return Cond;
18608       }
18609
18610       // Optimize cases that will turn into an LEA instruction.  This requires
18611       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18612       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18613         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18614         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18615
18616         bool isFastMultiplier = false;
18617         if (Diff < 10) {
18618           switch ((unsigned char)Diff) {
18619           default: break;
18620           case 1:  // result = add base, cond
18621           case 2:  // result = lea base(    , cond*2)
18622           case 3:  // result = lea base(cond, cond*2)
18623           case 4:  // result = lea base(    , cond*4)
18624           case 5:  // result = lea base(cond, cond*4)
18625           case 8:  // result = lea base(    , cond*8)
18626           case 9:  // result = lea base(cond, cond*8)
18627             isFastMultiplier = true;
18628             break;
18629           }
18630         }
18631
18632         if (isFastMultiplier) {
18633           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18634           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18635                              DAG.getConstant(CC, MVT::i8), Cond);
18636           // Zero extend the condition if needed.
18637           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18638                              Cond);
18639           // Scale the condition by the difference.
18640           if (Diff != 1)
18641             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18642                                DAG.getConstant(Diff, Cond.getValueType()));
18643
18644           // Add the base if non-zero.
18645           if (FalseC->getAPIntValue() != 0)
18646             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18647                                SDValue(FalseC, 0));
18648           if (N->getNumValues() == 2)  // Dead flag value?
18649             return DCI.CombineTo(N, Cond, SDValue());
18650           return Cond;
18651         }
18652       }
18653     }
18654   }
18655
18656   // Handle these cases:
18657   //   (select (x != c), e, c) -> select (x != c), e, x),
18658   //   (select (x == c), c, e) -> select (x == c), x, e)
18659   // where the c is an integer constant, and the "select" is the combination
18660   // of CMOV and CMP.
18661   //
18662   // The rationale for this change is that the conditional-move from a constant
18663   // needs two instructions, however, conditional-move from a register needs
18664   // only one instruction.
18665   //
18666   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18667   //  some instruction-combining opportunities. This opt needs to be
18668   //  postponed as late as possible.
18669   //
18670   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18671     // the DCI.xxxx conditions are provided to postpone the optimization as
18672     // late as possible.
18673
18674     ConstantSDNode *CmpAgainst = nullptr;
18675     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18676         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18677         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18678
18679       if (CC == X86::COND_NE &&
18680           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18681         CC = X86::GetOppositeBranchCondition(CC);
18682         std::swap(TrueOp, FalseOp);
18683       }
18684
18685       if (CC == X86::COND_E &&
18686           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18687         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18688                           DAG.getConstant(CC, MVT::i8), Cond };
18689         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18690       }
18691     }
18692   }
18693
18694   return SDValue();
18695 }
18696
18697 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18698                                                 const X86Subtarget *Subtarget) {
18699   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18700   switch (IntNo) {
18701   default: return SDValue();
18702   // SSE/AVX/AVX2 blend intrinsics.
18703   case Intrinsic::x86_avx2_pblendvb:
18704   case Intrinsic::x86_avx2_pblendw:
18705   case Intrinsic::x86_avx2_pblendd_128:
18706   case Intrinsic::x86_avx2_pblendd_256:
18707     // Don't try to simplify this intrinsic if we don't have AVX2.
18708     if (!Subtarget->hasAVX2())
18709       return SDValue();
18710     // FALL-THROUGH
18711   case Intrinsic::x86_avx_blend_pd_256:
18712   case Intrinsic::x86_avx_blend_ps_256:
18713   case Intrinsic::x86_avx_blendv_pd_256:
18714   case Intrinsic::x86_avx_blendv_ps_256:
18715     // Don't try to simplify this intrinsic if we don't have AVX.
18716     if (!Subtarget->hasAVX())
18717       return SDValue();
18718     // FALL-THROUGH
18719   case Intrinsic::x86_sse41_pblendw:
18720   case Intrinsic::x86_sse41_blendpd:
18721   case Intrinsic::x86_sse41_blendps:
18722   case Intrinsic::x86_sse41_blendvps:
18723   case Intrinsic::x86_sse41_blendvpd:
18724   case Intrinsic::x86_sse41_pblendvb: {
18725     SDValue Op0 = N->getOperand(1);
18726     SDValue Op1 = N->getOperand(2);
18727     SDValue Mask = N->getOperand(3);
18728
18729     // Don't try to simplify this intrinsic if we don't have SSE4.1.
18730     if (!Subtarget->hasSSE41())
18731       return SDValue();
18732
18733     // fold (blend A, A, Mask) -> A
18734     if (Op0 == Op1)
18735       return Op0;
18736     // fold (blend A, B, allZeros) -> A
18737     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18738       return Op0;
18739     // fold (blend A, B, allOnes) -> B
18740     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18741       return Op1;
18742     
18743     // Simplify the case where the mask is a constant i32 value.
18744     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18745       if (C->isNullValue())
18746         return Op0;
18747       if (C->isAllOnesValue())
18748         return Op1;
18749     }
18750   }
18751
18752   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18753   case Intrinsic::x86_sse2_psrai_w:
18754   case Intrinsic::x86_sse2_psrai_d:
18755   case Intrinsic::x86_avx2_psrai_w:
18756   case Intrinsic::x86_avx2_psrai_d:
18757   case Intrinsic::x86_sse2_psra_w:
18758   case Intrinsic::x86_sse2_psra_d:
18759   case Intrinsic::x86_avx2_psra_w:
18760   case Intrinsic::x86_avx2_psra_d: {
18761     SDValue Op0 = N->getOperand(1);
18762     SDValue Op1 = N->getOperand(2);
18763     EVT VT = Op0.getValueType();
18764     assert(VT.isVector() && "Expected a vector type!");
18765
18766     if (isa<BuildVectorSDNode>(Op1))
18767       Op1 = Op1.getOperand(0);
18768
18769     if (!isa<ConstantSDNode>(Op1))
18770       return SDValue();
18771
18772     EVT SVT = VT.getVectorElementType();
18773     unsigned SVTBits = SVT.getSizeInBits();
18774
18775     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18776     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18777     uint64_t ShAmt = C.getZExtValue();
18778
18779     // Don't try to convert this shift into a ISD::SRA if the shift
18780     // count is bigger than or equal to the element size.
18781     if (ShAmt >= SVTBits)
18782       return SDValue();
18783
18784     // Trivial case: if the shift count is zero, then fold this
18785     // into the first operand.
18786     if (ShAmt == 0)
18787       return Op0;
18788
18789     // Replace this packed shift intrinsic with a target independent
18790     // shift dag node.
18791     SDValue Splat = DAG.getConstant(C, VT);
18792     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18793   }
18794   }
18795 }
18796
18797 /// PerformMulCombine - Optimize a single multiply with constant into two
18798 /// in order to implement it with two cheaper instructions, e.g.
18799 /// LEA + SHL, LEA + LEA.
18800 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18801                                  TargetLowering::DAGCombinerInfo &DCI) {
18802   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18803     return SDValue();
18804
18805   EVT VT = N->getValueType(0);
18806   if (VT != MVT::i64)
18807     return SDValue();
18808
18809   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18810   if (!C)
18811     return SDValue();
18812   uint64_t MulAmt = C->getZExtValue();
18813   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18814     return SDValue();
18815
18816   uint64_t MulAmt1 = 0;
18817   uint64_t MulAmt2 = 0;
18818   if ((MulAmt % 9) == 0) {
18819     MulAmt1 = 9;
18820     MulAmt2 = MulAmt / 9;
18821   } else if ((MulAmt % 5) == 0) {
18822     MulAmt1 = 5;
18823     MulAmt2 = MulAmt / 5;
18824   } else if ((MulAmt % 3) == 0) {
18825     MulAmt1 = 3;
18826     MulAmt2 = MulAmt / 3;
18827   }
18828   if (MulAmt2 &&
18829       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18830     SDLoc DL(N);
18831
18832     if (isPowerOf2_64(MulAmt2) &&
18833         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18834       // If second multiplifer is pow2, issue it first. We want the multiply by
18835       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18836       // is an add.
18837       std::swap(MulAmt1, MulAmt2);
18838
18839     SDValue NewMul;
18840     if (isPowerOf2_64(MulAmt1))
18841       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18842                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18843     else
18844       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18845                            DAG.getConstant(MulAmt1, VT));
18846
18847     if (isPowerOf2_64(MulAmt2))
18848       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18849                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18850     else
18851       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18852                            DAG.getConstant(MulAmt2, VT));
18853
18854     // Do not add new nodes to DAG combiner worklist.
18855     DCI.CombineTo(N, NewMul, false);
18856   }
18857   return SDValue();
18858 }
18859
18860 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18861   SDValue N0 = N->getOperand(0);
18862   SDValue N1 = N->getOperand(1);
18863   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18864   EVT VT = N0.getValueType();
18865
18866   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18867   // since the result of setcc_c is all zero's or all ones.
18868   if (VT.isInteger() && !VT.isVector() &&
18869       N1C && N0.getOpcode() == ISD::AND &&
18870       N0.getOperand(1).getOpcode() == ISD::Constant) {
18871     SDValue N00 = N0.getOperand(0);
18872     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18873         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18874           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18875          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18876       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18877       APInt ShAmt = N1C->getAPIntValue();
18878       Mask = Mask.shl(ShAmt);
18879       if (Mask != 0)
18880         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18881                            N00, DAG.getConstant(Mask, VT));
18882     }
18883   }
18884
18885   // Hardware support for vector shifts is sparse which makes us scalarize the
18886   // vector operations in many cases. Also, on sandybridge ADD is faster than
18887   // shl.
18888   // (shl V, 1) -> add V,V
18889   if (isSplatVector(N1.getNode())) {
18890     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18891     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18892     // We shift all of the values by one. In many cases we do not have
18893     // hardware support for this operation. This is better expressed as an ADD
18894     // of two values.
18895     if (N1C && (1 == N1C->getZExtValue())) {
18896       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18897     }
18898   }
18899
18900   return SDValue();
18901 }
18902
18903 /// \brief Returns a vector of 0s if the node in input is a vector logical
18904 /// shift by a constant amount which is known to be bigger than or equal
18905 /// to the vector element size in bits.
18906 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18907                                       const X86Subtarget *Subtarget) {
18908   EVT VT = N->getValueType(0);
18909
18910   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18911       (!Subtarget->hasInt256() ||
18912        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18913     return SDValue();
18914
18915   SDValue Amt = N->getOperand(1);
18916   SDLoc DL(N);
18917   if (isSplatVector(Amt.getNode())) {
18918     SDValue SclrAmt = Amt->getOperand(0);
18919     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18920       APInt ShiftAmt = C->getAPIntValue();
18921       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18922
18923       // SSE2/AVX2 logical shifts always return a vector of 0s
18924       // if the shift amount is bigger than or equal to
18925       // the element size. The constant shift amount will be
18926       // encoded as a 8-bit immediate.
18927       if (ShiftAmt.trunc(8).uge(MaxAmount))
18928         return getZeroVector(VT, Subtarget, DAG, DL);
18929     }
18930   }
18931
18932   return SDValue();
18933 }
18934
18935 /// PerformShiftCombine - Combine shifts.
18936 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18937                                    TargetLowering::DAGCombinerInfo &DCI,
18938                                    const X86Subtarget *Subtarget) {
18939   if (N->getOpcode() == ISD::SHL) {
18940     SDValue V = PerformSHLCombine(N, DAG);
18941     if (V.getNode()) return V;
18942   }
18943
18944   if (N->getOpcode() != ISD::SRA) {
18945     // Try to fold this logical shift into a zero vector.
18946     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18947     if (V.getNode()) return V;
18948   }
18949
18950   return SDValue();
18951 }
18952
18953 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18954 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18955 // and friends.  Likewise for OR -> CMPNEQSS.
18956 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18957                             TargetLowering::DAGCombinerInfo &DCI,
18958                             const X86Subtarget *Subtarget) {
18959   unsigned opcode;
18960
18961   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18962   // we're requiring SSE2 for both.
18963   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18964     SDValue N0 = N->getOperand(0);
18965     SDValue N1 = N->getOperand(1);
18966     SDValue CMP0 = N0->getOperand(1);
18967     SDValue CMP1 = N1->getOperand(1);
18968     SDLoc DL(N);
18969
18970     // The SETCCs should both refer to the same CMP.
18971     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18972       return SDValue();
18973
18974     SDValue CMP00 = CMP0->getOperand(0);
18975     SDValue CMP01 = CMP0->getOperand(1);
18976     EVT     VT    = CMP00.getValueType();
18977
18978     if (VT == MVT::f32 || VT == MVT::f64) {
18979       bool ExpectingFlags = false;
18980       // Check for any users that want flags:
18981       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18982            !ExpectingFlags && UI != UE; ++UI)
18983         switch (UI->getOpcode()) {
18984         default:
18985         case ISD::BR_CC:
18986         case ISD::BRCOND:
18987         case ISD::SELECT:
18988           ExpectingFlags = true;
18989           break;
18990         case ISD::CopyToReg:
18991         case ISD::SIGN_EXTEND:
18992         case ISD::ZERO_EXTEND:
18993         case ISD::ANY_EXTEND:
18994           break;
18995         }
18996
18997       if (!ExpectingFlags) {
18998         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18999         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19000
19001         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19002           X86::CondCode tmp = cc0;
19003           cc0 = cc1;
19004           cc1 = tmp;
19005         }
19006
19007         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
19008             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19009           // FIXME: need symbolic constants for these magic numbers.
19010           // See X86ATTInstPrinter.cpp:printSSECC().
19011           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19012           if (Subtarget->hasAVX512()) {
19013             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19014                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
19015             if (N->getValueType(0) != MVT::i1)
19016               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19017                                  FSetCC);
19018             return FSetCC;
19019           }
19020           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19021                                               CMP00.getValueType(), CMP00, CMP01,
19022                                               DAG.getConstant(x86cc, MVT::i8));
19023
19024           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19025           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19026
19027           if (is64BitFP && !Subtarget->is64Bit()) {
19028             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19029             // 64-bit integer, since that's not a legal type. Since
19030             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19031             // bits, but can do this little dance to extract the lowest 32 bits
19032             // and work with those going forward.
19033             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19034                                            OnesOrZeroesF);
19035             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19036                                            Vector64);
19037             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19038                                         Vector32, DAG.getIntPtrConstant(0));
19039             IntVT = MVT::i32;
19040           }
19041
19042           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19043           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19044                                       DAG.getConstant(1, IntVT));
19045           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19046           return OneBitOfTruth;
19047         }
19048       }
19049     }
19050   }
19051   return SDValue();
19052 }
19053
19054 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19055 /// so it can be folded inside ANDNP.
19056 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19057   EVT VT = N->getValueType(0);
19058
19059   // Match direct AllOnes for 128 and 256-bit vectors
19060   if (ISD::isBuildVectorAllOnes(N))
19061     return true;
19062
19063   // Look through a bit convert.
19064   if (N->getOpcode() == ISD::BITCAST)
19065     N = N->getOperand(0).getNode();
19066
19067   // Sometimes the operand may come from a insert_subvector building a 256-bit
19068   // allones vector
19069   if (VT.is256BitVector() &&
19070       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19071     SDValue V1 = N->getOperand(0);
19072     SDValue V2 = N->getOperand(1);
19073
19074     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19075         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19076         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19077         ISD::isBuildVectorAllOnes(V2.getNode()))
19078       return true;
19079   }
19080
19081   return false;
19082 }
19083
19084 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19085 // register. In most cases we actually compare or select YMM-sized registers
19086 // and mixing the two types creates horrible code. This method optimizes
19087 // some of the transition sequences.
19088 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19089                                  TargetLowering::DAGCombinerInfo &DCI,
19090                                  const X86Subtarget *Subtarget) {
19091   EVT VT = N->getValueType(0);
19092   if (!VT.is256BitVector())
19093     return SDValue();
19094
19095   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19096           N->getOpcode() == ISD::ZERO_EXTEND ||
19097           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19098
19099   SDValue Narrow = N->getOperand(0);
19100   EVT NarrowVT = Narrow->getValueType(0);
19101   if (!NarrowVT.is128BitVector())
19102     return SDValue();
19103
19104   if (Narrow->getOpcode() != ISD::XOR &&
19105       Narrow->getOpcode() != ISD::AND &&
19106       Narrow->getOpcode() != ISD::OR)
19107     return SDValue();
19108
19109   SDValue N0  = Narrow->getOperand(0);
19110   SDValue N1  = Narrow->getOperand(1);
19111   SDLoc DL(Narrow);
19112
19113   // The Left side has to be a trunc.
19114   if (N0.getOpcode() != ISD::TRUNCATE)
19115     return SDValue();
19116
19117   // The type of the truncated inputs.
19118   EVT WideVT = N0->getOperand(0)->getValueType(0);
19119   if (WideVT != VT)
19120     return SDValue();
19121
19122   // The right side has to be a 'trunc' or a constant vector.
19123   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19124   bool RHSConst = (isSplatVector(N1.getNode()) &&
19125                    isa<ConstantSDNode>(N1->getOperand(0)));
19126   if (!RHSTrunc && !RHSConst)
19127     return SDValue();
19128
19129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19130
19131   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19132     return SDValue();
19133
19134   // Set N0 and N1 to hold the inputs to the new wide operation.
19135   N0 = N0->getOperand(0);
19136   if (RHSConst) {
19137     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19138                      N1->getOperand(0));
19139     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19140     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19141   } else if (RHSTrunc) {
19142     N1 = N1->getOperand(0);
19143   }
19144
19145   // Generate the wide operation.
19146   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19147   unsigned Opcode = N->getOpcode();
19148   switch (Opcode) {
19149   case ISD::ANY_EXTEND:
19150     return Op;
19151   case ISD::ZERO_EXTEND: {
19152     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19153     APInt Mask = APInt::getAllOnesValue(InBits);
19154     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19155     return DAG.getNode(ISD::AND, DL, VT,
19156                        Op, DAG.getConstant(Mask, VT));
19157   }
19158   case ISD::SIGN_EXTEND:
19159     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19160                        Op, DAG.getValueType(NarrowVT));
19161   default:
19162     llvm_unreachable("Unexpected opcode");
19163   }
19164 }
19165
19166 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19167                                  TargetLowering::DAGCombinerInfo &DCI,
19168                                  const X86Subtarget *Subtarget) {
19169   EVT VT = N->getValueType(0);
19170   if (DCI.isBeforeLegalizeOps())
19171     return SDValue();
19172
19173   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19174   if (R.getNode())
19175     return R;
19176
19177   // Create BEXTR instructions
19178   // BEXTR is ((X >> imm) & (2**size-1))
19179   if (VT == MVT::i32 || VT == MVT::i64) {
19180     SDValue N0 = N->getOperand(0);
19181     SDValue N1 = N->getOperand(1);
19182     SDLoc DL(N);
19183
19184     // Check for BEXTR.
19185     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19186         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19187       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19188       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19189       if (MaskNode && ShiftNode) {
19190         uint64_t Mask = MaskNode->getZExtValue();
19191         uint64_t Shift = ShiftNode->getZExtValue();
19192         if (isMask_64(Mask)) {
19193           uint64_t MaskSize = CountPopulation_64(Mask);
19194           if (Shift + MaskSize <= VT.getSizeInBits())
19195             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19196                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19197         }
19198       }
19199     } // BEXTR
19200
19201     return SDValue();
19202   }
19203
19204   // Want to form ANDNP nodes:
19205   // 1) In the hopes of then easily combining them with OR and AND nodes
19206   //    to form PBLEND/PSIGN.
19207   // 2) To match ANDN packed intrinsics
19208   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19209     return SDValue();
19210
19211   SDValue N0 = N->getOperand(0);
19212   SDValue N1 = N->getOperand(1);
19213   SDLoc DL(N);
19214
19215   // Check LHS for vnot
19216   if (N0.getOpcode() == ISD::XOR &&
19217       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19218       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19219     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19220
19221   // Check RHS for vnot
19222   if (N1.getOpcode() == ISD::XOR &&
19223       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19224       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19225     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19226
19227   return SDValue();
19228 }
19229
19230 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19231                                 TargetLowering::DAGCombinerInfo &DCI,
19232                                 const X86Subtarget *Subtarget) {
19233   if (DCI.isBeforeLegalizeOps())
19234     return SDValue();
19235
19236   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19237   if (R.getNode())
19238     return R;
19239
19240   SDValue N0 = N->getOperand(0);
19241   SDValue N1 = N->getOperand(1);
19242   EVT VT = N->getValueType(0);
19243
19244   // look for psign/blend
19245   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19246     if (!Subtarget->hasSSSE3() ||
19247         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19248       return SDValue();
19249
19250     // Canonicalize pandn to RHS
19251     if (N0.getOpcode() == X86ISD::ANDNP)
19252       std::swap(N0, N1);
19253     // or (and (m, y), (pandn m, x))
19254     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19255       SDValue Mask = N1.getOperand(0);
19256       SDValue X    = N1.getOperand(1);
19257       SDValue Y;
19258       if (N0.getOperand(0) == Mask)
19259         Y = N0.getOperand(1);
19260       if (N0.getOperand(1) == Mask)
19261         Y = N0.getOperand(0);
19262
19263       // Check to see if the mask appeared in both the AND and ANDNP and
19264       if (!Y.getNode())
19265         return SDValue();
19266
19267       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19268       // Look through mask bitcast.
19269       if (Mask.getOpcode() == ISD::BITCAST)
19270         Mask = Mask.getOperand(0);
19271       if (X.getOpcode() == ISD::BITCAST)
19272         X = X.getOperand(0);
19273       if (Y.getOpcode() == ISD::BITCAST)
19274         Y = Y.getOperand(0);
19275
19276       EVT MaskVT = Mask.getValueType();
19277
19278       // Validate that the Mask operand is a vector sra node.
19279       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19280       // there is no psrai.b
19281       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19282       unsigned SraAmt = ~0;
19283       if (Mask.getOpcode() == ISD::SRA) {
19284         SDValue Amt = Mask.getOperand(1);
19285         if (isSplatVector(Amt.getNode())) {
19286           SDValue SclrAmt = Amt->getOperand(0);
19287           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19288             SraAmt = C->getZExtValue();
19289         }
19290       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19291         SDValue SraC = Mask.getOperand(1);
19292         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19293       }
19294       if ((SraAmt + 1) != EltBits)
19295         return SDValue();
19296
19297       SDLoc DL(N);
19298
19299       // Now we know we at least have a plendvb with the mask val.  See if
19300       // we can form a psignb/w/d.
19301       // psign = x.type == y.type == mask.type && y = sub(0, x);
19302       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19303           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19304           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19305         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19306                "Unsupported VT for PSIGN");
19307         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19308         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19309       }
19310       // PBLENDVB only available on SSE 4.1
19311       if (!Subtarget->hasSSE41())
19312         return SDValue();
19313
19314       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19315
19316       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19317       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19318       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19319       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19320       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19321     }
19322   }
19323
19324   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19325     return SDValue();
19326
19327   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19328   MachineFunction &MF = DAG.getMachineFunction();
19329   bool OptForSize = MF.getFunction()->getAttributes().
19330     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19331
19332   // SHLD/SHRD instructions have lower register pressure, but on some
19333   // platforms they have higher latency than the equivalent
19334   // series of shifts/or that would otherwise be generated.
19335   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19336   // have higher latencies and we are not optimizing for size.
19337   if (!OptForSize && Subtarget->isSHLDSlow())
19338     return SDValue();
19339
19340   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19341     std::swap(N0, N1);
19342   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19343     return SDValue();
19344   if (!N0.hasOneUse() || !N1.hasOneUse())
19345     return SDValue();
19346
19347   SDValue ShAmt0 = N0.getOperand(1);
19348   if (ShAmt0.getValueType() != MVT::i8)
19349     return SDValue();
19350   SDValue ShAmt1 = N1.getOperand(1);
19351   if (ShAmt1.getValueType() != MVT::i8)
19352     return SDValue();
19353   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19354     ShAmt0 = ShAmt0.getOperand(0);
19355   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19356     ShAmt1 = ShAmt1.getOperand(0);
19357
19358   SDLoc DL(N);
19359   unsigned Opc = X86ISD::SHLD;
19360   SDValue Op0 = N0.getOperand(0);
19361   SDValue Op1 = N1.getOperand(0);
19362   if (ShAmt0.getOpcode() == ISD::SUB) {
19363     Opc = X86ISD::SHRD;
19364     std::swap(Op0, Op1);
19365     std::swap(ShAmt0, ShAmt1);
19366   }
19367
19368   unsigned Bits = VT.getSizeInBits();
19369   if (ShAmt1.getOpcode() == ISD::SUB) {
19370     SDValue Sum = ShAmt1.getOperand(0);
19371     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19372       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19373       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19374         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19375       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19376         return DAG.getNode(Opc, DL, VT,
19377                            Op0, Op1,
19378                            DAG.getNode(ISD::TRUNCATE, DL,
19379                                        MVT::i8, ShAmt0));
19380     }
19381   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19382     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19383     if (ShAmt0C &&
19384         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19385       return DAG.getNode(Opc, DL, VT,
19386                          N0.getOperand(0), N1.getOperand(0),
19387                          DAG.getNode(ISD::TRUNCATE, DL,
19388                                        MVT::i8, ShAmt0));
19389   }
19390
19391   return SDValue();
19392 }
19393
19394 // Generate NEG and CMOV for integer abs.
19395 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19396   EVT VT = N->getValueType(0);
19397
19398   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19399   // 8-bit integer abs to NEG and CMOV.
19400   if (VT.isInteger() && VT.getSizeInBits() == 8)
19401     return SDValue();
19402
19403   SDValue N0 = N->getOperand(0);
19404   SDValue N1 = N->getOperand(1);
19405   SDLoc DL(N);
19406
19407   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19408   // and change it to SUB and CMOV.
19409   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19410       N0.getOpcode() == ISD::ADD &&
19411       N0.getOperand(1) == N1 &&
19412       N1.getOpcode() == ISD::SRA &&
19413       N1.getOperand(0) == N0.getOperand(0))
19414     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19415       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19416         // Generate SUB & CMOV.
19417         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19418                                   DAG.getConstant(0, VT), N0.getOperand(0));
19419
19420         SDValue Ops[] = { N0.getOperand(0), Neg,
19421                           DAG.getConstant(X86::COND_GE, MVT::i8),
19422                           SDValue(Neg.getNode(), 1) };
19423         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19424       }
19425   return SDValue();
19426 }
19427
19428 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19429 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19430                                  TargetLowering::DAGCombinerInfo &DCI,
19431                                  const X86Subtarget *Subtarget) {
19432   if (DCI.isBeforeLegalizeOps())
19433     return SDValue();
19434
19435   if (Subtarget->hasCMov()) {
19436     SDValue RV = performIntegerAbsCombine(N, DAG);
19437     if (RV.getNode())
19438       return RV;
19439   }
19440
19441   return SDValue();
19442 }
19443
19444 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19445 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19446                                   TargetLowering::DAGCombinerInfo &DCI,
19447                                   const X86Subtarget *Subtarget) {
19448   LoadSDNode *Ld = cast<LoadSDNode>(N);
19449   EVT RegVT = Ld->getValueType(0);
19450   EVT MemVT = Ld->getMemoryVT();
19451   SDLoc dl(Ld);
19452   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19453   unsigned RegSz = RegVT.getSizeInBits();
19454
19455   // On Sandybridge unaligned 256bit loads are inefficient.
19456   ISD::LoadExtType Ext = Ld->getExtensionType();
19457   unsigned Alignment = Ld->getAlignment();
19458   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19459   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19460       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19461     unsigned NumElems = RegVT.getVectorNumElements();
19462     if (NumElems < 2)
19463       return SDValue();
19464
19465     SDValue Ptr = Ld->getBasePtr();
19466     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19467
19468     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19469                                   NumElems/2);
19470     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19471                                 Ld->getPointerInfo(), Ld->isVolatile(),
19472                                 Ld->isNonTemporal(), Ld->isInvariant(),
19473                                 Alignment);
19474     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19475     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19476                                 Ld->getPointerInfo(), Ld->isVolatile(),
19477                                 Ld->isNonTemporal(), Ld->isInvariant(),
19478                                 std::min(16U, Alignment));
19479     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19480                              Load1.getValue(1),
19481                              Load2.getValue(1));
19482
19483     SDValue NewVec = DAG.getUNDEF(RegVT);
19484     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19485     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19486     return DCI.CombineTo(N, NewVec, TF, true);
19487   }
19488
19489   // If this is a vector EXT Load then attempt to optimize it using a
19490   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19491   // expansion is still better than scalar code.
19492   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19493   // emit a shuffle and a arithmetic shift.
19494   // TODO: It is possible to support ZExt by zeroing the undef values
19495   // during the shuffle phase or after the shuffle.
19496   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19497       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19498     assert(MemVT != RegVT && "Cannot extend to the same type");
19499     assert(MemVT.isVector() && "Must load a vector from memory");
19500
19501     unsigned NumElems = RegVT.getVectorNumElements();
19502     unsigned MemSz = MemVT.getSizeInBits();
19503     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19504
19505     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19506       return SDValue();
19507
19508     // All sizes must be a power of two.
19509     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19510       return SDValue();
19511
19512     // Attempt to load the original value using scalar loads.
19513     // Find the largest scalar type that divides the total loaded size.
19514     MVT SclrLoadTy = MVT::i8;
19515     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19516          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19517       MVT Tp = (MVT::SimpleValueType)tp;
19518       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19519         SclrLoadTy = Tp;
19520       }
19521     }
19522
19523     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19524     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19525         (64 <= MemSz))
19526       SclrLoadTy = MVT::f64;
19527
19528     // Calculate the number of scalar loads that we need to perform
19529     // in order to load our vector from memory.
19530     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19531     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19532       return SDValue();
19533
19534     unsigned loadRegZize = RegSz;
19535     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19536       loadRegZize /= 2;
19537
19538     // Represent our vector as a sequence of elements which are the
19539     // largest scalar that we can load.
19540     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19541       loadRegZize/SclrLoadTy.getSizeInBits());
19542
19543     // Represent the data using the same element type that is stored in
19544     // memory. In practice, we ''widen'' MemVT.
19545     EVT WideVecVT =
19546           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19547                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19548
19549     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19550       "Invalid vector type");
19551
19552     // We can't shuffle using an illegal type.
19553     if (!TLI.isTypeLegal(WideVecVT))
19554       return SDValue();
19555
19556     SmallVector<SDValue, 8> Chains;
19557     SDValue Ptr = Ld->getBasePtr();
19558     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19559                                         TLI.getPointerTy());
19560     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19561
19562     for (unsigned i = 0; i < NumLoads; ++i) {
19563       // Perform a single load.
19564       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19565                                        Ptr, Ld->getPointerInfo(),
19566                                        Ld->isVolatile(), Ld->isNonTemporal(),
19567                                        Ld->isInvariant(), Ld->getAlignment());
19568       Chains.push_back(ScalarLoad.getValue(1));
19569       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19570       // another round of DAGCombining.
19571       if (i == 0)
19572         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19573       else
19574         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19575                           ScalarLoad, DAG.getIntPtrConstant(i));
19576
19577       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19578     }
19579
19580     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19581
19582     // Bitcast the loaded value to a vector of the original element type, in
19583     // the size of the target vector type.
19584     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19585     unsigned SizeRatio = RegSz/MemSz;
19586
19587     if (Ext == ISD::SEXTLOAD) {
19588       // If we have SSE4.1 we can directly emit a VSEXT node.
19589       if (Subtarget->hasSSE41()) {
19590         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19591         return DCI.CombineTo(N, Sext, TF, true);
19592       }
19593
19594       // Otherwise we'll shuffle the small elements in the high bits of the
19595       // larger type and perform an arithmetic shift. If the shift is not legal
19596       // it's better to scalarize.
19597       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19598         return SDValue();
19599
19600       // Redistribute the loaded elements into the different locations.
19601       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19602       for (unsigned i = 0; i != NumElems; ++i)
19603         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19604
19605       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19606                                            DAG.getUNDEF(WideVecVT),
19607                                            &ShuffleVec[0]);
19608
19609       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19610
19611       // Build the arithmetic shift.
19612       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19613                      MemVT.getVectorElementType().getSizeInBits();
19614       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19615                           DAG.getConstant(Amt, RegVT));
19616
19617       return DCI.CombineTo(N, Shuff, TF, true);
19618     }
19619
19620     // Redistribute the loaded elements into the different locations.
19621     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19622     for (unsigned i = 0; i != NumElems; ++i)
19623       ShuffleVec[i*SizeRatio] = i;
19624
19625     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19626                                          DAG.getUNDEF(WideVecVT),
19627                                          &ShuffleVec[0]);
19628
19629     // Bitcast to the requested type.
19630     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19631     // Replace the original load with the new sequence
19632     // and return the new chain.
19633     return DCI.CombineTo(N, Shuff, TF, true);
19634   }
19635
19636   return SDValue();
19637 }
19638
19639 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19640 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19641                                    const X86Subtarget *Subtarget) {
19642   StoreSDNode *St = cast<StoreSDNode>(N);
19643   EVT VT = St->getValue().getValueType();
19644   EVT StVT = St->getMemoryVT();
19645   SDLoc dl(St);
19646   SDValue StoredVal = St->getOperand(1);
19647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19648
19649   // If we are saving a concatenation of two XMM registers, perform two stores.
19650   // On Sandy Bridge, 256-bit memory operations are executed by two
19651   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19652   // memory  operation.
19653   unsigned Alignment = St->getAlignment();
19654   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19655   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19656       StVT == VT && !IsAligned) {
19657     unsigned NumElems = VT.getVectorNumElements();
19658     if (NumElems < 2)
19659       return SDValue();
19660
19661     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19662     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19663
19664     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19665     SDValue Ptr0 = St->getBasePtr();
19666     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19667
19668     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19669                                 St->getPointerInfo(), St->isVolatile(),
19670                                 St->isNonTemporal(), Alignment);
19671     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19672                                 St->getPointerInfo(), St->isVolatile(),
19673                                 St->isNonTemporal(),
19674                                 std::min(16U, Alignment));
19675     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19676   }
19677
19678   // Optimize trunc store (of multiple scalars) to shuffle and store.
19679   // First, pack all of the elements in one place. Next, store to memory
19680   // in fewer chunks.
19681   if (St->isTruncatingStore() && VT.isVector()) {
19682     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19683     unsigned NumElems = VT.getVectorNumElements();
19684     assert(StVT != VT && "Cannot truncate to the same type");
19685     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19686     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19687
19688     // From, To sizes and ElemCount must be pow of two
19689     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19690     // We are going to use the original vector elt for storing.
19691     // Accumulated smaller vector elements must be a multiple of the store size.
19692     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19693
19694     unsigned SizeRatio  = FromSz / ToSz;
19695
19696     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19697
19698     // Create a type on which we perform the shuffle
19699     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19700             StVT.getScalarType(), NumElems*SizeRatio);
19701
19702     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19703
19704     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19705     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19706     for (unsigned i = 0; i != NumElems; ++i)
19707       ShuffleVec[i] = i * SizeRatio;
19708
19709     // Can't shuffle using an illegal type.
19710     if (!TLI.isTypeLegal(WideVecVT))
19711       return SDValue();
19712
19713     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19714                                          DAG.getUNDEF(WideVecVT),
19715                                          &ShuffleVec[0]);
19716     // At this point all of the data is stored at the bottom of the
19717     // register. We now need to save it to mem.
19718
19719     // Find the largest store unit
19720     MVT StoreType = MVT::i8;
19721     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19722          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19723       MVT Tp = (MVT::SimpleValueType)tp;
19724       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19725         StoreType = Tp;
19726     }
19727
19728     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19729     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19730         (64 <= NumElems * ToSz))
19731       StoreType = MVT::f64;
19732
19733     // Bitcast the original vector into a vector of store-size units
19734     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19735             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19736     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19737     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19738     SmallVector<SDValue, 8> Chains;
19739     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19740                                         TLI.getPointerTy());
19741     SDValue Ptr = St->getBasePtr();
19742
19743     // Perform one or more big stores into memory.
19744     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19745       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19746                                    StoreType, ShuffWide,
19747                                    DAG.getIntPtrConstant(i));
19748       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19749                                 St->getPointerInfo(), St->isVolatile(),
19750                                 St->isNonTemporal(), St->getAlignment());
19751       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19752       Chains.push_back(Ch);
19753     }
19754
19755     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19756   }
19757
19758   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19759   // the FP state in cases where an emms may be missing.
19760   // A preferable solution to the general problem is to figure out the right
19761   // places to insert EMMS.  This qualifies as a quick hack.
19762
19763   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19764   if (VT.getSizeInBits() != 64)
19765     return SDValue();
19766
19767   const Function *F = DAG.getMachineFunction().getFunction();
19768   bool NoImplicitFloatOps = F->getAttributes().
19769     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19770   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19771                      && Subtarget->hasSSE2();
19772   if ((VT.isVector() ||
19773        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19774       isa<LoadSDNode>(St->getValue()) &&
19775       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19776       St->getChain().hasOneUse() && !St->isVolatile()) {
19777     SDNode* LdVal = St->getValue().getNode();
19778     LoadSDNode *Ld = nullptr;
19779     int TokenFactorIndex = -1;
19780     SmallVector<SDValue, 8> Ops;
19781     SDNode* ChainVal = St->getChain().getNode();
19782     // Must be a store of a load.  We currently handle two cases:  the load
19783     // is a direct child, and it's under an intervening TokenFactor.  It is
19784     // possible to dig deeper under nested TokenFactors.
19785     if (ChainVal == LdVal)
19786       Ld = cast<LoadSDNode>(St->getChain());
19787     else if (St->getValue().hasOneUse() &&
19788              ChainVal->getOpcode() == ISD::TokenFactor) {
19789       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19790         if (ChainVal->getOperand(i).getNode() == LdVal) {
19791           TokenFactorIndex = i;
19792           Ld = cast<LoadSDNode>(St->getValue());
19793         } else
19794           Ops.push_back(ChainVal->getOperand(i));
19795       }
19796     }
19797
19798     if (!Ld || !ISD::isNormalLoad(Ld))
19799       return SDValue();
19800
19801     // If this is not the MMX case, i.e. we are just turning i64 load/store
19802     // into f64 load/store, avoid the transformation if there are multiple
19803     // uses of the loaded value.
19804     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19805       return SDValue();
19806
19807     SDLoc LdDL(Ld);
19808     SDLoc StDL(N);
19809     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19810     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19811     // pair instead.
19812     if (Subtarget->is64Bit() || F64IsLegal) {
19813       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19814       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19815                                   Ld->getPointerInfo(), Ld->isVolatile(),
19816                                   Ld->isNonTemporal(), Ld->isInvariant(),
19817                                   Ld->getAlignment());
19818       SDValue NewChain = NewLd.getValue(1);
19819       if (TokenFactorIndex != -1) {
19820         Ops.push_back(NewChain);
19821         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19822       }
19823       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19824                           St->getPointerInfo(),
19825                           St->isVolatile(), St->isNonTemporal(),
19826                           St->getAlignment());
19827     }
19828
19829     // Otherwise, lower to two pairs of 32-bit loads / stores.
19830     SDValue LoAddr = Ld->getBasePtr();
19831     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19832                                  DAG.getConstant(4, MVT::i32));
19833
19834     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19835                                Ld->getPointerInfo(),
19836                                Ld->isVolatile(), Ld->isNonTemporal(),
19837                                Ld->isInvariant(), Ld->getAlignment());
19838     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19839                                Ld->getPointerInfo().getWithOffset(4),
19840                                Ld->isVolatile(), Ld->isNonTemporal(),
19841                                Ld->isInvariant(),
19842                                MinAlign(Ld->getAlignment(), 4));
19843
19844     SDValue NewChain = LoLd.getValue(1);
19845     if (TokenFactorIndex != -1) {
19846       Ops.push_back(LoLd);
19847       Ops.push_back(HiLd);
19848       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19849     }
19850
19851     LoAddr = St->getBasePtr();
19852     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19853                          DAG.getConstant(4, MVT::i32));
19854
19855     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19856                                 St->getPointerInfo(),
19857                                 St->isVolatile(), St->isNonTemporal(),
19858                                 St->getAlignment());
19859     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19860                                 St->getPointerInfo().getWithOffset(4),
19861                                 St->isVolatile(),
19862                                 St->isNonTemporal(),
19863                                 MinAlign(St->getAlignment(), 4));
19864     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19865   }
19866   return SDValue();
19867 }
19868
19869 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19870 /// and return the operands for the horizontal operation in LHS and RHS.  A
19871 /// horizontal operation performs the binary operation on successive elements
19872 /// of its first operand, then on successive elements of its second operand,
19873 /// returning the resulting values in a vector.  For example, if
19874 ///   A = < float a0, float a1, float a2, float a3 >
19875 /// and
19876 ///   B = < float b0, float b1, float b2, float b3 >
19877 /// then the result of doing a horizontal operation on A and B is
19878 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19879 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19880 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19881 /// set to A, RHS to B, and the routine returns 'true'.
19882 /// Note that the binary operation should have the property that if one of the
19883 /// operands is UNDEF then the result is UNDEF.
19884 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19885   // Look for the following pattern: if
19886   //   A = < float a0, float a1, float a2, float a3 >
19887   //   B = < float b0, float b1, float b2, float b3 >
19888   // and
19889   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19890   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19891   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19892   // which is A horizontal-op B.
19893
19894   // At least one of the operands should be a vector shuffle.
19895   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19896       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19897     return false;
19898
19899   MVT VT = LHS.getSimpleValueType();
19900
19901   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19902          "Unsupported vector type for horizontal add/sub");
19903
19904   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19905   // operate independently on 128-bit lanes.
19906   unsigned NumElts = VT.getVectorNumElements();
19907   unsigned NumLanes = VT.getSizeInBits()/128;
19908   unsigned NumLaneElts = NumElts / NumLanes;
19909   assert((NumLaneElts % 2 == 0) &&
19910          "Vector type should have an even number of elements in each lane");
19911   unsigned HalfLaneElts = NumLaneElts/2;
19912
19913   // View LHS in the form
19914   //   LHS = VECTOR_SHUFFLE A, B, LMask
19915   // If LHS is not a shuffle then pretend it is the shuffle
19916   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19917   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19918   // type VT.
19919   SDValue A, B;
19920   SmallVector<int, 16> LMask(NumElts);
19921   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19922     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19923       A = LHS.getOperand(0);
19924     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19925       B = LHS.getOperand(1);
19926     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19927     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19928   } else {
19929     if (LHS.getOpcode() != ISD::UNDEF)
19930       A = LHS;
19931     for (unsigned i = 0; i != NumElts; ++i)
19932       LMask[i] = i;
19933   }
19934
19935   // Likewise, view RHS in the form
19936   //   RHS = VECTOR_SHUFFLE C, D, RMask
19937   SDValue C, D;
19938   SmallVector<int, 16> RMask(NumElts);
19939   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19940     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19941       C = RHS.getOperand(0);
19942     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19943       D = RHS.getOperand(1);
19944     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19945     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19946   } else {
19947     if (RHS.getOpcode() != ISD::UNDEF)
19948       C = RHS;
19949     for (unsigned i = 0; i != NumElts; ++i)
19950       RMask[i] = i;
19951   }
19952
19953   // Check that the shuffles are both shuffling the same vectors.
19954   if (!(A == C && B == D) && !(A == D && B == C))
19955     return false;
19956
19957   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19958   if (!A.getNode() && !B.getNode())
19959     return false;
19960
19961   // If A and B occur in reverse order in RHS, then "swap" them (which means
19962   // rewriting the mask).
19963   if (A != C)
19964     CommuteVectorShuffleMask(RMask, NumElts);
19965
19966   // At this point LHS and RHS are equivalent to
19967   //   LHS = VECTOR_SHUFFLE A, B, LMask
19968   //   RHS = VECTOR_SHUFFLE A, B, RMask
19969   // Check that the masks correspond to performing a horizontal operation.
19970   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19971     for (unsigned i = 0; i != NumLaneElts; ++i) {
19972       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19973
19974       // Ignore any UNDEF components.
19975       if (LIdx < 0 || RIdx < 0 ||
19976           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19977           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19978         continue;
19979
19980       // Check that successive elements are being operated on.  If not, this is
19981       // not a horizontal operation.
19982       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19983       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19984       if (!(LIdx == Index && RIdx == Index + 1) &&
19985           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19986         return false;
19987     }
19988   }
19989
19990   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19991   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19992   return true;
19993 }
19994
19995 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19996 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19997                                   const X86Subtarget *Subtarget) {
19998   EVT VT = N->getValueType(0);
19999   SDValue LHS = N->getOperand(0);
20000   SDValue RHS = N->getOperand(1);
20001
20002   // Try to synthesize horizontal adds from adds of shuffles.
20003   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20004        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20005       isHorizontalBinOp(LHS, RHS, true))
20006     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20007   return SDValue();
20008 }
20009
20010 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20011 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20012                                   const X86Subtarget *Subtarget) {
20013   EVT VT = N->getValueType(0);
20014   SDValue LHS = N->getOperand(0);
20015   SDValue RHS = N->getOperand(1);
20016
20017   // Try to synthesize horizontal subs from subs of shuffles.
20018   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20019        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20020       isHorizontalBinOp(LHS, RHS, false))
20021     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20022   return SDValue();
20023 }
20024
20025 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20026 /// X86ISD::FXOR nodes.
20027 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20028   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20029   // F[X]OR(0.0, x) -> x
20030   // F[X]OR(x, 0.0) -> x
20031   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20032     if (C->getValueAPF().isPosZero())
20033       return N->getOperand(1);
20034   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20035     if (C->getValueAPF().isPosZero())
20036       return N->getOperand(0);
20037   return SDValue();
20038 }
20039
20040 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20041 /// X86ISD::FMAX nodes.
20042 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20043   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20044
20045   // Only perform optimizations if UnsafeMath is used.
20046   if (!DAG.getTarget().Options.UnsafeFPMath)
20047     return SDValue();
20048
20049   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20050   // into FMINC and FMAXC, which are Commutative operations.
20051   unsigned NewOp = 0;
20052   switch (N->getOpcode()) {
20053     default: llvm_unreachable("unknown opcode");
20054     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20055     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20056   }
20057
20058   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20059                      N->getOperand(0), N->getOperand(1));
20060 }
20061
20062 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20063 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20064   // FAND(0.0, x) -> 0.0
20065   // FAND(x, 0.0) -> 0.0
20066   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20067     if (C->getValueAPF().isPosZero())
20068       return N->getOperand(0);
20069   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20070     if (C->getValueAPF().isPosZero())
20071       return N->getOperand(1);
20072   return SDValue();
20073 }
20074
20075 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20076 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20077   // FANDN(x, 0.0) -> 0.0
20078   // FANDN(0.0, x) -> x
20079   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20080     if (C->getValueAPF().isPosZero())
20081       return N->getOperand(1);
20082   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20083     if (C->getValueAPF().isPosZero())
20084       return N->getOperand(1);
20085   return SDValue();
20086 }
20087
20088 static SDValue PerformBTCombine(SDNode *N,
20089                                 SelectionDAG &DAG,
20090                                 TargetLowering::DAGCombinerInfo &DCI) {
20091   // BT ignores high bits in the bit index operand.
20092   SDValue Op1 = N->getOperand(1);
20093   if (Op1.hasOneUse()) {
20094     unsigned BitWidth = Op1.getValueSizeInBits();
20095     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20096     APInt KnownZero, KnownOne;
20097     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20098                                           !DCI.isBeforeLegalizeOps());
20099     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20100     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20101         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20102       DCI.CommitTargetLoweringOpt(TLO);
20103   }
20104   return SDValue();
20105 }
20106
20107 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20108   SDValue Op = N->getOperand(0);
20109   if (Op.getOpcode() == ISD::BITCAST)
20110     Op = Op.getOperand(0);
20111   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20112   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20113       VT.getVectorElementType().getSizeInBits() ==
20114       OpVT.getVectorElementType().getSizeInBits()) {
20115     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20116   }
20117   return SDValue();
20118 }
20119
20120 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20121                                                const X86Subtarget *Subtarget) {
20122   EVT VT = N->getValueType(0);
20123   if (!VT.isVector())
20124     return SDValue();
20125
20126   SDValue N0 = N->getOperand(0);
20127   SDValue N1 = N->getOperand(1);
20128   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20129   SDLoc dl(N);
20130
20131   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20132   // both SSE and AVX2 since there is no sign-extended shift right
20133   // operation on a vector with 64-bit elements.
20134   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20135   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20136   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20137       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20138     SDValue N00 = N0.getOperand(0);
20139
20140     // EXTLOAD has a better solution on AVX2,
20141     // it may be replaced with X86ISD::VSEXT node.
20142     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20143       if (!ISD::isNormalLoad(N00.getNode()))
20144         return SDValue();
20145
20146     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20147         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20148                                   N00, N1);
20149       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20150     }
20151   }
20152   return SDValue();
20153 }
20154
20155 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20156                                   TargetLowering::DAGCombinerInfo &DCI,
20157                                   const X86Subtarget *Subtarget) {
20158   if (!DCI.isBeforeLegalizeOps())
20159     return SDValue();
20160
20161   if (!Subtarget->hasFp256())
20162     return SDValue();
20163
20164   EVT VT = N->getValueType(0);
20165   if (VT.isVector() && VT.getSizeInBits() == 256) {
20166     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20167     if (R.getNode())
20168       return R;
20169   }
20170
20171   return SDValue();
20172 }
20173
20174 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20175                                  const X86Subtarget* Subtarget) {
20176   SDLoc dl(N);
20177   EVT VT = N->getValueType(0);
20178
20179   // Let legalize expand this if it isn't a legal type yet.
20180   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20181     return SDValue();
20182
20183   EVT ScalarVT = VT.getScalarType();
20184   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20185       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20186     return SDValue();
20187
20188   SDValue A = N->getOperand(0);
20189   SDValue B = N->getOperand(1);
20190   SDValue C = N->getOperand(2);
20191
20192   bool NegA = (A.getOpcode() == ISD::FNEG);
20193   bool NegB = (B.getOpcode() == ISD::FNEG);
20194   bool NegC = (C.getOpcode() == ISD::FNEG);
20195
20196   // Negative multiplication when NegA xor NegB
20197   bool NegMul = (NegA != NegB);
20198   if (NegA)
20199     A = A.getOperand(0);
20200   if (NegB)
20201     B = B.getOperand(0);
20202   if (NegC)
20203     C = C.getOperand(0);
20204
20205   unsigned Opcode;
20206   if (!NegMul)
20207     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20208   else
20209     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20210
20211   return DAG.getNode(Opcode, dl, VT, A, B, C);
20212 }
20213
20214 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20215                                   TargetLowering::DAGCombinerInfo &DCI,
20216                                   const X86Subtarget *Subtarget) {
20217   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20218   //           (and (i32 x86isd::setcc_carry), 1)
20219   // This eliminates the zext. This transformation is necessary because
20220   // ISD::SETCC is always legalized to i8.
20221   SDLoc dl(N);
20222   SDValue N0 = N->getOperand(0);
20223   EVT VT = N->getValueType(0);
20224
20225   if (N0.getOpcode() == ISD::AND &&
20226       N0.hasOneUse() &&
20227       N0.getOperand(0).hasOneUse()) {
20228     SDValue N00 = N0.getOperand(0);
20229     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20230       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20231       if (!C || C->getZExtValue() != 1)
20232         return SDValue();
20233       return DAG.getNode(ISD::AND, dl, VT,
20234                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20235                                      N00.getOperand(0), N00.getOperand(1)),
20236                          DAG.getConstant(1, VT));
20237     }
20238   }
20239
20240   if (N0.getOpcode() == ISD::TRUNCATE &&
20241       N0.hasOneUse() &&
20242       N0.getOperand(0).hasOneUse()) {
20243     SDValue N00 = N0.getOperand(0);
20244     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20245       return DAG.getNode(ISD::AND, dl, VT,
20246                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20247                                      N00.getOperand(0), N00.getOperand(1)),
20248                          DAG.getConstant(1, VT));
20249     }
20250   }
20251   if (VT.is256BitVector()) {
20252     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20253     if (R.getNode())
20254       return R;
20255   }
20256
20257   return SDValue();
20258 }
20259
20260 // Optimize x == -y --> x+y == 0
20261 //          x != -y --> x+y != 0
20262 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20263                                       const X86Subtarget* Subtarget) {
20264   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20265   SDValue LHS = N->getOperand(0);
20266   SDValue RHS = N->getOperand(1);
20267   EVT VT = N->getValueType(0);
20268   SDLoc DL(N);
20269
20270   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20271     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20272       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20273         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20274                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20275         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20276                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20277       }
20278   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20279     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20280       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20281         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20282                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20283         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20284                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20285       }
20286
20287   if (VT.getScalarType() == MVT::i1) {
20288     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20289       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20290     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20291     if (!IsSEXT0 && !IsVZero0)
20292       return SDValue();
20293     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20294       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20295     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20296
20297     if (!IsSEXT1 && !IsVZero1)
20298       return SDValue();
20299
20300     if (IsSEXT0 && IsVZero1) {
20301       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20302       if (CC == ISD::SETEQ)
20303         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20304       return LHS.getOperand(0);
20305     }
20306     if (IsSEXT1 && IsVZero0) {
20307       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20308       if (CC == ISD::SETEQ)
20309         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20310       return RHS.getOperand(0);
20311     }
20312   }
20313
20314   return SDValue();
20315 }
20316
20317 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20318                                       const X86Subtarget *Subtarget) {
20319   SDLoc dl(N);
20320   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20321   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20322          "X86insertps is only defined for v4x32");
20323
20324   SDValue Ld = N->getOperand(1);
20325   if (MayFoldLoad(Ld)) {
20326     // Extract the countS bits from the immediate so we can get the proper
20327     // address when narrowing the vector load to a specific element.
20328     // When the second source op is a memory address, interps doesn't use
20329     // countS and just gets an f32 from that address.
20330     unsigned DestIndex =
20331         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20332     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20333   } else
20334     return SDValue();
20335
20336   // Create this as a scalar to vector to match the instruction pattern.
20337   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20338   // countS bits are ignored when loading from memory on insertps, which
20339   // means we don't need to explicitly set them to 0.
20340   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20341                      LoadScalarToVector, N->getOperand(2));
20342 }
20343
20344 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20345 // as "sbb reg,reg", since it can be extended without zext and produces
20346 // an all-ones bit which is more useful than 0/1 in some cases.
20347 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20348                                MVT VT) {
20349   if (VT == MVT::i8)
20350     return DAG.getNode(ISD::AND, DL, VT,
20351                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20352                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20353                        DAG.getConstant(1, VT));
20354   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20355   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20356                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20357                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20358 }
20359
20360 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20361 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20362                                    TargetLowering::DAGCombinerInfo &DCI,
20363                                    const X86Subtarget *Subtarget) {
20364   SDLoc DL(N);
20365   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20366   SDValue EFLAGS = N->getOperand(1);
20367
20368   if (CC == X86::COND_A) {
20369     // Try to convert COND_A into COND_B in an attempt to facilitate
20370     // materializing "setb reg".
20371     //
20372     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20373     // cannot take an immediate as its first operand.
20374     //
20375     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20376         EFLAGS.getValueType().isInteger() &&
20377         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20378       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20379                                    EFLAGS.getNode()->getVTList(),
20380                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20381       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20382       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20383     }
20384   }
20385
20386   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20387   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20388   // cases.
20389   if (CC == X86::COND_B)
20390     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20391
20392   SDValue Flags;
20393
20394   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20395   if (Flags.getNode()) {
20396     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20397     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20398   }
20399
20400   return SDValue();
20401 }
20402
20403 // Optimize branch condition evaluation.
20404 //
20405 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20406                                     TargetLowering::DAGCombinerInfo &DCI,
20407                                     const X86Subtarget *Subtarget) {
20408   SDLoc DL(N);
20409   SDValue Chain = N->getOperand(0);
20410   SDValue Dest = N->getOperand(1);
20411   SDValue EFLAGS = N->getOperand(3);
20412   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20413
20414   SDValue Flags;
20415
20416   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20417   if (Flags.getNode()) {
20418     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20419     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20420                        Flags);
20421   }
20422
20423   return SDValue();
20424 }
20425
20426 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20427                                         const X86TargetLowering *XTLI) {
20428   SDValue Op0 = N->getOperand(0);
20429   EVT InVT = Op0->getValueType(0);
20430
20431   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20432   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20433     SDLoc dl(N);
20434     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20435     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20436     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20437   }
20438
20439   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20440   // a 32-bit target where SSE doesn't support i64->FP operations.
20441   if (Op0.getOpcode() == ISD::LOAD) {
20442     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20443     EVT VT = Ld->getValueType(0);
20444     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20445         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20446         !XTLI->getSubtarget()->is64Bit() &&
20447         VT == MVT::i64) {
20448       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20449                                           Ld->getChain(), Op0, DAG);
20450       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20451       return FILDChain;
20452     }
20453   }
20454   return SDValue();
20455 }
20456
20457 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20458 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20459                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20460   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20461   // the result is either zero or one (depending on the input carry bit).
20462   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20463   if (X86::isZeroNode(N->getOperand(0)) &&
20464       X86::isZeroNode(N->getOperand(1)) &&
20465       // We don't have a good way to replace an EFLAGS use, so only do this when
20466       // dead right now.
20467       SDValue(N, 1).use_empty()) {
20468     SDLoc DL(N);
20469     EVT VT = N->getValueType(0);
20470     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20471     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20472                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20473                                            DAG.getConstant(X86::COND_B,MVT::i8),
20474                                            N->getOperand(2)),
20475                                DAG.getConstant(1, VT));
20476     return DCI.CombineTo(N, Res1, CarryOut);
20477   }
20478
20479   return SDValue();
20480 }
20481
20482 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20483 //      (add Y, (setne X, 0)) -> sbb -1, Y
20484 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20485 //      (sub (setne X, 0), Y) -> adc -1, Y
20486 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20487   SDLoc DL(N);
20488
20489   // Look through ZExts.
20490   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20491   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20492     return SDValue();
20493
20494   SDValue SetCC = Ext.getOperand(0);
20495   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20496     return SDValue();
20497
20498   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20499   if (CC != X86::COND_E && CC != X86::COND_NE)
20500     return SDValue();
20501
20502   SDValue Cmp = SetCC.getOperand(1);
20503   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20504       !X86::isZeroNode(Cmp.getOperand(1)) ||
20505       !Cmp.getOperand(0).getValueType().isInteger())
20506     return SDValue();
20507
20508   SDValue CmpOp0 = Cmp.getOperand(0);
20509   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20510                                DAG.getConstant(1, CmpOp0.getValueType()));
20511
20512   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20513   if (CC == X86::COND_NE)
20514     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20515                        DL, OtherVal.getValueType(), OtherVal,
20516                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20517   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20518                      DL, OtherVal.getValueType(), OtherVal,
20519                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20520 }
20521
20522 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20523 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20524                                  const X86Subtarget *Subtarget) {
20525   EVT VT = N->getValueType(0);
20526   SDValue Op0 = N->getOperand(0);
20527   SDValue Op1 = N->getOperand(1);
20528
20529   // Try to synthesize horizontal adds from adds of shuffles.
20530   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20531        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20532       isHorizontalBinOp(Op0, Op1, true))
20533     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20534
20535   return OptimizeConditionalInDecrement(N, DAG);
20536 }
20537
20538 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20539                                  const X86Subtarget *Subtarget) {
20540   SDValue Op0 = N->getOperand(0);
20541   SDValue Op1 = N->getOperand(1);
20542
20543   // X86 can't encode an immediate LHS of a sub. See if we can push the
20544   // negation into a preceding instruction.
20545   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20546     // If the RHS of the sub is a XOR with one use and a constant, invert the
20547     // immediate. Then add one to the LHS of the sub so we can turn
20548     // X-Y -> X+~Y+1, saving one register.
20549     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20550         isa<ConstantSDNode>(Op1.getOperand(1))) {
20551       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20552       EVT VT = Op0.getValueType();
20553       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20554                                    Op1.getOperand(0),
20555                                    DAG.getConstant(~XorC, VT));
20556       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20557                          DAG.getConstant(C->getAPIntValue()+1, VT));
20558     }
20559   }
20560
20561   // Try to synthesize horizontal adds from adds of shuffles.
20562   EVT VT = N->getValueType(0);
20563   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20564        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20565       isHorizontalBinOp(Op0, Op1, true))
20566     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20567
20568   return OptimizeConditionalInDecrement(N, DAG);
20569 }
20570
20571 /// performVZEXTCombine - Performs build vector combines
20572 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20573                                         TargetLowering::DAGCombinerInfo &DCI,
20574                                         const X86Subtarget *Subtarget) {
20575   // (vzext (bitcast (vzext (x)) -> (vzext x)
20576   SDValue In = N->getOperand(0);
20577   while (In.getOpcode() == ISD::BITCAST)
20578     In = In.getOperand(0);
20579
20580   if (In.getOpcode() != X86ISD::VZEXT)
20581     return SDValue();
20582
20583   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20584                      In.getOperand(0));
20585 }
20586
20587 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20588                                              DAGCombinerInfo &DCI) const {
20589   SelectionDAG &DAG = DCI.DAG;
20590   switch (N->getOpcode()) {
20591   default: break;
20592   case ISD::EXTRACT_VECTOR_ELT:
20593     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20594   case ISD::VSELECT:
20595   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20596   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20597   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20598   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20599   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20600   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20601   case ISD::SHL:
20602   case ISD::SRA:
20603   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20604   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20605   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20606   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20607   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20608   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20609   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20610   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20611   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20612   case X86ISD::FXOR:
20613   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20614   case X86ISD::FMIN:
20615   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20616   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20617   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20618   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20619   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20620   case ISD::ANY_EXTEND:
20621   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20622   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20623   case ISD::SIGN_EXTEND_INREG:
20624     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20625   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20626   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20627   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20628   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20629   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20630   case X86ISD::SHUFP:       // Handle all target specific shuffles
20631   case X86ISD::PALIGNR:
20632   case X86ISD::UNPCKH:
20633   case X86ISD::UNPCKL:
20634   case X86ISD::MOVHLPS:
20635   case X86ISD::MOVLHPS:
20636   case X86ISD::PSHUFD:
20637   case X86ISD::PSHUFHW:
20638   case X86ISD::PSHUFLW:
20639   case X86ISD::MOVSS:
20640   case X86ISD::MOVSD:
20641   case X86ISD::VPERMILP:
20642   case X86ISD::VPERM2X128:
20643   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20644   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20645   case ISD::INTRINSIC_WO_CHAIN:
20646     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20647   case X86ISD::INSERTPS:
20648     return PerformINSERTPSCombine(N, DAG, Subtarget);
20649   }
20650
20651   return SDValue();
20652 }
20653
20654 /// isTypeDesirableForOp - Return true if the target has native support for
20655 /// the specified value type and it is 'desirable' to use the type for the
20656 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20657 /// instruction encodings are longer and some i16 instructions are slow.
20658 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20659   if (!isTypeLegal(VT))
20660     return false;
20661   if (VT != MVT::i16)
20662     return true;
20663
20664   switch (Opc) {
20665   default:
20666     return true;
20667   case ISD::LOAD:
20668   case ISD::SIGN_EXTEND:
20669   case ISD::ZERO_EXTEND:
20670   case ISD::ANY_EXTEND:
20671   case ISD::SHL:
20672   case ISD::SRL:
20673   case ISD::SUB:
20674   case ISD::ADD:
20675   case ISD::MUL:
20676   case ISD::AND:
20677   case ISD::OR:
20678   case ISD::XOR:
20679     return false;
20680   }
20681 }
20682
20683 /// IsDesirableToPromoteOp - This method query the target whether it is
20684 /// beneficial for dag combiner to promote the specified node. If true, it
20685 /// should return the desired promotion type by reference.
20686 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20687   EVT VT = Op.getValueType();
20688   if (VT != MVT::i16)
20689     return false;
20690
20691   bool Promote = false;
20692   bool Commute = false;
20693   switch (Op.getOpcode()) {
20694   default: break;
20695   case ISD::LOAD: {
20696     LoadSDNode *LD = cast<LoadSDNode>(Op);
20697     // If the non-extending load has a single use and it's not live out, then it
20698     // might be folded.
20699     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20700                                                      Op.hasOneUse()*/) {
20701       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20702              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20703         // The only case where we'd want to promote LOAD (rather then it being
20704         // promoted as an operand is when it's only use is liveout.
20705         if (UI->getOpcode() != ISD::CopyToReg)
20706           return false;
20707       }
20708     }
20709     Promote = true;
20710     break;
20711   }
20712   case ISD::SIGN_EXTEND:
20713   case ISD::ZERO_EXTEND:
20714   case ISD::ANY_EXTEND:
20715     Promote = true;
20716     break;
20717   case ISD::SHL:
20718   case ISD::SRL: {
20719     SDValue N0 = Op.getOperand(0);
20720     // Look out for (store (shl (load), x)).
20721     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20722       return false;
20723     Promote = true;
20724     break;
20725   }
20726   case ISD::ADD:
20727   case ISD::MUL:
20728   case ISD::AND:
20729   case ISD::OR:
20730   case ISD::XOR:
20731     Commute = true;
20732     // fallthrough
20733   case ISD::SUB: {
20734     SDValue N0 = Op.getOperand(0);
20735     SDValue N1 = Op.getOperand(1);
20736     if (!Commute && MayFoldLoad(N1))
20737       return false;
20738     // Avoid disabling potential load folding opportunities.
20739     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20740       return false;
20741     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20742       return false;
20743     Promote = true;
20744   }
20745   }
20746
20747   PVT = MVT::i32;
20748   return Promote;
20749 }
20750
20751 //===----------------------------------------------------------------------===//
20752 //                           X86 Inline Assembly Support
20753 //===----------------------------------------------------------------------===//
20754
20755 namespace {
20756   // Helper to match a string separated by whitespace.
20757   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20758     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20759
20760     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20761       StringRef piece(*args[i]);
20762       if (!s.startswith(piece)) // Check if the piece matches.
20763         return false;
20764
20765       s = s.substr(piece.size());
20766       StringRef::size_type pos = s.find_first_not_of(" \t");
20767       if (pos == 0) // We matched a prefix.
20768         return false;
20769
20770       s = s.substr(pos);
20771     }
20772
20773     return s.empty();
20774   }
20775   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20776 }
20777
20778 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20779
20780   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20781     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20782         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20783         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20784
20785       if (AsmPieces.size() == 3)
20786         return true;
20787       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20788         return true;
20789     }
20790   }
20791   return false;
20792 }
20793
20794 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20795   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20796
20797   std::string AsmStr = IA->getAsmString();
20798
20799   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20800   if (!Ty || Ty->getBitWidth() % 16 != 0)
20801     return false;
20802
20803   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20804   SmallVector<StringRef, 4> AsmPieces;
20805   SplitString(AsmStr, AsmPieces, ";\n");
20806
20807   switch (AsmPieces.size()) {
20808   default: return false;
20809   case 1:
20810     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20811     // we will turn this bswap into something that will be lowered to logical
20812     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20813     // lower so don't worry about this.
20814     // bswap $0
20815     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20816         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20817         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20818         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20819         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20820         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20821       // No need to check constraints, nothing other than the equivalent of
20822       // "=r,0" would be valid here.
20823       return IntrinsicLowering::LowerToByteSwap(CI);
20824     }
20825
20826     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20827     if (CI->getType()->isIntegerTy(16) &&
20828         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20829         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20830          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20831       AsmPieces.clear();
20832       const std::string &ConstraintsStr = IA->getConstraintString();
20833       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20834       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20835       if (clobbersFlagRegisters(AsmPieces))
20836         return IntrinsicLowering::LowerToByteSwap(CI);
20837     }
20838     break;
20839   case 3:
20840     if (CI->getType()->isIntegerTy(32) &&
20841         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20842         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20843         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20844         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20845       AsmPieces.clear();
20846       const std::string &ConstraintsStr = IA->getConstraintString();
20847       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20848       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20849       if (clobbersFlagRegisters(AsmPieces))
20850         return IntrinsicLowering::LowerToByteSwap(CI);
20851     }
20852
20853     if (CI->getType()->isIntegerTy(64)) {
20854       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20855       if (Constraints.size() >= 2 &&
20856           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20857           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20858         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20859         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20860             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20861             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20862           return IntrinsicLowering::LowerToByteSwap(CI);
20863       }
20864     }
20865     break;
20866   }
20867   return false;
20868 }
20869
20870 /// getConstraintType - Given a constraint letter, return the type of
20871 /// constraint it is for this target.
20872 X86TargetLowering::ConstraintType
20873 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20874   if (Constraint.size() == 1) {
20875     switch (Constraint[0]) {
20876     case 'R':
20877     case 'q':
20878     case 'Q':
20879     case 'f':
20880     case 't':
20881     case 'u':
20882     case 'y':
20883     case 'x':
20884     case 'Y':
20885     case 'l':
20886       return C_RegisterClass;
20887     case 'a':
20888     case 'b':
20889     case 'c':
20890     case 'd':
20891     case 'S':
20892     case 'D':
20893     case 'A':
20894       return C_Register;
20895     case 'I':
20896     case 'J':
20897     case 'K':
20898     case 'L':
20899     case 'M':
20900     case 'N':
20901     case 'G':
20902     case 'C':
20903     case 'e':
20904     case 'Z':
20905       return C_Other;
20906     default:
20907       break;
20908     }
20909   }
20910   return TargetLowering::getConstraintType(Constraint);
20911 }
20912
20913 /// Examine constraint type and operand type and determine a weight value.
20914 /// This object must already have been set up with the operand type
20915 /// and the current alternative constraint selected.
20916 TargetLowering::ConstraintWeight
20917   X86TargetLowering::getSingleConstraintMatchWeight(
20918     AsmOperandInfo &info, const char *constraint) const {
20919   ConstraintWeight weight = CW_Invalid;
20920   Value *CallOperandVal = info.CallOperandVal;
20921     // If we don't have a value, we can't do a match,
20922     // but allow it at the lowest weight.
20923   if (!CallOperandVal)
20924     return CW_Default;
20925   Type *type = CallOperandVal->getType();
20926   // Look at the constraint type.
20927   switch (*constraint) {
20928   default:
20929     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20930   case 'R':
20931   case 'q':
20932   case 'Q':
20933   case 'a':
20934   case 'b':
20935   case 'c':
20936   case 'd':
20937   case 'S':
20938   case 'D':
20939   case 'A':
20940     if (CallOperandVal->getType()->isIntegerTy())
20941       weight = CW_SpecificReg;
20942     break;
20943   case 'f':
20944   case 't':
20945   case 'u':
20946     if (type->isFloatingPointTy())
20947       weight = CW_SpecificReg;
20948     break;
20949   case 'y':
20950     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20951       weight = CW_SpecificReg;
20952     break;
20953   case 'x':
20954   case 'Y':
20955     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20956         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20957       weight = CW_Register;
20958     break;
20959   case 'I':
20960     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20961       if (C->getZExtValue() <= 31)
20962         weight = CW_Constant;
20963     }
20964     break;
20965   case 'J':
20966     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20967       if (C->getZExtValue() <= 63)
20968         weight = CW_Constant;
20969     }
20970     break;
20971   case 'K':
20972     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20973       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20974         weight = CW_Constant;
20975     }
20976     break;
20977   case 'L':
20978     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20979       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20980         weight = CW_Constant;
20981     }
20982     break;
20983   case 'M':
20984     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20985       if (C->getZExtValue() <= 3)
20986         weight = CW_Constant;
20987     }
20988     break;
20989   case 'N':
20990     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20991       if (C->getZExtValue() <= 0xff)
20992         weight = CW_Constant;
20993     }
20994     break;
20995   case 'G':
20996   case 'C':
20997     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20998       weight = CW_Constant;
20999     }
21000     break;
21001   case 'e':
21002     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21003       if ((C->getSExtValue() >= -0x80000000LL) &&
21004           (C->getSExtValue() <= 0x7fffffffLL))
21005         weight = CW_Constant;
21006     }
21007     break;
21008   case 'Z':
21009     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21010       if (C->getZExtValue() <= 0xffffffff)
21011         weight = CW_Constant;
21012     }
21013     break;
21014   }
21015   return weight;
21016 }
21017
21018 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21019 /// with another that has more specific requirements based on the type of the
21020 /// corresponding operand.
21021 const char *X86TargetLowering::
21022 LowerXConstraint(EVT ConstraintVT) const {
21023   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21024   // 'f' like normal targets.
21025   if (ConstraintVT.isFloatingPoint()) {
21026     if (Subtarget->hasSSE2())
21027       return "Y";
21028     if (Subtarget->hasSSE1())
21029       return "x";
21030   }
21031
21032   return TargetLowering::LowerXConstraint(ConstraintVT);
21033 }
21034
21035 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21036 /// vector.  If it is invalid, don't add anything to Ops.
21037 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21038                                                      std::string &Constraint,
21039                                                      std::vector<SDValue>&Ops,
21040                                                      SelectionDAG &DAG) const {
21041   SDValue Result;
21042
21043   // Only support length 1 constraints for now.
21044   if (Constraint.length() > 1) return;
21045
21046   char ConstraintLetter = Constraint[0];
21047   switch (ConstraintLetter) {
21048   default: break;
21049   case 'I':
21050     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21051       if (C->getZExtValue() <= 31) {
21052         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21053         break;
21054       }
21055     }
21056     return;
21057   case 'J':
21058     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21059       if (C->getZExtValue() <= 63) {
21060         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21061         break;
21062       }
21063     }
21064     return;
21065   case 'K':
21066     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21067       if (isInt<8>(C->getSExtValue())) {
21068         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21069         break;
21070       }
21071     }
21072     return;
21073   case 'N':
21074     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21075       if (C->getZExtValue() <= 255) {
21076         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21077         break;
21078       }
21079     }
21080     return;
21081   case 'e': {
21082     // 32-bit signed value
21083     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21084       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21085                                            C->getSExtValue())) {
21086         // Widen to 64 bits here to get it sign extended.
21087         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21088         break;
21089       }
21090     // FIXME gcc accepts some relocatable values here too, but only in certain
21091     // memory models; it's complicated.
21092     }
21093     return;
21094   }
21095   case 'Z': {
21096     // 32-bit unsigned value
21097     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21098       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21099                                            C->getZExtValue())) {
21100         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21101         break;
21102       }
21103     }
21104     // FIXME gcc accepts some relocatable values here too, but only in certain
21105     // memory models; it's complicated.
21106     return;
21107   }
21108   case 'i': {
21109     // Literal immediates are always ok.
21110     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21111       // Widen to 64 bits here to get it sign extended.
21112       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21113       break;
21114     }
21115
21116     // In any sort of PIC mode addresses need to be computed at runtime by
21117     // adding in a register or some sort of table lookup.  These can't
21118     // be used as immediates.
21119     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21120       return;
21121
21122     // If we are in non-pic codegen mode, we allow the address of a global (with
21123     // an optional displacement) to be used with 'i'.
21124     GlobalAddressSDNode *GA = nullptr;
21125     int64_t Offset = 0;
21126
21127     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21128     while (1) {
21129       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21130         Offset += GA->getOffset();
21131         break;
21132       } else if (Op.getOpcode() == ISD::ADD) {
21133         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21134           Offset += C->getZExtValue();
21135           Op = Op.getOperand(0);
21136           continue;
21137         }
21138       } else if (Op.getOpcode() == ISD::SUB) {
21139         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21140           Offset += -C->getZExtValue();
21141           Op = Op.getOperand(0);
21142           continue;
21143         }
21144       }
21145
21146       // Otherwise, this isn't something we can handle, reject it.
21147       return;
21148     }
21149
21150     const GlobalValue *GV = GA->getGlobal();
21151     // If we require an extra load to get this address, as in PIC mode, we
21152     // can't accept it.
21153     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21154                                                         getTargetMachine())))
21155       return;
21156
21157     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21158                                         GA->getValueType(0), Offset);
21159     break;
21160   }
21161   }
21162
21163   if (Result.getNode()) {
21164     Ops.push_back(Result);
21165     return;
21166   }
21167   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21168 }
21169
21170 std::pair<unsigned, const TargetRegisterClass*>
21171 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21172                                                 MVT VT) const {
21173   // First, see if this is a constraint that directly corresponds to an LLVM
21174   // register class.
21175   if (Constraint.size() == 1) {
21176     // GCC Constraint Letters
21177     switch (Constraint[0]) {
21178     default: break;
21179       // TODO: Slight differences here in allocation order and leaving
21180       // RIP in the class. Do they matter any more here than they do
21181       // in the normal allocation?
21182     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21183       if (Subtarget->is64Bit()) {
21184         if (VT == MVT::i32 || VT == MVT::f32)
21185           return std::make_pair(0U, &X86::GR32RegClass);
21186         if (VT == MVT::i16)
21187           return std::make_pair(0U, &X86::GR16RegClass);
21188         if (VT == MVT::i8 || VT == MVT::i1)
21189           return std::make_pair(0U, &X86::GR8RegClass);
21190         if (VT == MVT::i64 || VT == MVT::f64)
21191           return std::make_pair(0U, &X86::GR64RegClass);
21192         break;
21193       }
21194       // 32-bit fallthrough
21195     case 'Q':   // Q_REGS
21196       if (VT == MVT::i32 || VT == MVT::f32)
21197         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21198       if (VT == MVT::i16)
21199         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21200       if (VT == MVT::i8 || VT == MVT::i1)
21201         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21202       if (VT == MVT::i64)
21203         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21204       break;
21205     case 'r':   // GENERAL_REGS
21206     case 'l':   // INDEX_REGS
21207       if (VT == MVT::i8 || VT == MVT::i1)
21208         return std::make_pair(0U, &X86::GR8RegClass);
21209       if (VT == MVT::i16)
21210         return std::make_pair(0U, &X86::GR16RegClass);
21211       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21212         return std::make_pair(0U, &X86::GR32RegClass);
21213       return std::make_pair(0U, &X86::GR64RegClass);
21214     case 'R':   // LEGACY_REGS
21215       if (VT == MVT::i8 || VT == MVT::i1)
21216         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21217       if (VT == MVT::i16)
21218         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21219       if (VT == MVT::i32 || !Subtarget->is64Bit())
21220         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21221       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21222     case 'f':  // FP Stack registers.
21223       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21224       // value to the correct fpstack register class.
21225       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21226         return std::make_pair(0U, &X86::RFP32RegClass);
21227       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21228         return std::make_pair(0U, &X86::RFP64RegClass);
21229       return std::make_pair(0U, &X86::RFP80RegClass);
21230     case 'y':   // MMX_REGS if MMX allowed.
21231       if (!Subtarget->hasMMX()) break;
21232       return std::make_pair(0U, &X86::VR64RegClass);
21233     case 'Y':   // SSE_REGS if SSE2 allowed
21234       if (!Subtarget->hasSSE2()) break;
21235       // FALL THROUGH.
21236     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21237       if (!Subtarget->hasSSE1()) break;
21238
21239       switch (VT.SimpleTy) {
21240       default: break;
21241       // Scalar SSE types.
21242       case MVT::f32:
21243       case MVT::i32:
21244         return std::make_pair(0U, &X86::FR32RegClass);
21245       case MVT::f64:
21246       case MVT::i64:
21247         return std::make_pair(0U, &X86::FR64RegClass);
21248       // Vector types.
21249       case MVT::v16i8:
21250       case MVT::v8i16:
21251       case MVT::v4i32:
21252       case MVT::v2i64:
21253       case MVT::v4f32:
21254       case MVT::v2f64:
21255         return std::make_pair(0U, &X86::VR128RegClass);
21256       // AVX types.
21257       case MVT::v32i8:
21258       case MVT::v16i16:
21259       case MVT::v8i32:
21260       case MVT::v4i64:
21261       case MVT::v8f32:
21262       case MVT::v4f64:
21263         return std::make_pair(0U, &X86::VR256RegClass);
21264       case MVT::v8f64:
21265       case MVT::v16f32:
21266       case MVT::v16i32:
21267       case MVT::v8i64:
21268         return std::make_pair(0U, &X86::VR512RegClass);
21269       }
21270       break;
21271     }
21272   }
21273
21274   // Use the default implementation in TargetLowering to convert the register
21275   // constraint into a member of a register class.
21276   std::pair<unsigned, const TargetRegisterClass*> Res;
21277   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21278
21279   // Not found as a standard register?
21280   if (!Res.second) {
21281     // Map st(0) -> st(7) -> ST0
21282     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21283         tolower(Constraint[1]) == 's' &&
21284         tolower(Constraint[2]) == 't' &&
21285         Constraint[3] == '(' &&
21286         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21287         Constraint[5] == ')' &&
21288         Constraint[6] == '}') {
21289
21290       Res.first = X86::ST0+Constraint[4]-'0';
21291       Res.second = &X86::RFP80RegClass;
21292       return Res;
21293     }
21294
21295     // GCC allows "st(0)" to be called just plain "st".
21296     if (StringRef("{st}").equals_lower(Constraint)) {
21297       Res.first = X86::ST0;
21298       Res.second = &X86::RFP80RegClass;
21299       return Res;
21300     }
21301
21302     // flags -> EFLAGS
21303     if (StringRef("{flags}").equals_lower(Constraint)) {
21304       Res.first = X86::EFLAGS;
21305       Res.second = &X86::CCRRegClass;
21306       return Res;
21307     }
21308
21309     // 'A' means EAX + EDX.
21310     if (Constraint == "A") {
21311       Res.first = X86::EAX;
21312       Res.second = &X86::GR32_ADRegClass;
21313       return Res;
21314     }
21315     return Res;
21316   }
21317
21318   // Otherwise, check to see if this is a register class of the wrong value
21319   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21320   // turn into {ax},{dx}.
21321   if (Res.second->hasType(VT))
21322     return Res;   // Correct type already, nothing to do.
21323
21324   // All of the single-register GCC register classes map their values onto
21325   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21326   // really want an 8-bit or 32-bit register, map to the appropriate register
21327   // class and return the appropriate register.
21328   if (Res.second == &X86::GR16RegClass) {
21329     if (VT == MVT::i8 || VT == MVT::i1) {
21330       unsigned DestReg = 0;
21331       switch (Res.first) {
21332       default: break;
21333       case X86::AX: DestReg = X86::AL; break;
21334       case X86::DX: DestReg = X86::DL; break;
21335       case X86::CX: DestReg = X86::CL; break;
21336       case X86::BX: DestReg = X86::BL; break;
21337       }
21338       if (DestReg) {
21339         Res.first = DestReg;
21340         Res.second = &X86::GR8RegClass;
21341       }
21342     } else if (VT == MVT::i32 || VT == MVT::f32) {
21343       unsigned DestReg = 0;
21344       switch (Res.first) {
21345       default: break;
21346       case X86::AX: DestReg = X86::EAX; break;
21347       case X86::DX: DestReg = X86::EDX; break;
21348       case X86::CX: DestReg = X86::ECX; break;
21349       case X86::BX: DestReg = X86::EBX; break;
21350       case X86::SI: DestReg = X86::ESI; break;
21351       case X86::DI: DestReg = X86::EDI; break;
21352       case X86::BP: DestReg = X86::EBP; break;
21353       case X86::SP: DestReg = X86::ESP; break;
21354       }
21355       if (DestReg) {
21356         Res.first = DestReg;
21357         Res.second = &X86::GR32RegClass;
21358       }
21359     } else if (VT == MVT::i64 || VT == MVT::f64) {
21360       unsigned DestReg = 0;
21361       switch (Res.first) {
21362       default: break;
21363       case X86::AX: DestReg = X86::RAX; break;
21364       case X86::DX: DestReg = X86::RDX; break;
21365       case X86::CX: DestReg = X86::RCX; break;
21366       case X86::BX: DestReg = X86::RBX; break;
21367       case X86::SI: DestReg = X86::RSI; break;
21368       case X86::DI: DestReg = X86::RDI; break;
21369       case X86::BP: DestReg = X86::RBP; break;
21370       case X86::SP: DestReg = X86::RSP; break;
21371       }
21372       if (DestReg) {
21373         Res.first = DestReg;
21374         Res.second = &X86::GR64RegClass;
21375       }
21376     }
21377   } else if (Res.second == &X86::FR32RegClass ||
21378              Res.second == &X86::FR64RegClass ||
21379              Res.second == &X86::VR128RegClass ||
21380              Res.second == &X86::VR256RegClass ||
21381              Res.second == &X86::FR32XRegClass ||
21382              Res.second == &X86::FR64XRegClass ||
21383              Res.second == &X86::VR128XRegClass ||
21384              Res.second == &X86::VR256XRegClass ||
21385              Res.second == &X86::VR512RegClass) {
21386     // Handle references to XMM physical registers that got mapped into the
21387     // wrong class.  This can happen with constraints like {xmm0} where the
21388     // target independent register mapper will just pick the first match it can
21389     // find, ignoring the required type.
21390
21391     if (VT == MVT::f32 || VT == MVT::i32)
21392       Res.second = &X86::FR32RegClass;
21393     else if (VT == MVT::f64 || VT == MVT::i64)
21394       Res.second = &X86::FR64RegClass;
21395     else if (X86::VR128RegClass.hasType(VT))
21396       Res.second = &X86::VR128RegClass;
21397     else if (X86::VR256RegClass.hasType(VT))
21398       Res.second = &X86::VR256RegClass;
21399     else if (X86::VR512RegClass.hasType(VT))
21400       Res.second = &X86::VR512RegClass;
21401   }
21402
21403   return Res;
21404 }
21405
21406 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21407                                             Type *Ty) const {
21408   // Scaling factors are not free at all.
21409   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21410   // will take 2 allocations in the out of order engine instead of 1
21411   // for plain addressing mode, i.e. inst (reg1).
21412   // E.g.,
21413   // vaddps (%rsi,%drx), %ymm0, %ymm1
21414   // Requires two allocations (one for the load, one for the computation)
21415   // whereas:
21416   // vaddps (%rsi), %ymm0, %ymm1
21417   // Requires just 1 allocation, i.e., freeing allocations for other operations
21418   // and having less micro operations to execute.
21419   //
21420   // For some X86 architectures, this is even worse because for instance for
21421   // stores, the complex addressing mode forces the instruction to use the
21422   // "load" ports instead of the dedicated "store" port.
21423   // E.g., on Haswell:
21424   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21425   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21426   if (isLegalAddressingMode(AM, Ty))
21427     // Scale represents reg2 * scale, thus account for 1
21428     // as soon as we use a second register.
21429     return AM.Scale != 0;
21430   return -1;
21431 }