[SKX] Added new versions of cmp instructions in avx512_icmp_cc multiclass, added...
[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/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "X86IntrinsicsInfo.h"
53 #include <bitset>
54 #include <numeric>
55 #include <cctype>
56 using namespace llvm;
57
58 #define DEBUG_TYPE "x86-isel"
59
60 STATISTIC(NumTailCalls, "Number of tail calls");
61
62 static cl::opt<bool> ExperimentalVectorWideningLegalization(
63     "x86-experimental-vector-widening-legalization", cl::init(false),
64     cl::desc("Enable an experimental vector type legalization through widening "
65              "rather than promotion."),
66     cl::Hidden);
67
68 static cl::opt<bool> ExperimentalVectorShuffleLowering(
69     "x86-experimental-vector-shuffle-lowering", cl::init(false),
70     cl::desc("Enable an experimental vector shuffle lowering code path."),
71     cl::Hidden);
72
73 // Forward declarations.
74 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
75                        SDValue V2);
76
77 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
78                                 SelectionDAG &DAG, SDLoc dl,
79                                 unsigned vectorWidth) {
80   assert((vectorWidth == 128 || vectorWidth == 256) &&
81          "Unsupported vector width");
82   EVT VT = Vec.getValueType();
83   EVT ElVT = VT.getVectorElementType();
84   unsigned Factor = VT.getSizeInBits()/vectorWidth;
85   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
86                                   VT.getVectorNumElements()/Factor);
87
88   // Extract from UNDEF is UNDEF.
89   if (Vec.getOpcode() == ISD::UNDEF)
90     return DAG.getUNDEF(ResultVT);
91
92   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
93   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94
95   // This is the index of the first element of the vectorWidth-bit chunk
96   // we want.
97   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
98                                * ElemsPerChunk);
99
100   // If the input is a buildvector just emit a smaller one.
101   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
102     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
103                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
104                                     ElemsPerChunk));
105
106   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
107   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                VecIdx);
109
110   return Result;
111
112 }
113 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
114 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
115 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
116 /// instructions or a simple subregister reference. Idx is an index in the
117 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
118 /// lowering EXTRACT_VECTOR_ELT operations easier.
119 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
120                                    SelectionDAG &DAG, SDLoc dl) {
121   assert((Vec.getValueType().is256BitVector() ||
122           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
123   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
124 }
125
126 /// Generate a DAG to grab 256-bits from a 512-bit vector.
127 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
128                                    SelectionDAG &DAG, SDLoc dl) {
129   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
130   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
131 }
132
133 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
134                                unsigned IdxVal, SelectionDAG &DAG,
135                                SDLoc dl, unsigned vectorWidth) {
136   assert((vectorWidth == 128 || vectorWidth == 256) &&
137          "Unsupported vector width");
138   // Inserting UNDEF is Result
139   if (Vec.getOpcode() == ISD::UNDEF)
140     return Result;
141   EVT VT = Vec.getValueType();
142   EVT ElVT = VT.getVectorElementType();
143   EVT ResultVT = Result.getValueType();
144
145   // Insert the relevant vectorWidth bits.
146   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147
148   // This is the index of the first element of the vectorWidth-bit chunk
149   // we want.
150   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
151                                * ElemsPerChunk);
152
153   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
154   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                      VecIdx);
156 }
157 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
158 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
159 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
160 /// simple superregister reference.  Idx is an index in the 128 bits
161 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
162 /// lowering INSERT_VECTOR_ELT operations easier.
163 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
164                                   unsigned IdxVal, SelectionDAG &DAG,
165                                   SDLoc dl) {
166   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
167   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
168 }
169
170 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
171                                   unsigned IdxVal, SelectionDAG &DAG,
172                                   SDLoc dl) {
173   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
174   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
175 }
176
177 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
178 /// instructions. This is used because creating CONCAT_VECTOR nodes of
179 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
180 /// large BUILD_VECTORS.
181 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
182                                    unsigned NumElems, SelectionDAG &DAG,
183                                    SDLoc dl) {
184   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
186 }
187
188 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
189                                    unsigned NumElems, SelectionDAG &DAG,
190                                    SDLoc dl) {
191   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
192   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
193 }
194
195 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
196   if (TT.isOSBinFormatMachO()) {
197     if (TT.getArch() == Triple::x86_64)
198       return new X86_64MachoTargetObjectFile();
199     return new TargetLoweringObjectFileMachO();
200   }
201
202   if (TT.isOSLinux())
203     return new X86LinuxTargetObjectFile();
204   if (TT.isOSBinFormatELF())
205     return new TargetLoweringObjectFileELF();
206   if (TT.isKnownWindowsMSVCEnvironment())
207     return new X86WindowsTargetObjectFile();
208   if (TT.isOSBinFormatCOFF())
209     return new TargetLoweringObjectFileCOFF();
210   llvm_unreachable("unknown subtarget type");
211 }
212
213 // FIXME: This should stop caching the target machine as soon as
214 // we can remove resetOperationActions et al.
215 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
216   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
217   Subtarget = &TM.getSubtarget<X86Subtarget>();
218   X86ScalarSSEf64 = Subtarget->hasSSE2();
219   X86ScalarSSEf32 = Subtarget->hasSSE1();
220   TD = getDataLayout();
221
222   resetOperationActions();
223 }
224
225 void X86TargetLowering::resetOperationActions() {
226   const TargetMachine &TM = getTargetMachine();
227   static bool FirstTimeThrough = true;
228
229   // If none of the target options have changed, then we don't need to reset the
230   // operation actions.
231   if (!FirstTimeThrough && TO == TM.Options) return;
232
233   if (!FirstTimeThrough) {
234     // Reinitialize the actions.
235     initActions();
236     FirstTimeThrough = false;
237   }
238
239   TO = TM.Options;
240
241   // Set up the TargetLowering object.
242   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243
244   // X86 is weird, it always uses i8 for shift amounts and setcc results.
245   setBooleanContents(ZeroOrOneBooleanContent);
246   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
247   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248
249   // For 64-bit since we have so many registers use the ILP scheduler, for
250   // 32-bit code use the register pressure specific scheduling.
251   // For Atom, always use ILP scheduling.
252   if (Subtarget->isAtom())
253     setSchedulingPreference(Sched::ILP);
254   else if (Subtarget->is64Bit())
255     setSchedulingPreference(Sched::ILP);
256   else
257     setSchedulingPreference(Sched::RegPressure);
258   const X86RegisterInfo *RegInfo =
259       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
260   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261
262   // Bypass expensive divides on Atom when compiling with O2
263   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
264     addBypassSlowDiv(32, 8);
265     if (Subtarget->is64Bit())
266       addBypassSlowDiv(64, 16);
267   }
268
269   if (Subtarget->isTargetKnownWindowsMSVC()) {
270     // Setup Windows compiler runtime calls.
271     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
272     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
273     setLibcallName(RTLIB::SREM_I64, "_allrem");
274     setLibcallName(RTLIB::UREM_I64, "_aullrem");
275     setLibcallName(RTLIB::MUL_I64, "_allmul");
276     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
280     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281
282     // The _ftol2 runtime function has an unusual calling conv, which
283     // is modeled by a special pseudo-instruction.
284     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
287     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
288   }
289
290   if (Subtarget->isTargetDarwin()) {
291     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
292     setUseUnderscoreSetJmp(false);
293     setUseUnderscoreLongJmp(false);
294   } else if (Subtarget->isTargetWindowsGNU()) {
295     // MS runtime is weird: it exports _setjmp, but longjmp!
296     setUseUnderscoreSetJmp(true);
297     setUseUnderscoreLongJmp(false);
298   } else {
299     setUseUnderscoreSetJmp(true);
300     setUseUnderscoreLongJmp(true);
301   }
302
303   // Set up the register classes.
304   addRegisterClass(MVT::i8, &X86::GR8RegClass);
305   addRegisterClass(MVT::i16, &X86::GR16RegClass);
306   addRegisterClass(MVT::i32, &X86::GR32RegClass);
307   if (Subtarget->is64Bit())
308     addRegisterClass(MVT::i64, &X86::GR64RegClass);
309
310   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311
312   // We don't accept any truncstore of integer registers.
313   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
315   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
316   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
317   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
318   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
319
320   // SETOEQ and SETUNE require checking two conditions.
321   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
323   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
326   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327
328   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329   // operation.
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
332   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
333
334   if (Subtarget->is64Bit()) {
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
336     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
337   } else if (!TM.Options.UseSoftFloat) {
338     // We have an algorithm for SSE2->double, and we turn this into a
339     // 64-bit FILD followed by conditional FADD for other targets.
340     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
341     // We have an algorithm for SSE2, and we turn this into a 64-bit
342     // FILD for other targets.
343     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
344   }
345
346   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347   // this operation.
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
349   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
350
351   if (!TM.Options.UseSoftFloat) {
352     // SSE has no i16 to fp conversion, only i32
353     if (X86ScalarSSEf32) {
354       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
355       // f32 and f64 cases are Legal, f80 case is not
356       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
357     } else {
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
359       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
360     }
361   } else {
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
363     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
364   }
365
366   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
367   // are Legal, f80 is custom lowered.
368   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
369   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
370
371   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372   // this operation.
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
374   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
375
376   if (X86ScalarSSEf32) {
377     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
378     // f32 and f64 cases are Legal, f80 case is not
379     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
380   } else {
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
382     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
383   }
384
385   // Handle FP_TO_UINT by promoting the destination to a larger signed
386   // conversion.
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
389   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
390
391   if (Subtarget->is64Bit()) {
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
393     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
394   } else if (!TM.Options.UseSoftFloat) {
395     // Since AVX is a superset of SSE3, only check for SSE here.
396     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
397       // Expand FP_TO_UINT into a select.
398       // FIXME: We would like to use a Custom expander here eventually to do
399       // the optimal thing for SSE vs. the default expansion in the legalizer.
400       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
401     else
402       // With SSE3 we can use fisttpll to convert to a signed i64; without
403       // SSE, we're stuck with a fistpll.
404       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
405   }
406
407   if (isTargetFTOL()) {
408     // Use the _ftol2 runtime function, which has a pseudo-instruction
409     // to handle its weird calling convention.
410     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
411   }
412
413   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
414   if (!X86ScalarSSEf64) {
415     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
416     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
417     if (Subtarget->is64Bit()) {
418       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
419       // Without SSE, i64->f64 goes through memory.
420       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
421     }
422   }
423
424   // Scalar integer divide and remainder are lowered to use operations that
425   // produce two results, to match the available instructions. This exposes
426   // the two-result form to trivial CSE, which is able to combine x/y and x%y
427   // into a single instruction.
428   //
429   // Scalar integer multiply-high is also lowered to use two-result
430   // operations, to match the available instructions. However, plain multiply
431   // (low) operations are left as Legal, as there are single-result
432   // instructions for this in x86. Using the two-result multiply instructions
433   // when both high and low results are needed must be arranged by dagcombine.
434   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435     MVT VT = IntVTs[i];
436     setOperationAction(ISD::MULHS, VT, Expand);
437     setOperationAction(ISD::MULHU, VT, Expand);
438     setOperationAction(ISD::SDIV, VT, Expand);
439     setOperationAction(ISD::UDIV, VT, Expand);
440     setOperationAction(ISD::SREM, VT, Expand);
441     setOperationAction(ISD::UREM, VT, Expand);
442
443     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
444     setOperationAction(ISD::ADDC, VT, Custom);
445     setOperationAction(ISD::ADDE, VT, Custom);
446     setOperationAction(ISD::SUBC, VT, Custom);
447     setOperationAction(ISD::SUBE, VT, Custom);
448   }
449
450   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
451   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
452   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
458   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
465   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
466   if (Subtarget->is64Bit())
467     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
470   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
471   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
474   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
475   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
476
477   // Promote the i8 variants and force them on up to i32 which has a shorter
478   // encoding.
479   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
480   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
481   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
482   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
483   if (Subtarget->hasBMI()) {
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
485     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
486     if (Subtarget->is64Bit())
487       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488   } else {
489     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
490     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
491     if (Subtarget->is64Bit())
492       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
493   }
494
495   if (Subtarget->hasLZCNT()) {
496     // When promoting the i8 variants, force them to i32 for a shorter
497     // encoding.
498     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
499     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
500     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
501     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
504     if (Subtarget->is64Bit())
505       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506   } else {
507     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
509     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
512     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
513     if (Subtarget->is64Bit()) {
514       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
515       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
516     }
517   }
518
519   // Special handling for half-precision floating point conversions.
520   // If we don't have F16C support, then lower half float conversions
521   // into library calls.
522   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
523     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
524     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
525   }
526
527   // There's never any support for operations beyond MVT::f32.
528   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
529   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
531   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532
533   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
536   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
537
538   if (Subtarget->hasPOPCNT()) {
539     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
540   } else {
541     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
543     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
544     if (Subtarget->is64Bit())
545       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
546   }
547
548   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
549
550   if (!Subtarget->hasMOVBE())
551     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
552
553   // These should be promoted to a larger select which is supported.
554   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
555   // X86 wants to expand cmov itself.
556   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
561   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
567   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
568   if (Subtarget->is64Bit()) {
569     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
570     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
571   }
572   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
573   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
574   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
575   // support continuation, user-level threading, and etc.. As a result, no
576   // other SjLj exception interfaces are implemented and please don't build
577   // your own exception handling based on them.
578   // LLVM/Clang supports zero-cost DWARF exception handling.
579   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
580   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
581
582   // Darwin ABI issue.
583   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
584   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
586   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
587   if (Subtarget->is64Bit())
588     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
589   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
590   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
591   if (Subtarget->is64Bit()) {
592     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
593     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
594     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
595     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
596     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
597   }
598   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
599   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
601   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
602   if (Subtarget->is64Bit()) {
603     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
605     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
606   }
607
608   if (Subtarget->hasSSE1())
609     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
610
611   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
612
613   // Expand certain atomics
614   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
615     MVT VT = IntVTs[i];
616     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
617     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
618     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
619   }
620
621   if (Subtarget->hasCmpxchg16b()) {
622     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
623   }
624
625   // FIXME - use subtarget debug flags
626   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
627       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
628     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
629   }
630
631   if (Subtarget->is64Bit()) {
632     setExceptionPointerRegister(X86::RAX);
633     setExceptionSelectorRegister(X86::RDX);
634   } else {
635     setExceptionPointerRegister(X86::EAX);
636     setExceptionSelectorRegister(X86::EDX);
637   }
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
639   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
640
641   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
642   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
643
644   setOperationAction(ISD::TRAP, MVT::Other, Legal);
645   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
646
647   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
648   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
649   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
650   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
651     // TargetInfo::X86_64ABIBuiltinVaList
652     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
653     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
654   } else {
655     // TargetInfo::CharPtrBuiltinVaList
656     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
657     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
658   }
659
660   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
661   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
662
663   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     // We support custom legalizing of sext and anyext loads for specific
1015     // memory vector types which we can load as a scalar (or sequence of
1016     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017     // loads these must work with a single scalar load.
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019     if (Subtarget->is64Bit()) {
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1022     }
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1034     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036
1037     if (Subtarget->is64Bit()) {
1038       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1039       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040     }
1041
1042     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044       MVT VT = (MVT::SimpleValueType)i;
1045
1046       // Do not attempt to promote non-128-bit vectors
1047       if (!VT.is128BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    VT, Promote);
1051       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1052       setOperationAction(ISD::OR,     VT, Promote);
1053       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1054       setOperationAction(ISD::XOR,    VT, Promote);
1055       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1056       setOperationAction(ISD::LOAD,   VT, Promote);
1057       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1058       setOperationAction(ISD::SELECT, VT, Promote);
1059       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060     }
1061
1062     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1063
1064     // Custom lower v2i64 and v2f64 selects.
1065     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1066     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1067     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1068     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1069
1070     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1072
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1075     // As there is no 64-bit GPR available, we need build a special custom
1076     // sequence to convert from v2i32 to v2f32.
1077     if (!Subtarget->is64Bit())
1078       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1079
1080     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1082
1083     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1084
1085     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1087     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1088   }
1089
1090   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1094     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1099     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1101
1102     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1105     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1106     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1107     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1110     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1111     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1112
1113     // FIXME: Do we need to handle scalar-to-vector here?
1114     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1115
1116     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1120     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1121     // There is no BLENDI for byte vectors. We don't need to custom lower
1122     // some vselects for now.
1123     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1124
1125     // SSE41 brings specific instructions for doing vector sign extend even in
1126     // cases where we don't have SRA.
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1130
1131     // i8 and i16 vectors are custom because the source register and source
1132     // source memory operand types are not the same width.  f32 vectors are
1133     // custom since the immediate controlling the insert encodes additional
1134     // information.
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1139
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1144
1145     // FIXME: these should be Legal, but that's only for the case where
1146     // the index is constant.  For now custom expand to deal with that.
1147     if (Subtarget->is64Bit()) {
1148       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1150     }
1151   }
1152
1153   if (Subtarget->hasSSE2()) {
1154     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1155     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1156
1157     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1158     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1159
1160     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1161     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1162
1163     // In the customized shift lowering, the legal cases in AVX2 will be
1164     // recognized.
1165     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1172   }
1173
1174   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1181
1182     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1184     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1185
1186     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1194     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1196     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1197     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1198
1199     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1207     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1209     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1210     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1211
1212     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213     // even though v8i16 is a legal type.
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1216     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1217
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1219     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1220     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1221
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1223     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1224
1225     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1226
1227     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1228     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1229
1230     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1231     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1232
1233     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1234     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1235
1236     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1239     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1240
1241     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1243     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1244
1245     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1248     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1249
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1252     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1255     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1258     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1261     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1262
1263     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1269       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1270     }
1271
1272     if (Subtarget->hasInt256()) {
1273       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1276       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1277
1278       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1281       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1282
1283       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1284       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1285       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1286       // Don't lower v32i8 because there is no 128-bit byte mul
1287
1288       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1290       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1291       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1292
1293       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1294       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1295     } else {
1296       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1299       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1300
1301       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1304       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1305
1306       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1309       // Don't lower v32i8 because there is no 128-bit byte mul
1310     }
1311
1312     // In the customized shift lowering, the legal cases in AVX2 will be
1313     // recognized.
1314     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1315     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1316
1317     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1318     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1319
1320     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1321
1322     // Custom lower several nodes for 256-bit types.
1323     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Extract subvector is special because the value type
1328       // (result) is 128-bit but the source is 256-bit wide.
1329       if (VT.is128BitVector())
1330         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1331
1332       // Do not attempt to custom lower other non-256-bit vectors
1333       if (!VT.is256BitVector())
1334         continue;
1335
1336       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1337       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1338       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1339       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1341       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1342       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1343     }
1344
1345     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347       MVT VT = (MVT::SimpleValueType)i;
1348
1349       // Do not attempt to promote non-256-bit vectors
1350       if (!VT.is256BitVector())
1351         continue;
1352
1353       setOperationAction(ISD::AND,    VT, Promote);
1354       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1355       setOperationAction(ISD::OR,     VT, Promote);
1356       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1357       setOperationAction(ISD::XOR,    VT, Promote);
1358       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1359       setOperationAction(ISD::LOAD,   VT, Promote);
1360       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1361       setOperationAction(ISD::SELECT, VT, Promote);
1362       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1363     }
1364   }
1365
1366   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1370     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1371
1372     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1373     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1374     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1375
1376     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1377     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1378     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1379     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1380     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1381     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1386     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1392     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1393     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1394
1395     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1399     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1400     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1401     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1402     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1403
1404     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1406     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1407     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1408     if (Subtarget->is64Bit()) {
1409       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1411       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1412       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1413     }
1414     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1422     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1423     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1424
1425     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460
1461     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1470     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1471
1472     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1473     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1474
1475     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1476     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1477
1478     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1480     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1482     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1483     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1484
1485     if (Subtarget->hasCDI()) {
1486       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1487       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1488     }
1489
1490     // Custom lower several nodes.
1491     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493       MVT VT = (MVT::SimpleValueType)i;
1494
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       // Extract subvector is special because the value type
1497       // (result) is 256/128-bit but the source is 512-bit wide.
1498       if (VT.is128BitVector() || VT.is256BitVector())
1499         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1500
1501       if (VT.getVectorElementType() == MVT::i1)
1502         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1503
1504       // Do not attempt to custom lower other non-512-bit vectors
1505       if (!VT.is512BitVector())
1506         continue;
1507
1508       if ( EltSize >= 32) {
1509         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1510         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1511         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1512         setOperationAction(ISD::VSELECT,             VT, Legal);
1513         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1514         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1515         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1516       }
1517     }
1518     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519       MVT VT = (MVT::SimpleValueType)i;
1520
1521       // Do not attempt to promote non-256-bit vectors
1522       if (!VT.is512BitVector())
1523         continue;
1524
1525       setOperationAction(ISD::SELECT, VT, Promote);
1526       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1527     }
1528   }// has  AVX-512
1529
1530   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1532     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1533   }
1534
1535   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536   // of this type with custom code.
1537   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1540                        Custom);
1541   }
1542
1543   // We want to custom lower some of our intrinsics.
1544   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547   if (!Subtarget->is64Bit())
1548     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1549
1550   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551   // handle type legalization for these operations here.
1552   //
1553   // FIXME: We really should do custom legalization for addition and
1554   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1555   // than generic legalization for 64-bit multiplication-with-overflow, though.
1556   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557     // Add/Sub/Mul with overflow operations are custom lowered.
1558     MVT VT = IntVTs[i];
1559     setOperationAction(ISD::SADDO, VT, Custom);
1560     setOperationAction(ISD::UADDO, VT, Custom);
1561     setOperationAction(ISD::SSUBO, VT, Custom);
1562     setOperationAction(ISD::USUBO, VT, Custom);
1563     setOperationAction(ISD::SMULO, VT, Custom);
1564     setOperationAction(ISD::UMULO, VT, Custom);
1565   }
1566
1567   // There are no 8-bit 3-address imul/mul instructions
1568   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1570
1571   if (!Subtarget->is64Bit()) {
1572     // These libcalls are not available in 32-bit.
1573     setLibcallName(RTLIB::SHL_I128, nullptr);
1574     setLibcallName(RTLIB::SRL_I128, nullptr);
1575     setLibcallName(RTLIB::SRA_I128, nullptr);
1576   }
1577
1578   // Combine sin / cos into one node or libcall if possible.
1579   if (Subtarget->hasSinCos()) {
1580     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582     if (Subtarget->isTargetDarwin()) {
1583       // For MacOSX, we don't want to the normal expansion of a libcall to
1584       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1585       // traffic.
1586       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1588     }
1589   }
1590
1591   if (Subtarget->isTargetWin64()) {
1592     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::SREM, MVT::i128, Custom);
1595     setOperationAction(ISD::UREM, MVT::i128, Custom);
1596     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1598   }
1599
1600   // We have target-specific dag combine patterns for the following nodes:
1601   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603   setTargetDAGCombine(ISD::VSELECT);
1604   setTargetDAGCombine(ISD::SELECT);
1605   setTargetDAGCombine(ISD::SHL);
1606   setTargetDAGCombine(ISD::SRA);
1607   setTargetDAGCombine(ISD::SRL);
1608   setTargetDAGCombine(ISD::OR);
1609   setTargetDAGCombine(ISD::AND);
1610   setTargetDAGCombine(ISD::ADD);
1611   setTargetDAGCombine(ISD::FADD);
1612   setTargetDAGCombine(ISD::FSUB);
1613   setTargetDAGCombine(ISD::FMA);
1614   setTargetDAGCombine(ISD::SUB);
1615   setTargetDAGCombine(ISD::LOAD);
1616   setTargetDAGCombine(ISD::STORE);
1617   setTargetDAGCombine(ISD::ZERO_EXTEND);
1618   setTargetDAGCombine(ISD::ANY_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND);
1620   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621   setTargetDAGCombine(ISD::TRUNCATE);
1622   setTargetDAGCombine(ISD::SINT_TO_FP);
1623   setTargetDAGCombine(ISD::SETCC);
1624   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625   setTargetDAGCombine(ISD::BUILD_VECTOR);
1626   if (Subtarget->is64Bit())
1627     setTargetDAGCombine(ISD::MUL);
1628   setTargetDAGCombine(ISD::XOR);
1629
1630   computeRegisterProperties();
1631
1632   // On Darwin, -Os means optimize for size without hurting performance,
1633   // do not reduce the limit.
1634   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   setPrefLoopAlignment(4); // 2^4 bytes.
1641
1642   // Predictable cmov don't hurt on atom because it's in-order.
1643   PredictableSelectIsExpensive = !Subtarget->isAtom();
1644
1645   setPrefFunctionAlignment(4); // 2^4 bytes.
1646
1647   InitIntrinsicTables();
1648 }
1649
1650 // This has so far only been implemented for 64-bit MachO.
1651 bool X86TargetLowering::useLoadStackGuardNode() const {
1652   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1653          Subtarget->is64Bit();
1654 }
1655
1656 TargetLoweringBase::LegalizeTypeAction
1657 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1658   if (ExperimentalVectorWideningLegalization &&
1659       VT.getVectorNumElements() != 1 &&
1660       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1661     return TypeWidenVector;
1662
1663   return TargetLoweringBase::getPreferredVectorAction(VT);
1664 }
1665
1666 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1667   if (!VT.isVector())
1668     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1669
1670   if (Subtarget->hasAVX512())
1671     switch(VT.getVectorNumElements()) {
1672     case  8: return MVT::v8i1;
1673     case 16: return MVT::v16i1;
1674   }
1675
1676   return VT.changeVectorElementTypeToInteger();
1677 }
1678
1679 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1680 /// the desired ByVal argument alignment.
1681 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1682   if (MaxAlign == 16)
1683     return;
1684   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1685     if (VTy->getBitWidth() == 128)
1686       MaxAlign = 16;
1687   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1688     unsigned EltAlign = 0;
1689     getMaxByValAlign(ATy->getElementType(), EltAlign);
1690     if (EltAlign > MaxAlign)
1691       MaxAlign = EltAlign;
1692   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1693     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1694       unsigned EltAlign = 0;
1695       getMaxByValAlign(STy->getElementType(i), EltAlign);
1696       if (EltAlign > MaxAlign)
1697         MaxAlign = EltAlign;
1698       if (MaxAlign == 16)
1699         break;
1700     }
1701   }
1702 }
1703
1704 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1705 /// function arguments in the caller parameter area. For X86, aggregates
1706 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1707 /// are at 4-byte boundaries.
1708 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1709   if (Subtarget->is64Bit()) {
1710     // Max of 8 and alignment of type.
1711     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1712     if (TyAlign > 8)
1713       return TyAlign;
1714     return 8;
1715   }
1716
1717   unsigned Align = 4;
1718   if (Subtarget->hasSSE1())
1719     getMaxByValAlign(Ty, Align);
1720   return Align;
1721 }
1722
1723 /// getOptimalMemOpType - Returns the target specific optimal type for load
1724 /// and store operations as a result of memset, memcpy, and memmove
1725 /// lowering. If DstAlign is zero that means it's safe to destination
1726 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1727 /// means there isn't a need to check it against alignment requirement,
1728 /// probably because the source does not need to be loaded. If 'IsMemset' is
1729 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1730 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1731 /// source is constant so it does not need to be loaded.
1732 /// It returns EVT::Other if the type should be determined using generic
1733 /// target-independent logic.
1734 EVT
1735 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1736                                        unsigned DstAlign, unsigned SrcAlign,
1737                                        bool IsMemset, bool ZeroMemset,
1738                                        bool MemcpyStrSrc,
1739                                        MachineFunction &MF) const {
1740   const Function *F = MF.getFunction();
1741   if ((!IsMemset || ZeroMemset) &&
1742       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1743                                        Attribute::NoImplicitFloat)) {
1744     if (Size >= 16 &&
1745         (Subtarget->isUnalignedMemAccessFast() ||
1746          ((DstAlign == 0 || DstAlign >= 16) &&
1747           (SrcAlign == 0 || SrcAlign >= 16)))) {
1748       if (Size >= 32) {
1749         if (Subtarget->hasInt256())
1750           return MVT::v8i32;
1751         if (Subtarget->hasFp256())
1752           return MVT::v8f32;
1753       }
1754       if (Subtarget->hasSSE2())
1755         return MVT::v4i32;
1756       if (Subtarget->hasSSE1())
1757         return MVT::v4f32;
1758     } else if (!MemcpyStrSrc && Size >= 8 &&
1759                !Subtarget->is64Bit() &&
1760                Subtarget->hasSSE2()) {
1761       // Do not use f64 to lower memcpy if source is string constant. It's
1762       // better to use i32 to avoid the loads.
1763       return MVT::f64;
1764     }
1765   }
1766   if (Subtarget->is64Bit() && Size >= 8)
1767     return MVT::i64;
1768   return MVT::i32;
1769 }
1770
1771 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1772   if (VT == MVT::f32)
1773     return X86ScalarSSEf32;
1774   else if (VT == MVT::f64)
1775     return X86ScalarSSEf64;
1776   return true;
1777 }
1778
1779 bool
1780 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1781                                                   unsigned,
1782                                                   unsigned,
1783                                                   bool *Fast) const {
1784   if (Fast)
1785     *Fast = Subtarget->isUnalignedMemAccessFast();
1786   return true;
1787 }
1788
1789 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1790 /// current function.  The returned value is a member of the
1791 /// MachineJumpTableInfo::JTEntryKind enum.
1792 unsigned X86TargetLowering::getJumpTableEncoding() const {
1793   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1794   // symbol.
1795   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1796       Subtarget->isPICStyleGOT())
1797     return MachineJumpTableInfo::EK_Custom32;
1798
1799   // Otherwise, use the normal jump table encoding heuristics.
1800   return TargetLowering::getJumpTableEncoding();
1801 }
1802
1803 const MCExpr *
1804 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1805                                              const MachineBasicBlock *MBB,
1806                                              unsigned uid,MCContext &Ctx) const{
1807   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1808          Subtarget->isPICStyleGOT());
1809   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1810   // entries.
1811   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1812                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1813 }
1814
1815 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1816 /// jumptable.
1817 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1818                                                     SelectionDAG &DAG) const {
1819   if (!Subtarget->is64Bit())
1820     // This doesn't have SDLoc associated with it, but is not really the
1821     // same as a Register.
1822     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1823   return Table;
1824 }
1825
1826 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1827 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1828 /// MCExpr.
1829 const MCExpr *X86TargetLowering::
1830 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1831                              MCContext &Ctx) const {
1832   // X86-64 uses RIP relative addressing based on the jump table label.
1833   if (Subtarget->isPICStyleRIPRel())
1834     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1835
1836   // Otherwise, the reference is relative to the PIC base.
1837   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1838 }
1839
1840 // FIXME: Why this routine is here? Move to RegInfo!
1841 std::pair<const TargetRegisterClass*, uint8_t>
1842 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1843   const TargetRegisterClass *RRC = nullptr;
1844   uint8_t Cost = 1;
1845   switch (VT.SimpleTy) {
1846   default:
1847     return TargetLowering::findRepresentativeClass(VT);
1848   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1849     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1850     break;
1851   case MVT::x86mmx:
1852     RRC = &X86::VR64RegClass;
1853     break;
1854   case MVT::f32: case MVT::f64:
1855   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856   case MVT::v4f32: case MVT::v2f64:
1857   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1858   case MVT::v4f64:
1859     RRC = &X86::VR128RegClass;
1860     break;
1861   }
1862   return std::make_pair(RRC, Cost);
1863 }
1864
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866                                                unsigned &Offset) const {
1867   if (!Subtarget->isTargetLinux())
1868     return false;
1869
1870   if (Subtarget->is64Bit()) {
1871     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1872     Offset = 0x28;
1873     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1874       AddressSpace = 256;
1875     else
1876       AddressSpace = 257;
1877   } else {
1878     // %gs:0x14 on i386
1879     Offset = 0x14;
1880     AddressSpace = 256;
1881   }
1882   return true;
1883 }
1884
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886                                             unsigned DestAS) const {
1887   assert(SrcAS != DestAS && "Expected different address spaces!");
1888
1889   return SrcAS < 256 && DestAS < 256;
1890 }
1891
1892 //===----------------------------------------------------------------------===//
1893 //               Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1895
1896 #include "X86GenCallingConv.inc"
1897
1898 bool
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900                                   MachineFunction &MF, bool isVarArg,
1901                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1902                         LLVMContext &Context) const {
1903   SmallVector<CCValAssign, 16> RVLocs;
1904   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1905   return CCInfo.CheckReturn(Outs, RetCC_X86);
1906 }
1907
1908 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1909   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1910   return ScratchRegs;
1911 }
1912
1913 SDValue
1914 X86TargetLowering::LowerReturn(SDValue Chain,
1915                                CallingConv::ID CallConv, bool isVarArg,
1916                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1917                                const SmallVectorImpl<SDValue> &OutVals,
1918                                SDLoc dl, SelectionDAG &DAG) const {
1919   MachineFunction &MF = DAG.getMachineFunction();
1920   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1921
1922   SmallVector<CCValAssign, 16> RVLocs;
1923   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1924   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1925
1926   SDValue Flag;
1927   SmallVector<SDValue, 6> RetOps;
1928   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1929   // Operand #1 = Bytes To Pop
1930   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1931                    MVT::i16));
1932
1933   // Copy the result values into the output registers.
1934   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1935     CCValAssign &VA = RVLocs[i];
1936     assert(VA.isRegLoc() && "Can only return in registers!");
1937     SDValue ValToCopy = OutVals[i];
1938     EVT ValVT = ValToCopy.getValueType();
1939
1940     // Promote values to the appropriate types
1941     if (VA.getLocInfo() == CCValAssign::SExt)
1942       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1943     else if (VA.getLocInfo() == CCValAssign::ZExt)
1944       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945     else if (VA.getLocInfo() == CCValAssign::AExt)
1946       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::BCvt)
1948       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1949
1950     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1951            "Unexpected FP-extend for return value.");  
1952
1953     // If this is x86-64, and we disabled SSE, we can't return FP values,
1954     // or SSE or MMX vectors.
1955     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1956          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1957           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1958       report_fatal_error("SSE register return with SSE disabled");
1959     }
1960     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1961     // llvm-gcc has never done it right and no one has noticed, so this
1962     // should be OK for now.
1963     if (ValVT == MVT::f64 &&
1964         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1965       report_fatal_error("SSE2 register return with SSE2 disabled");
1966
1967     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1968     // the RET instruction and handled by the FP Stackifier.
1969     if (VA.getLocReg() == X86::FP0 ||
1970         VA.getLocReg() == X86::FP1) {
1971       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1972       // change the value to the FP stack register class.
1973       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1974         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1975       RetOps.push_back(ValToCopy);
1976       // Don't emit a copytoreg.
1977       continue;
1978     }
1979
1980     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1981     // which is returned in RAX / RDX.
1982     if (Subtarget->is64Bit()) {
1983       if (ValVT == MVT::x86mmx) {
1984         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1985           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1986           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1987                                   ValToCopy);
1988           // If we don't have SSE2 available, convert to v4f32 so the generated
1989           // register is legal.
1990           if (!Subtarget->hasSSE2())
1991             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1992         }
1993       }
1994     }
1995
1996     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1997     Flag = Chain.getValue(1);
1998     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1999   }
2000
2001   // The x86-64 ABIs require that for returning structs by value we copy
2002   // the sret argument into %rax/%eax (depending on ABI) for the return.
2003   // Win32 requires us to put the sret argument to %eax as well.
2004   // We saved the argument into a virtual register in the entry block,
2005   // so now we copy the value out and into %rax/%eax.
2006   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2007       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2008     MachineFunction &MF = DAG.getMachineFunction();
2009     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2010     unsigned Reg = FuncInfo->getSRetReturnReg();
2011     assert(Reg &&
2012            "SRetReturnReg should have been set in LowerFormalArguments().");
2013     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2014
2015     unsigned RetValReg
2016         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2017           X86::RAX : X86::EAX;
2018     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2019     Flag = Chain.getValue(1);
2020
2021     // RAX/EAX now acts like a return value.
2022     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2023   }
2024
2025   RetOps[0] = Chain;  // Update chain.
2026
2027   // Add the flag if we have it.
2028   if (Flag.getNode())
2029     RetOps.push_back(Flag);
2030
2031   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2032 }
2033
2034 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2035   if (N->getNumValues() != 1)
2036     return false;
2037   if (!N->hasNUsesOfValue(1, 0))
2038     return false;
2039
2040   SDValue TCChain = Chain;
2041   SDNode *Copy = *N->use_begin();
2042   if (Copy->getOpcode() == ISD::CopyToReg) {
2043     // If the copy has a glue operand, we conservatively assume it isn't safe to
2044     // perform a tail call.
2045     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2046       return false;
2047     TCChain = Copy->getOperand(0);
2048   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2049     return false;
2050
2051   bool HasRet = false;
2052   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2053        UI != UE; ++UI) {
2054     if (UI->getOpcode() != X86ISD::RET_FLAG)
2055       return false;
2056     // If we are returning more than one value, we can definitely
2057     // not make a tail call see PR19530
2058     if (UI->getNumOperands() > 4)
2059       return false;
2060     if (UI->getNumOperands() == 4 &&
2061         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2062       return false;
2063     HasRet = true;
2064   }
2065
2066   if (!HasRet)
2067     return false;
2068
2069   Chain = TCChain;
2070   return true;
2071 }
2072
2073 EVT
2074 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2075                                             ISD::NodeType ExtendKind) const {
2076   MVT ReturnMVT;
2077   // TODO: Is this also valid on 32-bit?
2078   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2079     ReturnMVT = MVT::i8;
2080   else
2081     ReturnMVT = MVT::i32;
2082
2083   EVT MinVT = getRegisterType(Context, ReturnMVT);
2084   return VT.bitsLT(MinVT) ? MinVT : VT;
2085 }
2086
2087 /// LowerCallResult - Lower the result values of a call into the
2088 /// appropriate copies out of appropriate physical registers.
2089 ///
2090 SDValue
2091 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2092                                    CallingConv::ID CallConv, bool isVarArg,
2093                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2094                                    SDLoc dl, SelectionDAG &DAG,
2095                                    SmallVectorImpl<SDValue> &InVals) const {
2096
2097   // Assign locations to each value returned by this call.
2098   SmallVector<CCValAssign, 16> RVLocs;
2099   bool Is64Bit = Subtarget->is64Bit();
2100   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2101                  *DAG.getContext());
2102   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2103
2104   // Copy all of the result registers out of their specified physreg.
2105   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2106     CCValAssign &VA = RVLocs[i];
2107     EVT CopyVT = VA.getValVT();
2108
2109     // If this is x86-64, and we disabled SSE, we can't return FP values
2110     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2111         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2112       report_fatal_error("SSE register return with SSE disabled");
2113     }
2114
2115     // If we prefer to use the value in xmm registers, copy it out as f80 and
2116     // use a truncate to move it from fp stack reg to xmm reg.
2117     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2118         isScalarFPTypeInSSEReg(VA.getValVT()))
2119       CopyVT = MVT::f80;
2120
2121     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2122                                CopyVT, InFlag).getValue(1);
2123     SDValue Val = Chain.getValue(0);
2124
2125     if (CopyVT != VA.getValVT())
2126       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2127                         // This truncation won't change the value.
2128                         DAG.getIntPtrConstant(1));
2129
2130     InFlag = Chain.getValue(2);
2131     InVals.push_back(Val);
2132   }
2133
2134   return Chain;
2135 }
2136
2137 //===----------------------------------------------------------------------===//
2138 //                C & StdCall & Fast Calling Convention implementation
2139 //===----------------------------------------------------------------------===//
2140 //  StdCall calling convention seems to be standard for many Windows' API
2141 //  routines and around. It differs from C calling convention just a little:
2142 //  callee should clean up the stack, not caller. Symbols should be also
2143 //  decorated in some fancy way :) It doesn't support any vector arguments.
2144 //  For info on fast calling convention see Fast Calling Convention (tail call)
2145 //  implementation LowerX86_32FastCCCallTo.
2146
2147 /// CallIsStructReturn - Determines whether a call uses struct return
2148 /// semantics.
2149 enum StructReturnType {
2150   NotStructReturn,
2151   RegStructReturn,
2152   StackStructReturn
2153 };
2154 static StructReturnType
2155 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2156   if (Outs.empty())
2157     return NotStructReturn;
2158
2159   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2160   if (!Flags.isSRet())
2161     return NotStructReturn;
2162   if (Flags.isInReg())
2163     return RegStructReturn;
2164   return StackStructReturn;
2165 }
2166
2167 /// ArgsAreStructReturn - Determines whether a function uses struct
2168 /// return semantics.
2169 static StructReturnType
2170 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2171   if (Ins.empty())
2172     return NotStructReturn;
2173
2174   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2175   if (!Flags.isSRet())
2176     return NotStructReturn;
2177   if (Flags.isInReg())
2178     return RegStructReturn;
2179   return StackStructReturn;
2180 }
2181
2182 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2183 /// by "Src" to address "Dst" with size and alignment information specified by
2184 /// the specific parameter attribute. The copy will be passed as a byval
2185 /// function parameter.
2186 static SDValue
2187 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2188                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2189                           SDLoc dl) {
2190   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2191
2192   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2193                        /*isVolatile*/false, /*AlwaysInline=*/true,
2194                        MachinePointerInfo(), MachinePointerInfo());
2195 }
2196
2197 /// IsTailCallConvention - Return true if the calling convention is one that
2198 /// supports tail call optimization.
2199 static bool IsTailCallConvention(CallingConv::ID CC) {
2200   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2201           CC == CallingConv::HiPE);
2202 }
2203
2204 /// \brief Return true if the calling convention is a C calling convention.
2205 static bool IsCCallConvention(CallingConv::ID CC) {
2206   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2207           CC == CallingConv::X86_64_SysV);
2208 }
2209
2210 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2211   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2212     return false;
2213
2214   CallSite CS(CI);
2215   CallingConv::ID CalleeCC = CS.getCallingConv();
2216   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2217     return false;
2218
2219   return true;
2220 }
2221
2222 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2223 /// a tailcall target by changing its ABI.
2224 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2225                                    bool GuaranteedTailCallOpt) {
2226   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2227 }
2228
2229 SDValue
2230 X86TargetLowering::LowerMemArgument(SDValue Chain,
2231                                     CallingConv::ID CallConv,
2232                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2233                                     SDLoc dl, SelectionDAG &DAG,
2234                                     const CCValAssign &VA,
2235                                     MachineFrameInfo *MFI,
2236                                     unsigned i) const {
2237   // Create the nodes corresponding to a load from this parameter slot.
2238   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2239   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2240       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2241   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2242   EVT ValVT;
2243
2244   // If value is passed by pointer we have address passed instead of the value
2245   // itself.
2246   if (VA.getLocInfo() == CCValAssign::Indirect)
2247     ValVT = VA.getLocVT();
2248   else
2249     ValVT = VA.getValVT();
2250
2251   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2252   // changed with more analysis.
2253   // In case of tail call optimization mark all arguments mutable. Since they
2254   // could be overwritten by lowering of arguments in case of a tail call.
2255   if (Flags.isByVal()) {
2256     unsigned Bytes = Flags.getByValSize();
2257     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2258     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2259     return DAG.getFrameIndex(FI, getPointerTy());
2260   } else {
2261     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2262                                     VA.getLocMemOffset(), isImmutable);
2263     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2264     return DAG.getLoad(ValVT, dl, Chain, FIN,
2265                        MachinePointerInfo::getFixedStack(FI),
2266                        false, false, false, 0);
2267   }
2268 }
2269
2270 SDValue
2271 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2272                                         CallingConv::ID CallConv,
2273                                         bool isVarArg,
2274                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2275                                         SDLoc dl,
2276                                         SelectionDAG &DAG,
2277                                         SmallVectorImpl<SDValue> &InVals)
2278                                           const {
2279   MachineFunction &MF = DAG.getMachineFunction();
2280   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2281
2282   const Function* Fn = MF.getFunction();
2283   if (Fn->hasExternalLinkage() &&
2284       Subtarget->isTargetCygMing() &&
2285       Fn->getName() == "main")
2286     FuncInfo->setForceFramePointer(true);
2287
2288   MachineFrameInfo *MFI = MF.getFrameInfo();
2289   bool Is64Bit = Subtarget->is64Bit();
2290   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2291
2292   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2293          "Var args not supported with calling convention fastcc, ghc or hipe");
2294
2295   // Assign locations to all of the incoming arguments.
2296   SmallVector<CCValAssign, 16> ArgLocs;
2297   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2298
2299   // Allocate shadow area for Win64
2300   if (IsWin64)
2301     CCInfo.AllocateStack(32, 8);
2302
2303   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2304
2305   unsigned LastVal = ~0U;
2306   SDValue ArgValue;
2307   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2308     CCValAssign &VA = ArgLocs[i];
2309     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2310     // places.
2311     assert(VA.getValNo() != LastVal &&
2312            "Don't support value assigned to multiple locs yet");
2313     (void)LastVal;
2314     LastVal = VA.getValNo();
2315
2316     if (VA.isRegLoc()) {
2317       EVT RegVT = VA.getLocVT();
2318       const TargetRegisterClass *RC;
2319       if (RegVT == MVT::i32)
2320         RC = &X86::GR32RegClass;
2321       else if (Is64Bit && RegVT == MVT::i64)
2322         RC = &X86::GR64RegClass;
2323       else if (RegVT == MVT::f32)
2324         RC = &X86::FR32RegClass;
2325       else if (RegVT == MVT::f64)
2326         RC = &X86::FR64RegClass;
2327       else if (RegVT.is512BitVector())
2328         RC = &X86::VR512RegClass;
2329       else if (RegVT.is256BitVector())
2330         RC = &X86::VR256RegClass;
2331       else if (RegVT.is128BitVector())
2332         RC = &X86::VR128RegClass;
2333       else if (RegVT == MVT::x86mmx)
2334         RC = &X86::VR64RegClass;
2335       else if (RegVT == MVT::i1)
2336         RC = &X86::VK1RegClass;
2337       else if (RegVT == MVT::v8i1)
2338         RC = &X86::VK8RegClass;
2339       else if (RegVT == MVT::v16i1)
2340         RC = &X86::VK16RegClass;
2341       else if (RegVT == MVT::v32i1)
2342         RC = &X86::VK32RegClass;
2343       else if (RegVT == MVT::v64i1)
2344         RC = &X86::VK64RegClass;
2345       else
2346         llvm_unreachable("Unknown argument type!");
2347
2348       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2349       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2350
2351       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2352       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2353       // right size.
2354       if (VA.getLocInfo() == CCValAssign::SExt)
2355         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2356                                DAG.getValueType(VA.getValVT()));
2357       else if (VA.getLocInfo() == CCValAssign::ZExt)
2358         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2359                                DAG.getValueType(VA.getValVT()));
2360       else if (VA.getLocInfo() == CCValAssign::BCvt)
2361         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2362
2363       if (VA.isExtInLoc()) {
2364         // Handle MMX values passed in XMM regs.
2365         if (RegVT.isVector())
2366           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2367         else
2368           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2369       }
2370     } else {
2371       assert(VA.isMemLoc());
2372       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2373     }
2374
2375     // If value is passed via pointer - do a load.
2376     if (VA.getLocInfo() == CCValAssign::Indirect)
2377       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2378                              MachinePointerInfo(), false, false, false, 0);
2379
2380     InVals.push_back(ArgValue);
2381   }
2382
2383   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2384     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2385       // The x86-64 ABIs require that for returning structs by value we copy
2386       // the sret argument into %rax/%eax (depending on ABI) for the return.
2387       // Win32 requires us to put the sret argument to %eax as well.
2388       // Save the argument into a virtual register so that we can access it
2389       // from the return points.
2390       if (Ins[i].Flags.isSRet()) {
2391         unsigned Reg = FuncInfo->getSRetReturnReg();
2392         if (!Reg) {
2393           MVT PtrTy = getPointerTy();
2394           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2395           FuncInfo->setSRetReturnReg(Reg);
2396         }
2397         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2398         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2399         break;
2400       }
2401     }
2402   }
2403
2404   unsigned StackSize = CCInfo.getNextStackOffset();
2405   // Align stack specially for tail calls.
2406   if (FuncIsMadeTailCallSafe(CallConv,
2407                              MF.getTarget().Options.GuaranteedTailCallOpt))
2408     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2409
2410   // If the function takes variable number of arguments, make a frame index for
2411   // the start of the first vararg value... for expansion of llvm.va_start. We
2412   // can skip this if there are no va_start calls.
2413   if (isVarArg && MFI->hasVAStart()) {
2414     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2415                     CallConv != CallingConv::X86_ThisCall)) {
2416       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2417     }
2418     if (Is64Bit) {
2419       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2420
2421       // FIXME: We should really autogenerate these arrays
2422       static const MCPhysReg GPR64ArgRegsWin64[] = {
2423         X86::RCX, X86::RDX, X86::R8,  X86::R9
2424       };
2425       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2426         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2427       };
2428       static const MCPhysReg XMMArgRegs64Bit[] = {
2429         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2430         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2431       };
2432       const MCPhysReg *GPR64ArgRegs;
2433       unsigned NumXMMRegs = 0;
2434
2435       if (IsWin64) {
2436         // The XMM registers which might contain var arg parameters are shadowed
2437         // in their paired GPR.  So we only need to save the GPR to their home
2438         // slots.
2439         TotalNumIntRegs = 4;
2440         GPR64ArgRegs = GPR64ArgRegsWin64;
2441       } else {
2442         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2443         GPR64ArgRegs = GPR64ArgRegs64Bit;
2444
2445         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2446                                                 TotalNumXMMRegs);
2447       }
2448       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2449                                                        TotalNumIntRegs);
2450
2451       bool NoImplicitFloatOps = Fn->getAttributes().
2452         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2453       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2454              "SSE register cannot be used when SSE is disabled!");
2455       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2456                NoImplicitFloatOps) &&
2457              "SSE register cannot be used when SSE is disabled!");
2458       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2459           !Subtarget->hasSSE1())
2460         // Kernel mode asks for SSE to be disabled, so don't push them
2461         // on the stack.
2462         TotalNumXMMRegs = 0;
2463
2464       if (IsWin64) {
2465         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2466         // Get to the caller-allocated home save location.  Add 8 to account
2467         // for the return address.
2468         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2469         FuncInfo->setRegSaveFrameIndex(
2470           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2471         // Fixup to set vararg frame on shadow area (4 x i64).
2472         if (NumIntRegs < 4)
2473           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2474       } else {
2475         // For X86-64, if there are vararg parameters that are passed via
2476         // registers, then we must store them to their spots on the stack so
2477         // they may be loaded by deferencing the result of va_next.
2478         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2479         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2480         FuncInfo->setRegSaveFrameIndex(
2481           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2482                                false));
2483       }
2484
2485       // Store the integer parameter registers.
2486       SmallVector<SDValue, 8> MemOps;
2487       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2488                                         getPointerTy());
2489       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2490       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2491         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2492                                   DAG.getIntPtrConstant(Offset));
2493         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2494                                      &X86::GR64RegClass);
2495         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2496         SDValue Store =
2497           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2498                        MachinePointerInfo::getFixedStack(
2499                          FuncInfo->getRegSaveFrameIndex(), Offset),
2500                        false, false, 0);
2501         MemOps.push_back(Store);
2502         Offset += 8;
2503       }
2504
2505       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2506         // Now store the XMM (fp + vector) parameter registers.
2507         SmallVector<SDValue, 12> SaveXMMOps;
2508         SaveXMMOps.push_back(Chain);
2509
2510         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2511         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2512         SaveXMMOps.push_back(ALVal);
2513
2514         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2515                                FuncInfo->getRegSaveFrameIndex()));
2516         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2517                                FuncInfo->getVarArgsFPOffset()));
2518
2519         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2520           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2521                                        &X86::VR128RegClass);
2522           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2523           SaveXMMOps.push_back(Val);
2524         }
2525         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2526                                      MVT::Other, SaveXMMOps));
2527       }
2528
2529       if (!MemOps.empty())
2530         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2531     }
2532   }
2533
2534   // Some CCs need callee pop.
2535   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2536                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2537     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2538   } else {
2539     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2540     // If this is an sret function, the return should pop the hidden pointer.
2541     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2542         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2543         argsAreStructReturn(Ins) == StackStructReturn)
2544       FuncInfo->setBytesToPopOnReturn(4);
2545   }
2546
2547   if (!Is64Bit) {
2548     // RegSaveFrameIndex is X86-64 only.
2549     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2550     if (CallConv == CallingConv::X86_FastCall ||
2551         CallConv == CallingConv::X86_ThisCall)
2552       // fastcc functions can't have varargs.
2553       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2554   }
2555
2556   FuncInfo->setArgumentStackSize(StackSize);
2557
2558   return Chain;
2559 }
2560
2561 SDValue
2562 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2563                                     SDValue StackPtr, SDValue Arg,
2564                                     SDLoc dl, SelectionDAG &DAG,
2565                                     const CCValAssign &VA,
2566                                     ISD::ArgFlagsTy Flags) const {
2567   unsigned LocMemOffset = VA.getLocMemOffset();
2568   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2569   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2570   if (Flags.isByVal())
2571     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2572
2573   return DAG.getStore(Chain, dl, Arg, PtrOff,
2574                       MachinePointerInfo::getStack(LocMemOffset),
2575                       false, false, 0);
2576 }
2577
2578 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2579 /// optimization is performed and it is required.
2580 SDValue
2581 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2582                                            SDValue &OutRetAddr, SDValue Chain,
2583                                            bool IsTailCall, bool Is64Bit,
2584                                            int FPDiff, SDLoc dl) const {
2585   // Adjust the Return address stack slot.
2586   EVT VT = getPointerTy();
2587   OutRetAddr = getReturnAddressFrameIndex(DAG);
2588
2589   // Load the "old" Return address.
2590   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2591                            false, false, false, 0);
2592   return SDValue(OutRetAddr.getNode(), 1);
2593 }
2594
2595 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2596 /// optimization is performed and it is required (FPDiff!=0).
2597 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2598                                         SDValue Chain, SDValue RetAddrFrIdx,
2599                                         EVT PtrVT, unsigned SlotSize,
2600                                         int FPDiff, SDLoc dl) {
2601   // Store the return address to the appropriate stack slot.
2602   if (!FPDiff) return Chain;
2603   // Calculate the new stack slot for the return address.
2604   int NewReturnAddrFI =
2605     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2606                                          false);
2607   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2608   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2609                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2610                        false, false, 0);
2611   return Chain;
2612 }
2613
2614 SDValue
2615 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2616                              SmallVectorImpl<SDValue> &InVals) const {
2617   SelectionDAG &DAG                     = CLI.DAG;
2618   SDLoc &dl                             = CLI.DL;
2619   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2620   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2621   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2622   SDValue Chain                         = CLI.Chain;
2623   SDValue Callee                        = CLI.Callee;
2624   CallingConv::ID CallConv              = CLI.CallConv;
2625   bool &isTailCall                      = CLI.IsTailCall;
2626   bool isVarArg                         = CLI.IsVarArg;
2627
2628   MachineFunction &MF = DAG.getMachineFunction();
2629   bool Is64Bit        = Subtarget->is64Bit();
2630   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2631   StructReturnType SR = callIsStructReturn(Outs);
2632   bool IsSibcall      = false;
2633
2634   if (MF.getTarget().Options.DisableTailCalls)
2635     isTailCall = false;
2636
2637   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2638   if (IsMustTail) {
2639     // Force this to be a tail call.  The verifier rules are enough to ensure
2640     // that we can lower this successfully without moving the return address
2641     // around.
2642     isTailCall = true;
2643   } else if (isTailCall) {
2644     // Check if it's really possible to do a tail call.
2645     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2646                     isVarArg, SR != NotStructReturn,
2647                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2648                     Outs, OutVals, Ins, DAG);
2649
2650     // Sibcalls are automatically detected tailcalls which do not require
2651     // ABI changes.
2652     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2653       IsSibcall = true;
2654
2655     if (isTailCall)
2656       ++NumTailCalls;
2657   }
2658
2659   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2660          "Var args not supported with calling convention fastcc, ghc or hipe");
2661
2662   // Analyze operands of the call, assigning locations to each operand.
2663   SmallVector<CCValAssign, 16> ArgLocs;
2664   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2665
2666   // Allocate shadow area for Win64
2667   if (IsWin64)
2668     CCInfo.AllocateStack(32, 8);
2669
2670   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2671
2672   // Get a count of how many bytes are to be pushed on the stack.
2673   unsigned NumBytes = CCInfo.getNextStackOffset();
2674   if (IsSibcall)
2675     // This is a sibcall. The memory operands are available in caller's
2676     // own caller's stack.
2677     NumBytes = 0;
2678   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2679            IsTailCallConvention(CallConv))
2680     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2681
2682   int FPDiff = 0;
2683   if (isTailCall && !IsSibcall && !IsMustTail) {
2684     // Lower arguments at fp - stackoffset + fpdiff.
2685     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2686     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2687
2688     FPDiff = NumBytesCallerPushed - NumBytes;
2689
2690     // Set the delta of movement of the returnaddr stackslot.
2691     // But only set if delta is greater than previous delta.
2692     if (FPDiff < X86Info->getTCReturnAddrDelta())
2693       X86Info->setTCReturnAddrDelta(FPDiff);
2694   }
2695
2696   unsigned NumBytesToPush = NumBytes;
2697   unsigned NumBytesToPop = NumBytes;
2698
2699   // If we have an inalloca argument, all stack space has already been allocated
2700   // for us and be right at the top of the stack.  We don't support multiple
2701   // arguments passed in memory when using inalloca.
2702   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2703     NumBytesToPush = 0;
2704     if (!ArgLocs.back().isMemLoc())
2705       report_fatal_error("cannot use inalloca attribute on a register "
2706                          "parameter");
2707     if (ArgLocs.back().getLocMemOffset() != 0)
2708       report_fatal_error("any parameter with the inalloca attribute must be "
2709                          "the only memory argument");
2710   }
2711
2712   if (!IsSibcall)
2713     Chain = DAG.getCALLSEQ_START(
2714         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2715
2716   SDValue RetAddrFrIdx;
2717   // Load return address for tail calls.
2718   if (isTailCall && FPDiff)
2719     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2720                                     Is64Bit, FPDiff, dl);
2721
2722   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2723   SmallVector<SDValue, 8> MemOpChains;
2724   SDValue StackPtr;
2725
2726   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2727   // of tail call optimization arguments are handle later.
2728   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2729       DAG.getSubtarget().getRegisterInfo());
2730   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2731     // Skip inalloca arguments, they have already been written.
2732     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2733     if (Flags.isInAlloca())
2734       continue;
2735
2736     CCValAssign &VA = ArgLocs[i];
2737     EVT RegVT = VA.getLocVT();
2738     SDValue Arg = OutVals[i];
2739     bool isByVal = Flags.isByVal();
2740
2741     // Promote the value if needed.
2742     switch (VA.getLocInfo()) {
2743     default: llvm_unreachable("Unknown loc info!");
2744     case CCValAssign::Full: break;
2745     case CCValAssign::SExt:
2746       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2747       break;
2748     case CCValAssign::ZExt:
2749       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2750       break;
2751     case CCValAssign::AExt:
2752       if (RegVT.is128BitVector()) {
2753         // Special case: passing MMX values in XMM registers.
2754         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2755         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2756         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2757       } else
2758         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2759       break;
2760     case CCValAssign::BCvt:
2761       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2762       break;
2763     case CCValAssign::Indirect: {
2764       // Store the argument.
2765       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2766       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2767       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2768                            MachinePointerInfo::getFixedStack(FI),
2769                            false, false, 0);
2770       Arg = SpillSlot;
2771       break;
2772     }
2773     }
2774
2775     if (VA.isRegLoc()) {
2776       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2777       if (isVarArg && IsWin64) {
2778         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2779         // shadow reg if callee is a varargs function.
2780         unsigned ShadowReg = 0;
2781         switch (VA.getLocReg()) {
2782         case X86::XMM0: ShadowReg = X86::RCX; break;
2783         case X86::XMM1: ShadowReg = X86::RDX; break;
2784         case X86::XMM2: ShadowReg = X86::R8; break;
2785         case X86::XMM3: ShadowReg = X86::R9; break;
2786         }
2787         if (ShadowReg)
2788           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2789       }
2790     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2791       assert(VA.isMemLoc());
2792       if (!StackPtr.getNode())
2793         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2794                                       getPointerTy());
2795       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2796                                              dl, DAG, VA, Flags));
2797     }
2798   }
2799
2800   if (!MemOpChains.empty())
2801     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2802
2803   if (Subtarget->isPICStyleGOT()) {
2804     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2805     // GOT pointer.
2806     if (!isTailCall) {
2807       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2808                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2809     } else {
2810       // If we are tail calling and generating PIC/GOT style code load the
2811       // address of the callee into ECX. The value in ecx is used as target of
2812       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2813       // for tail calls on PIC/GOT architectures. Normally we would just put the
2814       // address of GOT into ebx and then call target@PLT. But for tail calls
2815       // ebx would be restored (since ebx is callee saved) before jumping to the
2816       // target@PLT.
2817
2818       // Note: The actual moving to ECX is done further down.
2819       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2820       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2821           !G->getGlobal()->hasProtectedVisibility())
2822         Callee = LowerGlobalAddress(Callee, DAG);
2823       else if (isa<ExternalSymbolSDNode>(Callee))
2824         Callee = LowerExternalSymbol(Callee, DAG);
2825     }
2826   }
2827
2828   if (Is64Bit && isVarArg && !IsWin64) {
2829     // From AMD64 ABI document:
2830     // For calls that may call functions that use varargs or stdargs
2831     // (prototype-less calls or calls to functions containing ellipsis (...) in
2832     // the declaration) %al is used as hidden argument to specify the number
2833     // of SSE registers used. The contents of %al do not need to match exactly
2834     // the number of registers, but must be an ubound on the number of SSE
2835     // registers used and is in the range 0 - 8 inclusive.
2836
2837     // Count the number of XMM registers allocated.
2838     static const MCPhysReg XMMArgRegs[] = {
2839       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2840       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2841     };
2842     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2843     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2844            && "SSE registers cannot be used when SSE is disabled");
2845
2846     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2847                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2848   }
2849
2850   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2851   // don't need this because the eligibility check rejects calls that require
2852   // shuffling arguments passed in memory.
2853   if (!IsSibcall && isTailCall) {
2854     // Force all the incoming stack arguments to be loaded from the stack
2855     // before any new outgoing arguments are stored to the stack, because the
2856     // outgoing stack slots may alias the incoming argument stack slots, and
2857     // the alias isn't otherwise explicit. This is slightly more conservative
2858     // than necessary, because it means that each store effectively depends
2859     // on every argument instead of just those arguments it would clobber.
2860     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2861
2862     SmallVector<SDValue, 8> MemOpChains2;
2863     SDValue FIN;
2864     int FI = 0;
2865     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2866       CCValAssign &VA = ArgLocs[i];
2867       if (VA.isRegLoc())
2868         continue;
2869       assert(VA.isMemLoc());
2870       SDValue Arg = OutVals[i];
2871       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2872       // Skip inalloca arguments.  They don't require any work.
2873       if (Flags.isInAlloca())
2874         continue;
2875       // Create frame index.
2876       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2877       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2878       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2879       FIN = DAG.getFrameIndex(FI, getPointerTy());
2880
2881       if (Flags.isByVal()) {
2882         // Copy relative to framepointer.
2883         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2884         if (!StackPtr.getNode())
2885           StackPtr = DAG.getCopyFromReg(Chain, dl,
2886                                         RegInfo->getStackRegister(),
2887                                         getPointerTy());
2888         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2889
2890         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2891                                                          ArgChain,
2892                                                          Flags, DAG, dl));
2893       } else {
2894         // Store relative to framepointer.
2895         MemOpChains2.push_back(
2896           DAG.getStore(ArgChain, dl, Arg, FIN,
2897                        MachinePointerInfo::getFixedStack(FI),
2898                        false, false, 0));
2899       }
2900     }
2901
2902     if (!MemOpChains2.empty())
2903       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2904
2905     // Store the return address to the appropriate stack slot.
2906     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2907                                      getPointerTy(), RegInfo->getSlotSize(),
2908                                      FPDiff, dl);
2909   }
2910
2911   // Build a sequence of copy-to-reg nodes chained together with token chain
2912   // and flag operands which copy the outgoing args into registers.
2913   SDValue InFlag;
2914   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2915     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2916                              RegsToPass[i].second, InFlag);
2917     InFlag = Chain.getValue(1);
2918   }
2919
2920   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2921     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2922     // In the 64-bit large code model, we have to make all calls
2923     // through a register, since the call instruction's 32-bit
2924     // pc-relative offset may not be large enough to hold the whole
2925     // address.
2926   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2927     // If the callee is a GlobalAddress node (quite common, every direct call
2928     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2929     // it.
2930
2931     // We should use extra load for direct calls to dllimported functions in
2932     // non-JIT mode.
2933     const GlobalValue *GV = G->getGlobal();
2934     if (!GV->hasDLLImportStorageClass()) {
2935       unsigned char OpFlags = 0;
2936       bool ExtraLoad = false;
2937       unsigned WrapperKind = ISD::DELETED_NODE;
2938
2939       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2940       // external symbols most go through the PLT in PIC mode.  If the symbol
2941       // has hidden or protected visibility, or if it is static or local, then
2942       // we don't need to use the PLT - we can directly call it.
2943       if (Subtarget->isTargetELF() &&
2944           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2945           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2946         OpFlags = X86II::MO_PLT;
2947       } else if (Subtarget->isPICStyleStubAny() &&
2948                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2949                  (!Subtarget->getTargetTriple().isMacOSX() ||
2950                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2951         // PC-relative references to external symbols should go through $stub,
2952         // unless we're building with the leopard linker or later, which
2953         // automatically synthesizes these stubs.
2954         OpFlags = X86II::MO_DARWIN_STUB;
2955       } else if (Subtarget->isPICStyleRIPRel() &&
2956                  isa<Function>(GV) &&
2957                  cast<Function>(GV)->getAttributes().
2958                    hasAttribute(AttributeSet::FunctionIndex,
2959                                 Attribute::NonLazyBind)) {
2960         // If the function is marked as non-lazy, generate an indirect call
2961         // which loads from the GOT directly. This avoids runtime overhead
2962         // at the cost of eager binding (and one extra byte of encoding).
2963         OpFlags = X86II::MO_GOTPCREL;
2964         WrapperKind = X86ISD::WrapperRIP;
2965         ExtraLoad = true;
2966       }
2967
2968       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2969                                           G->getOffset(), OpFlags);
2970
2971       // Add a wrapper if needed.
2972       if (WrapperKind != ISD::DELETED_NODE)
2973         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2974       // Add extra indirection if needed.
2975       if (ExtraLoad)
2976         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2977                              MachinePointerInfo::getGOT(),
2978                              false, false, false, 0);
2979     }
2980   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2981     unsigned char OpFlags = 0;
2982
2983     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2984     // external symbols should go through the PLT.
2985     if (Subtarget->isTargetELF() &&
2986         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2987       OpFlags = X86II::MO_PLT;
2988     } else if (Subtarget->isPICStyleStubAny() &&
2989                (!Subtarget->getTargetTriple().isMacOSX() ||
2990                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2991       // PC-relative references to external symbols should go through $stub,
2992       // unless we're building with the leopard linker or later, which
2993       // automatically synthesizes these stubs.
2994       OpFlags = X86II::MO_DARWIN_STUB;
2995     }
2996
2997     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2998                                          OpFlags);
2999   }
3000
3001   // Returns a chain & a flag for retval copy to use.
3002   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3003   SmallVector<SDValue, 8> Ops;
3004
3005   if (!IsSibcall && isTailCall) {
3006     Chain = DAG.getCALLSEQ_END(Chain,
3007                                DAG.getIntPtrConstant(NumBytesToPop, true),
3008                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3009     InFlag = Chain.getValue(1);
3010   }
3011
3012   Ops.push_back(Chain);
3013   Ops.push_back(Callee);
3014
3015   if (isTailCall)
3016     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3017
3018   // Add argument registers to the end of the list so that they are known live
3019   // into the call.
3020   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3021     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3022                                   RegsToPass[i].second.getValueType()));
3023
3024   // Add a register mask operand representing the call-preserved registers.
3025   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3026   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3027   assert(Mask && "Missing call preserved mask for calling convention");
3028   Ops.push_back(DAG.getRegisterMask(Mask));
3029
3030   if (InFlag.getNode())
3031     Ops.push_back(InFlag);
3032
3033   if (isTailCall) {
3034     // We used to do:
3035     //// If this is the first return lowered for this function, add the regs
3036     //// to the liveout set for the function.
3037     // This isn't right, although it's probably harmless on x86; liveouts
3038     // should be computed from returns not tail calls.  Consider a void
3039     // function making a tail call to a function returning int.
3040     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3041   }
3042
3043   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3044   InFlag = Chain.getValue(1);
3045
3046   // Create the CALLSEQ_END node.
3047   unsigned NumBytesForCalleeToPop;
3048   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3049                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3050     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3051   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3052            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3053            SR == StackStructReturn)
3054     // If this is a call to a struct-return function, the callee
3055     // pops the hidden struct pointer, so we have to push it back.
3056     // This is common for Darwin/X86, Linux & Mingw32 targets.
3057     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3058     NumBytesForCalleeToPop = 4;
3059   else
3060     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3061
3062   // Returns a flag for retval copy to use.
3063   if (!IsSibcall) {
3064     Chain = DAG.getCALLSEQ_END(Chain,
3065                                DAG.getIntPtrConstant(NumBytesToPop, true),
3066                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3067                                                      true),
3068                                InFlag, dl);
3069     InFlag = Chain.getValue(1);
3070   }
3071
3072   // Handle result values, copying them out of physregs into vregs that we
3073   // return.
3074   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3075                          Ins, dl, DAG, InVals);
3076 }
3077
3078 //===----------------------------------------------------------------------===//
3079 //                Fast Calling Convention (tail call) implementation
3080 //===----------------------------------------------------------------------===//
3081
3082 //  Like std call, callee cleans arguments, convention except that ECX is
3083 //  reserved for storing the tail called function address. Only 2 registers are
3084 //  free for argument passing (inreg). Tail call optimization is performed
3085 //  provided:
3086 //                * tailcallopt is enabled
3087 //                * caller/callee are fastcc
3088 //  On X86_64 architecture with GOT-style position independent code only local
3089 //  (within module) calls are supported at the moment.
3090 //  To keep the stack aligned according to platform abi the function
3091 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3092 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3093 //  If a tail called function callee has more arguments than the caller the
3094 //  caller needs to make sure that there is room to move the RETADDR to. This is
3095 //  achieved by reserving an area the size of the argument delta right after the
3096 //  original RETADDR, but before the saved framepointer or the spilled registers
3097 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3098 //  stack layout:
3099 //    arg1
3100 //    arg2
3101 //    RETADDR
3102 //    [ new RETADDR
3103 //      move area ]
3104 //    (possible EBP)
3105 //    ESI
3106 //    EDI
3107 //    local1 ..
3108
3109 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3110 /// for a 16 byte align requirement.
3111 unsigned
3112 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3113                                                SelectionDAG& DAG) const {
3114   MachineFunction &MF = DAG.getMachineFunction();
3115   const TargetMachine &TM = MF.getTarget();
3116   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3117       TM.getSubtargetImpl()->getRegisterInfo());
3118   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3119   unsigned StackAlignment = TFI.getStackAlignment();
3120   uint64_t AlignMask = StackAlignment - 1;
3121   int64_t Offset = StackSize;
3122   unsigned SlotSize = RegInfo->getSlotSize();
3123   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3124     // Number smaller than 12 so just add the difference.
3125     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3126   } else {
3127     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3128     Offset = ((~AlignMask) & Offset) + StackAlignment +
3129       (StackAlignment-SlotSize);
3130   }
3131   return Offset;
3132 }
3133
3134 /// MatchingStackOffset - Return true if the given stack call argument is
3135 /// already available in the same position (relatively) of the caller's
3136 /// incoming argument stack.
3137 static
3138 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3139                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3140                          const X86InstrInfo *TII) {
3141   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3142   int FI = INT_MAX;
3143   if (Arg.getOpcode() == ISD::CopyFromReg) {
3144     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3145     if (!TargetRegisterInfo::isVirtualRegister(VR))
3146       return false;
3147     MachineInstr *Def = MRI->getVRegDef(VR);
3148     if (!Def)
3149       return false;
3150     if (!Flags.isByVal()) {
3151       if (!TII->isLoadFromStackSlot(Def, FI))
3152         return false;
3153     } else {
3154       unsigned Opcode = Def->getOpcode();
3155       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3156           Def->getOperand(1).isFI()) {
3157         FI = Def->getOperand(1).getIndex();
3158         Bytes = Flags.getByValSize();
3159       } else
3160         return false;
3161     }
3162   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3163     if (Flags.isByVal())
3164       // ByVal argument is passed in as a pointer but it's now being
3165       // dereferenced. e.g.
3166       // define @foo(%struct.X* %A) {
3167       //   tail call @bar(%struct.X* byval %A)
3168       // }
3169       return false;
3170     SDValue Ptr = Ld->getBasePtr();
3171     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3172     if (!FINode)
3173       return false;
3174     FI = FINode->getIndex();
3175   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3176     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3177     FI = FINode->getIndex();
3178     Bytes = Flags.getByValSize();
3179   } else
3180     return false;
3181
3182   assert(FI != INT_MAX);
3183   if (!MFI->isFixedObjectIndex(FI))
3184     return false;
3185   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3186 }
3187
3188 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3189 /// for tail call optimization. Targets which want to do tail call
3190 /// optimization should implement this function.
3191 bool
3192 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3193                                                      CallingConv::ID CalleeCC,
3194                                                      bool isVarArg,
3195                                                      bool isCalleeStructRet,
3196                                                      bool isCallerStructRet,
3197                                                      Type *RetTy,
3198                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3199                                     const SmallVectorImpl<SDValue> &OutVals,
3200                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3201                                                      SelectionDAG &DAG) const {
3202   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3203     return false;
3204
3205   // If -tailcallopt is specified, make fastcc functions tail-callable.
3206   const MachineFunction &MF = DAG.getMachineFunction();
3207   const Function *CallerF = MF.getFunction();
3208
3209   // If the function return type is x86_fp80 and the callee return type is not,
3210   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3211   // perform a tailcall optimization here.
3212   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3213     return false;
3214
3215   CallingConv::ID CallerCC = CallerF->getCallingConv();
3216   bool CCMatch = CallerCC == CalleeCC;
3217   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3218   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3219
3220   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3221     if (IsTailCallConvention(CalleeCC) && CCMatch)
3222       return true;
3223     return false;
3224   }
3225
3226   // Look for obvious safe cases to perform tail call optimization that do not
3227   // require ABI changes. This is what gcc calls sibcall.
3228
3229   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3230   // emit a special epilogue.
3231   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3232       DAG.getSubtarget().getRegisterInfo());
3233   if (RegInfo->needsStackRealignment(MF))
3234     return false;
3235
3236   // Also avoid sibcall optimization if either caller or callee uses struct
3237   // return semantics.
3238   if (isCalleeStructRet || isCallerStructRet)
3239     return false;
3240
3241   // An stdcall/thiscall caller is expected to clean up its arguments; the
3242   // callee isn't going to do that.
3243   // FIXME: this is more restrictive than needed. We could produce a tailcall
3244   // when the stack adjustment matches. For example, with a thiscall that takes
3245   // only one argument.
3246   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3247                    CallerCC == CallingConv::X86_ThisCall))
3248     return false;
3249
3250   // Do not sibcall optimize vararg calls unless all arguments are passed via
3251   // registers.
3252   if (isVarArg && !Outs.empty()) {
3253
3254     // Optimizing for varargs on Win64 is unlikely to be safe without
3255     // additional testing.
3256     if (IsCalleeWin64 || IsCallerWin64)
3257       return false;
3258
3259     SmallVector<CCValAssign, 16> ArgLocs;
3260     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3261                    *DAG.getContext());
3262
3263     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3264     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3265       if (!ArgLocs[i].isRegLoc())
3266         return false;
3267   }
3268
3269   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3270   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3271   // this into a sibcall.
3272   bool Unused = false;
3273   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3274     if (!Ins[i].Used) {
3275       Unused = true;
3276       break;
3277     }
3278   }
3279   if (Unused) {
3280     SmallVector<CCValAssign, 16> RVLocs;
3281     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3282                    *DAG.getContext());
3283     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3284     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3285       CCValAssign &VA = RVLocs[i];
3286       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3287         return false;
3288     }
3289   }
3290
3291   // If the calling conventions do not match, then we'd better make sure the
3292   // results are returned in the same way as what the caller expects.
3293   if (!CCMatch) {
3294     SmallVector<CCValAssign, 16> RVLocs1;
3295     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3296                     *DAG.getContext());
3297     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3298
3299     SmallVector<CCValAssign, 16> RVLocs2;
3300     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3301                     *DAG.getContext());
3302     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3303
3304     if (RVLocs1.size() != RVLocs2.size())
3305       return false;
3306     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3307       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3308         return false;
3309       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3310         return false;
3311       if (RVLocs1[i].isRegLoc()) {
3312         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3313           return false;
3314       } else {
3315         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3316           return false;
3317       }
3318     }
3319   }
3320
3321   // If the callee takes no arguments then go on to check the results of the
3322   // call.
3323   if (!Outs.empty()) {
3324     // Check if stack adjustment is needed. For now, do not do this if any
3325     // argument is passed on the stack.
3326     SmallVector<CCValAssign, 16> ArgLocs;
3327     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3328                    *DAG.getContext());
3329
3330     // Allocate shadow area for Win64
3331     if (IsCalleeWin64)
3332       CCInfo.AllocateStack(32, 8);
3333
3334     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3335     if (CCInfo.getNextStackOffset()) {
3336       MachineFunction &MF = DAG.getMachineFunction();
3337       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3338         return false;
3339
3340       // Check if the arguments are already laid out in the right way as
3341       // the caller's fixed stack objects.
3342       MachineFrameInfo *MFI = MF.getFrameInfo();
3343       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3344       const X86InstrInfo *TII =
3345           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3346       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3347         CCValAssign &VA = ArgLocs[i];
3348         SDValue Arg = OutVals[i];
3349         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3350         if (VA.getLocInfo() == CCValAssign::Indirect)
3351           return false;
3352         if (!VA.isRegLoc()) {
3353           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3354                                    MFI, MRI, TII))
3355             return false;
3356         }
3357       }
3358     }
3359
3360     // If the tailcall address may be in a register, then make sure it's
3361     // possible to register allocate for it. In 32-bit, the call address can
3362     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3363     // callee-saved registers are restored. These happen to be the same
3364     // registers used to pass 'inreg' arguments so watch out for those.
3365     if (!Subtarget->is64Bit() &&
3366         ((!isa<GlobalAddressSDNode>(Callee) &&
3367           !isa<ExternalSymbolSDNode>(Callee)) ||
3368          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3369       unsigned NumInRegs = 0;
3370       // In PIC we need an extra register to formulate the address computation
3371       // for the callee.
3372       unsigned MaxInRegs =
3373         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3374
3375       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3376         CCValAssign &VA = ArgLocs[i];
3377         if (!VA.isRegLoc())
3378           continue;
3379         unsigned Reg = VA.getLocReg();
3380         switch (Reg) {
3381         default: break;
3382         case X86::EAX: case X86::EDX: case X86::ECX:
3383           if (++NumInRegs == MaxInRegs)
3384             return false;
3385           break;
3386         }
3387       }
3388     }
3389   }
3390
3391   return true;
3392 }
3393
3394 FastISel *
3395 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3396                                   const TargetLibraryInfo *libInfo) const {
3397   return X86::createFastISel(funcInfo, libInfo);
3398 }
3399
3400 //===----------------------------------------------------------------------===//
3401 //                           Other Lowering Hooks
3402 //===----------------------------------------------------------------------===//
3403
3404 static bool MayFoldLoad(SDValue Op) {
3405   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3406 }
3407
3408 static bool MayFoldIntoStore(SDValue Op) {
3409   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3410 }
3411
3412 static bool isTargetShuffle(unsigned Opcode) {
3413   switch(Opcode) {
3414   default: return false;
3415   case X86ISD::PSHUFB:
3416   case X86ISD::PSHUFD:
3417   case X86ISD::PSHUFHW:
3418   case X86ISD::PSHUFLW:
3419   case X86ISD::SHUFP:
3420   case X86ISD::PALIGNR:
3421   case X86ISD::MOVLHPS:
3422   case X86ISD::MOVLHPD:
3423   case X86ISD::MOVHLPS:
3424   case X86ISD::MOVLPS:
3425   case X86ISD::MOVLPD:
3426   case X86ISD::MOVSHDUP:
3427   case X86ISD::MOVSLDUP:
3428   case X86ISD::MOVDDUP:
3429   case X86ISD::MOVSS:
3430   case X86ISD::MOVSD:
3431   case X86ISD::UNPCKL:
3432   case X86ISD::UNPCKH:
3433   case X86ISD::VPERMILP:
3434   case X86ISD::VPERM2X128:
3435   case X86ISD::VPERMI:
3436     return true;
3437   }
3438 }
3439
3440 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3441                                     SDValue V1, SelectionDAG &DAG) {
3442   switch(Opc) {
3443   default: llvm_unreachable("Unknown x86 shuffle node");
3444   case X86ISD::MOVSHDUP:
3445   case X86ISD::MOVSLDUP:
3446   case X86ISD::MOVDDUP:
3447     return DAG.getNode(Opc, dl, VT, V1);
3448   }
3449 }
3450
3451 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3452                                     SDValue V1, unsigned TargetMask,
3453                                     SelectionDAG &DAG) {
3454   switch(Opc) {
3455   default: llvm_unreachable("Unknown x86 shuffle node");
3456   case X86ISD::PSHUFD:
3457   case X86ISD::PSHUFHW:
3458   case X86ISD::PSHUFLW:
3459   case X86ISD::VPERMILP:
3460   case X86ISD::VPERMI:
3461     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3462   }
3463 }
3464
3465 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3466                                     SDValue V1, SDValue V2, unsigned TargetMask,
3467                                     SelectionDAG &DAG) {
3468   switch(Opc) {
3469   default: llvm_unreachable("Unknown x86 shuffle node");
3470   case X86ISD::PALIGNR:
3471   case X86ISD::VALIGN:
3472   case X86ISD::SHUFP:
3473   case X86ISD::VPERM2X128:
3474     return DAG.getNode(Opc, dl, VT, V1, V2,
3475                        DAG.getConstant(TargetMask, MVT::i8));
3476   }
3477 }
3478
3479 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3480                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3481   switch(Opc) {
3482   default: llvm_unreachable("Unknown x86 shuffle node");
3483   case X86ISD::MOVLHPS:
3484   case X86ISD::MOVLHPD:
3485   case X86ISD::MOVHLPS:
3486   case X86ISD::MOVLPS:
3487   case X86ISD::MOVLPD:
3488   case X86ISD::MOVSS:
3489   case X86ISD::MOVSD:
3490   case X86ISD::UNPCKL:
3491   case X86ISD::UNPCKH:
3492     return DAG.getNode(Opc, dl, VT, V1, V2);
3493   }
3494 }
3495
3496 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3497   MachineFunction &MF = DAG.getMachineFunction();
3498   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3499       DAG.getSubtarget().getRegisterInfo());
3500   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3501   int ReturnAddrIndex = FuncInfo->getRAIndex();
3502
3503   if (ReturnAddrIndex == 0) {
3504     // Set up a frame object for the return address.
3505     unsigned SlotSize = RegInfo->getSlotSize();
3506     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3507                                                            -(int64_t)SlotSize,
3508                                                            false);
3509     FuncInfo->setRAIndex(ReturnAddrIndex);
3510   }
3511
3512   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3513 }
3514
3515 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3516                                        bool hasSymbolicDisplacement) {
3517   // Offset should fit into 32 bit immediate field.
3518   if (!isInt<32>(Offset))
3519     return false;
3520
3521   // If we don't have a symbolic displacement - we don't have any extra
3522   // restrictions.
3523   if (!hasSymbolicDisplacement)
3524     return true;
3525
3526   // FIXME: Some tweaks might be needed for medium code model.
3527   if (M != CodeModel::Small && M != CodeModel::Kernel)
3528     return false;
3529
3530   // For small code model we assume that latest object is 16MB before end of 31
3531   // bits boundary. We may also accept pretty large negative constants knowing
3532   // that all objects are in the positive half of address space.
3533   if (M == CodeModel::Small && Offset < 16*1024*1024)
3534     return true;
3535
3536   // For kernel code model we know that all object resist in the negative half
3537   // of 32bits address space. We may not accept negative offsets, since they may
3538   // be just off and we may accept pretty large positive ones.
3539   if (M == CodeModel::Kernel && Offset > 0)
3540     return true;
3541
3542   return false;
3543 }
3544
3545 /// isCalleePop - Determines whether the callee is required to pop its
3546 /// own arguments. Callee pop is necessary to support tail calls.
3547 bool X86::isCalleePop(CallingConv::ID CallingConv,
3548                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3549   if (IsVarArg)
3550     return false;
3551
3552   switch (CallingConv) {
3553   default:
3554     return false;
3555   case CallingConv::X86_StdCall:
3556     return !is64Bit;
3557   case CallingConv::X86_FastCall:
3558     return !is64Bit;
3559   case CallingConv::X86_ThisCall:
3560     return !is64Bit;
3561   case CallingConv::Fast:
3562     return TailCallOpt;
3563   case CallingConv::GHC:
3564     return TailCallOpt;
3565   case CallingConv::HiPE:
3566     return TailCallOpt;
3567   }
3568 }
3569
3570 /// \brief Return true if the condition is an unsigned comparison operation.
3571 static bool isX86CCUnsigned(unsigned X86CC) {
3572   switch (X86CC) {
3573   default: llvm_unreachable("Invalid integer condition!");
3574   case X86::COND_E:     return true;
3575   case X86::COND_G:     return false;
3576   case X86::COND_GE:    return false;
3577   case X86::COND_L:     return false;
3578   case X86::COND_LE:    return false;
3579   case X86::COND_NE:    return true;
3580   case X86::COND_B:     return true;
3581   case X86::COND_A:     return true;
3582   case X86::COND_BE:    return true;
3583   case X86::COND_AE:    return true;
3584   }
3585   llvm_unreachable("covered switch fell through?!");
3586 }
3587
3588 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3589 /// specific condition code, returning the condition code and the LHS/RHS of the
3590 /// comparison to make.
3591 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3592                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3593   if (!isFP) {
3594     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3595       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3596         // X > -1   -> X == 0, jump !sign.
3597         RHS = DAG.getConstant(0, RHS.getValueType());
3598         return X86::COND_NS;
3599       }
3600       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3601         // X < 0   -> X == 0, jump on sign.
3602         return X86::COND_S;
3603       }
3604       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3605         // X < 1   -> X <= 0
3606         RHS = DAG.getConstant(0, RHS.getValueType());
3607         return X86::COND_LE;
3608       }
3609     }
3610
3611     switch (SetCCOpcode) {
3612     default: llvm_unreachable("Invalid integer condition!");
3613     case ISD::SETEQ:  return X86::COND_E;
3614     case ISD::SETGT:  return X86::COND_G;
3615     case ISD::SETGE:  return X86::COND_GE;
3616     case ISD::SETLT:  return X86::COND_L;
3617     case ISD::SETLE:  return X86::COND_LE;
3618     case ISD::SETNE:  return X86::COND_NE;
3619     case ISD::SETULT: return X86::COND_B;
3620     case ISD::SETUGT: return X86::COND_A;
3621     case ISD::SETULE: return X86::COND_BE;
3622     case ISD::SETUGE: return X86::COND_AE;
3623     }
3624   }
3625
3626   // First determine if it is required or is profitable to flip the operands.
3627
3628   // If LHS is a foldable load, but RHS is not, flip the condition.
3629   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3630       !ISD::isNON_EXTLoad(RHS.getNode())) {
3631     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3632     std::swap(LHS, RHS);
3633   }
3634
3635   switch (SetCCOpcode) {
3636   default: break;
3637   case ISD::SETOLT:
3638   case ISD::SETOLE:
3639   case ISD::SETUGT:
3640   case ISD::SETUGE:
3641     std::swap(LHS, RHS);
3642     break;
3643   }
3644
3645   // On a floating point condition, the flags are set as follows:
3646   // ZF  PF  CF   op
3647   //  0 | 0 | 0 | X > Y
3648   //  0 | 0 | 1 | X < Y
3649   //  1 | 0 | 0 | X == Y
3650   //  1 | 1 | 1 | unordered
3651   switch (SetCCOpcode) {
3652   default: llvm_unreachable("Condcode should be pre-legalized away");
3653   case ISD::SETUEQ:
3654   case ISD::SETEQ:   return X86::COND_E;
3655   case ISD::SETOLT:              // flipped
3656   case ISD::SETOGT:
3657   case ISD::SETGT:   return X86::COND_A;
3658   case ISD::SETOLE:              // flipped
3659   case ISD::SETOGE:
3660   case ISD::SETGE:   return X86::COND_AE;
3661   case ISD::SETUGT:              // flipped
3662   case ISD::SETULT:
3663   case ISD::SETLT:   return X86::COND_B;
3664   case ISD::SETUGE:              // flipped
3665   case ISD::SETULE:
3666   case ISD::SETLE:   return X86::COND_BE;
3667   case ISD::SETONE:
3668   case ISD::SETNE:   return X86::COND_NE;
3669   case ISD::SETUO:   return X86::COND_P;
3670   case ISD::SETO:    return X86::COND_NP;
3671   case ISD::SETOEQ:
3672   case ISD::SETUNE:  return X86::COND_INVALID;
3673   }
3674 }
3675
3676 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3677 /// code. Current x86 isa includes the following FP cmov instructions:
3678 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3679 static bool hasFPCMov(unsigned X86CC) {
3680   switch (X86CC) {
3681   default:
3682     return false;
3683   case X86::COND_B:
3684   case X86::COND_BE:
3685   case X86::COND_E:
3686   case X86::COND_P:
3687   case X86::COND_A:
3688   case X86::COND_AE:
3689   case X86::COND_NE:
3690   case X86::COND_NP:
3691     return true;
3692   }
3693 }
3694
3695 /// isFPImmLegal - Returns true if the target can instruction select the
3696 /// specified FP immediate natively. If false, the legalizer will
3697 /// materialize the FP immediate as a load from a constant pool.
3698 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3699   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3700     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3701       return true;
3702   }
3703   return false;
3704 }
3705
3706 /// \brief Returns true if it is beneficial to convert a load of a constant
3707 /// to just the constant itself.
3708 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3709                                                           Type *Ty) const {
3710   assert(Ty->isIntegerTy());
3711
3712   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3713   if (BitSize == 0 || BitSize > 64)
3714     return false;
3715   return true;
3716 }
3717
3718 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3719 /// the specified range (L, H].
3720 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3721   return (Val < 0) || (Val >= Low && Val < Hi);
3722 }
3723
3724 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3725 /// specified value.
3726 static bool isUndefOrEqual(int Val, int CmpVal) {
3727   return (Val < 0 || Val == CmpVal);
3728 }
3729
3730 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3731 /// from position Pos and ending in Pos+Size, falls within the specified
3732 /// sequential range (L, L+Pos]. or is undef.
3733 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3734                                        unsigned Pos, unsigned Size, int Low) {
3735   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3736     if (!isUndefOrEqual(Mask[i], Low))
3737       return false;
3738   return true;
3739 }
3740
3741 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3742 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3743 /// the second operand.
3744 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3745   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3746     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3747   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3748     return (Mask[0] < 2 && Mask[1] < 2);
3749   return false;
3750 }
3751
3752 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3753 /// is suitable for input to PSHUFHW.
3754 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3755   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3756     return false;
3757
3758   // Lower quadword copied in order or undef.
3759   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3760     return false;
3761
3762   // Upper quadword shuffled.
3763   for (unsigned i = 4; i != 8; ++i)
3764     if (!isUndefOrInRange(Mask[i], 4, 8))
3765       return false;
3766
3767   if (VT == MVT::v16i16) {
3768     // Lower quadword copied in order or undef.
3769     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3770       return false;
3771
3772     // Upper quadword shuffled.
3773     for (unsigned i = 12; i != 16; ++i)
3774       if (!isUndefOrInRange(Mask[i], 12, 16))
3775         return false;
3776   }
3777
3778   return true;
3779 }
3780
3781 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3782 /// is suitable for input to PSHUFLW.
3783 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3784   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3785     return false;
3786
3787   // Upper quadword copied in order.
3788   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3789     return false;
3790
3791   // Lower quadword shuffled.
3792   for (unsigned i = 0; i != 4; ++i)
3793     if (!isUndefOrInRange(Mask[i], 0, 4))
3794       return false;
3795
3796   if (VT == MVT::v16i16) {
3797     // Upper quadword copied in order.
3798     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3799       return false;
3800
3801     // Lower quadword shuffled.
3802     for (unsigned i = 8; i != 12; ++i)
3803       if (!isUndefOrInRange(Mask[i], 8, 12))
3804         return false;
3805   }
3806
3807   return true;
3808 }
3809
3810 /// \brief Return true if the mask specifies a shuffle of elements that is
3811 /// suitable for input to intralane (palignr) or interlane (valign) vector
3812 /// right-shift.
3813 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3814   unsigned NumElts = VT.getVectorNumElements();
3815   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3816   unsigned NumLaneElts = NumElts/NumLanes;
3817
3818   // Do not handle 64-bit element shuffles with palignr.
3819   if (NumLaneElts == 2)
3820     return false;
3821
3822   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3823     unsigned i;
3824     for (i = 0; i != NumLaneElts; ++i) {
3825       if (Mask[i+l] >= 0)
3826         break;
3827     }
3828
3829     // Lane is all undef, go to next lane
3830     if (i == NumLaneElts)
3831       continue;
3832
3833     int Start = Mask[i+l];
3834
3835     // Make sure its in this lane in one of the sources
3836     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3837         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3838       return false;
3839
3840     // If not lane 0, then we must match lane 0
3841     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3842       return false;
3843
3844     // Correct second source to be contiguous with first source
3845     if (Start >= (int)NumElts)
3846       Start -= NumElts - NumLaneElts;
3847
3848     // Make sure we're shifting in the right direction.
3849     if (Start <= (int)(i+l))
3850       return false;
3851
3852     Start -= i;
3853
3854     // Check the rest of the elements to see if they are consecutive.
3855     for (++i; i != NumLaneElts; ++i) {
3856       int Idx = Mask[i+l];
3857
3858       // Make sure its in this lane
3859       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3860           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3861         return false;
3862
3863       // If not lane 0, then we must match lane 0
3864       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3865         return false;
3866
3867       if (Idx >= (int)NumElts)
3868         Idx -= NumElts - NumLaneElts;
3869
3870       if (!isUndefOrEqual(Idx, Start+i))
3871         return false;
3872
3873     }
3874   }
3875
3876   return true;
3877 }
3878
3879 /// \brief Return true if the node specifies a shuffle of elements that is
3880 /// suitable for input to PALIGNR.
3881 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3882                           const X86Subtarget *Subtarget) {
3883   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3884       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
3885       VT.is512BitVector())
3886     // FIXME: Add AVX512BW.
3887     return false;
3888
3889   return isAlignrMask(Mask, VT, false);
3890 }
3891
3892 /// \brief Return true if the node specifies a shuffle of elements that is
3893 /// suitable for input to VALIGN.
3894 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3895                           const X86Subtarget *Subtarget) {
3896   // FIXME: Add AVX512VL.
3897   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3898     return false;
3899   return isAlignrMask(Mask, VT, true);
3900 }
3901
3902 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3903 /// the two vector operands have swapped position.
3904 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3905                                      unsigned NumElems) {
3906   for (unsigned i = 0; i != NumElems; ++i) {
3907     int idx = Mask[i];
3908     if (idx < 0)
3909       continue;
3910     else if (idx < (int)NumElems)
3911       Mask[i] = idx + NumElems;
3912     else
3913       Mask[i] = idx - NumElems;
3914   }
3915 }
3916
3917 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3918 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3919 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3920 /// reverse of what x86 shuffles want.
3921 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3922
3923   unsigned NumElems = VT.getVectorNumElements();
3924   unsigned NumLanes = VT.getSizeInBits()/128;
3925   unsigned NumLaneElems = NumElems/NumLanes;
3926
3927   if (NumLaneElems != 2 && NumLaneElems != 4)
3928     return false;
3929
3930   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3931   bool symetricMaskRequired =
3932     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3933
3934   // VSHUFPSY divides the resulting vector into 4 chunks.
3935   // The sources are also splitted into 4 chunks, and each destination
3936   // chunk must come from a different source chunk.
3937   //
3938   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3939   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3940   //
3941   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3942   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3943   //
3944   // VSHUFPDY divides the resulting vector into 4 chunks.
3945   // The sources are also splitted into 4 chunks, and each destination
3946   // chunk must come from a different source chunk.
3947   //
3948   //  SRC1 =>      X3       X2       X1       X0
3949   //  SRC2 =>      Y3       Y2       Y1       Y0
3950   //
3951   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3952   //
3953   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3954   unsigned HalfLaneElems = NumLaneElems/2;
3955   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3956     for (unsigned i = 0; i != NumLaneElems; ++i) {
3957       int Idx = Mask[i+l];
3958       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3959       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3960         return false;
3961       // For VSHUFPSY, the mask of the second half must be the same as the
3962       // first but with the appropriate offsets. This works in the same way as
3963       // VPERMILPS works with masks.
3964       if (!symetricMaskRequired || Idx < 0)
3965         continue;
3966       if (MaskVal[i] < 0) {
3967         MaskVal[i] = Idx - l;
3968         continue;
3969       }
3970       if ((signed)(Idx - l) != MaskVal[i])
3971         return false;
3972     }
3973   }
3974
3975   return true;
3976 }
3977
3978 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3979 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3980 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3981   if (!VT.is128BitVector())
3982     return false;
3983
3984   unsigned NumElems = VT.getVectorNumElements();
3985
3986   if (NumElems != 4)
3987     return false;
3988
3989   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3990   return isUndefOrEqual(Mask[0], 6) &&
3991          isUndefOrEqual(Mask[1], 7) &&
3992          isUndefOrEqual(Mask[2], 2) &&
3993          isUndefOrEqual(Mask[3], 3);
3994 }
3995
3996 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3997 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3998 /// <2, 3, 2, 3>
3999 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4000   if (!VT.is128BitVector())
4001     return false;
4002
4003   unsigned NumElems = VT.getVectorNumElements();
4004
4005   if (NumElems != 4)
4006     return false;
4007
4008   return isUndefOrEqual(Mask[0], 2) &&
4009          isUndefOrEqual(Mask[1], 3) &&
4010          isUndefOrEqual(Mask[2], 2) &&
4011          isUndefOrEqual(Mask[3], 3);
4012 }
4013
4014 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4015 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4016 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4017   if (!VT.is128BitVector())
4018     return false;
4019
4020   unsigned NumElems = VT.getVectorNumElements();
4021
4022   if (NumElems != 2 && NumElems != 4)
4023     return false;
4024
4025   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4026     if (!isUndefOrEqual(Mask[i], i + NumElems))
4027       return false;
4028
4029   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4030     if (!isUndefOrEqual(Mask[i], i))
4031       return false;
4032
4033   return true;
4034 }
4035
4036 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4037 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4038 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4039   if (!VT.is128BitVector())
4040     return false;
4041
4042   unsigned NumElems = VT.getVectorNumElements();
4043
4044   if (NumElems != 2 && NumElems != 4)
4045     return false;
4046
4047   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4048     if (!isUndefOrEqual(Mask[i], i))
4049       return false;
4050
4051   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4052     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4053       return false;
4054
4055   return true;
4056 }
4057
4058 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4059 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4060 /// i. e: If all but one element come from the same vector.
4061 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4062   // TODO: Deal with AVX's VINSERTPS
4063   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4064     return false;
4065
4066   unsigned CorrectPosV1 = 0;
4067   unsigned CorrectPosV2 = 0;
4068   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4069     if (Mask[i] == -1) {
4070       ++CorrectPosV1;
4071       ++CorrectPosV2;
4072       continue;
4073     }
4074
4075     if (Mask[i] == i)
4076       ++CorrectPosV1;
4077     else if (Mask[i] == i + 4)
4078       ++CorrectPosV2;
4079   }
4080
4081   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4082     // We have 3 elements (undefs count as elements from any vector) from one
4083     // vector, and one from another.
4084     return true;
4085
4086   return false;
4087 }
4088
4089 //
4090 // Some special combinations that can be optimized.
4091 //
4092 static
4093 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4094                                SelectionDAG &DAG) {
4095   MVT VT = SVOp->getSimpleValueType(0);
4096   SDLoc dl(SVOp);
4097
4098   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4099     return SDValue();
4100
4101   ArrayRef<int> Mask = SVOp->getMask();
4102
4103   // These are the special masks that may be optimized.
4104   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4105   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4106   bool MatchEvenMask = true;
4107   bool MatchOddMask  = true;
4108   for (int i=0; i<8; ++i) {
4109     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4110       MatchEvenMask = false;
4111     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4112       MatchOddMask = false;
4113   }
4114
4115   if (!MatchEvenMask && !MatchOddMask)
4116     return SDValue();
4117
4118   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4119
4120   SDValue Op0 = SVOp->getOperand(0);
4121   SDValue Op1 = SVOp->getOperand(1);
4122
4123   if (MatchEvenMask) {
4124     // Shift the second operand right to 32 bits.
4125     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4126     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4127   } else {
4128     // Shift the first operand left to 32 bits.
4129     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4130     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4131   }
4132   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4133   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4134 }
4135
4136 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4137 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4138 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4139                          bool HasInt256, bool V2IsSplat = false) {
4140
4141   assert(VT.getSizeInBits() >= 128 &&
4142          "Unsupported vector type for unpckl");
4143
4144   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4145   unsigned NumLanes;
4146   unsigned NumOf256BitLanes;
4147   unsigned NumElts = VT.getVectorNumElements();
4148   if (VT.is256BitVector()) {
4149     if (NumElts != 4 && NumElts != 8 &&
4150         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4151     return false;
4152     NumLanes = 2;
4153     NumOf256BitLanes = 1;
4154   } else if (VT.is512BitVector()) {
4155     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4156            "Unsupported vector type for unpckh");
4157     NumLanes = 2;
4158     NumOf256BitLanes = 2;
4159   } else {
4160     NumLanes = 1;
4161     NumOf256BitLanes = 1;
4162   }
4163
4164   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4165   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4166
4167   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4168     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4169       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4170         int BitI  = Mask[l256*NumEltsInStride+l+i];
4171         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4172         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4173           return false;
4174         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4175           return false;
4176         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4177           return false;
4178       }
4179     }
4180   }
4181   return true;
4182 }
4183
4184 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4185 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4186 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4187                          bool HasInt256, bool V2IsSplat = false) {
4188   assert(VT.getSizeInBits() >= 128 &&
4189          "Unsupported vector type for unpckh");
4190
4191   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4192   unsigned NumLanes;
4193   unsigned NumOf256BitLanes;
4194   unsigned NumElts = VT.getVectorNumElements();
4195   if (VT.is256BitVector()) {
4196     if (NumElts != 4 && NumElts != 8 &&
4197         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4198     return false;
4199     NumLanes = 2;
4200     NumOf256BitLanes = 1;
4201   } else if (VT.is512BitVector()) {
4202     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4203            "Unsupported vector type for unpckh");
4204     NumLanes = 2;
4205     NumOf256BitLanes = 2;
4206   } else {
4207     NumLanes = 1;
4208     NumOf256BitLanes = 1;
4209   }
4210
4211   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4212   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4213
4214   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4215     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4216       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4217         int BitI  = Mask[l256*NumEltsInStride+l+i];
4218         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4219         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4220           return false;
4221         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4222           return false;
4223         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4224           return false;
4225       }
4226     }
4227   }
4228   return true;
4229 }
4230
4231 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4232 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4233 /// <0, 0, 1, 1>
4234 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4235   unsigned NumElts = VT.getVectorNumElements();
4236   bool Is256BitVec = VT.is256BitVector();
4237
4238   if (VT.is512BitVector())
4239     return false;
4240   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4241          "Unsupported vector type for unpckh");
4242
4243   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4244       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4245     return false;
4246
4247   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4248   // FIXME: Need a better way to get rid of this, there's no latency difference
4249   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4250   // the former later. We should also remove the "_undef" special mask.
4251   if (NumElts == 4 && Is256BitVec)
4252     return false;
4253
4254   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4255   // independently on 128-bit lanes.
4256   unsigned NumLanes = VT.getSizeInBits()/128;
4257   unsigned NumLaneElts = NumElts/NumLanes;
4258
4259   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4260     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4261       int BitI  = Mask[l+i];
4262       int BitI1 = Mask[l+i+1];
4263
4264       if (!isUndefOrEqual(BitI, j))
4265         return false;
4266       if (!isUndefOrEqual(BitI1, j))
4267         return false;
4268     }
4269   }
4270
4271   return true;
4272 }
4273
4274 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4275 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4276 /// <2, 2, 3, 3>
4277 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4278   unsigned NumElts = VT.getVectorNumElements();
4279
4280   if (VT.is512BitVector())
4281     return false;
4282
4283   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4284          "Unsupported vector type for unpckh");
4285
4286   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4287       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4288     return false;
4289
4290   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4291   // independently on 128-bit lanes.
4292   unsigned NumLanes = VT.getSizeInBits()/128;
4293   unsigned NumLaneElts = NumElts/NumLanes;
4294
4295   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4296     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4297       int BitI  = Mask[l+i];
4298       int BitI1 = Mask[l+i+1];
4299       if (!isUndefOrEqual(BitI, j))
4300         return false;
4301       if (!isUndefOrEqual(BitI1, j))
4302         return false;
4303     }
4304   }
4305   return true;
4306 }
4307
4308 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4309 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4310 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4311   if (!VT.is512BitVector())
4312     return false;
4313
4314   unsigned NumElts = VT.getVectorNumElements();
4315   unsigned HalfSize = NumElts/2;
4316   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4317     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4318       *Imm = 1;
4319       return true;
4320     }
4321   }
4322   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4323     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4324       *Imm = 0;
4325       return true;
4326     }
4327   }
4328   return false;
4329 }
4330
4331 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4332 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4333 /// MOVSD, and MOVD, i.e. setting the lowest element.
4334 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4335   if (VT.getVectorElementType().getSizeInBits() < 32)
4336     return false;
4337   if (!VT.is128BitVector())
4338     return false;
4339
4340   unsigned NumElts = VT.getVectorNumElements();
4341
4342   if (!isUndefOrEqual(Mask[0], NumElts))
4343     return false;
4344
4345   for (unsigned i = 1; i != NumElts; ++i)
4346     if (!isUndefOrEqual(Mask[i], i))
4347       return false;
4348
4349   return true;
4350 }
4351
4352 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4353 /// as permutations between 128-bit chunks or halves. As an example: this
4354 /// shuffle bellow:
4355 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4356 /// The first half comes from the second half of V1 and the second half from the
4357 /// the second half of V2.
4358 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4359   if (!HasFp256 || !VT.is256BitVector())
4360     return false;
4361
4362   // The shuffle result is divided into half A and half B. In total the two
4363   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4364   // B must come from C, D, E or F.
4365   unsigned HalfSize = VT.getVectorNumElements()/2;
4366   bool MatchA = false, MatchB = false;
4367
4368   // Check if A comes from one of C, D, E, F.
4369   for (unsigned Half = 0; Half != 4; ++Half) {
4370     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4371       MatchA = true;
4372       break;
4373     }
4374   }
4375
4376   // Check if B comes from one of C, D, E, F.
4377   for (unsigned Half = 0; Half != 4; ++Half) {
4378     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4379       MatchB = true;
4380       break;
4381     }
4382   }
4383
4384   return MatchA && MatchB;
4385 }
4386
4387 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4388 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4389 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4390   MVT VT = SVOp->getSimpleValueType(0);
4391
4392   unsigned HalfSize = VT.getVectorNumElements()/2;
4393
4394   unsigned FstHalf = 0, SndHalf = 0;
4395   for (unsigned i = 0; i < HalfSize; ++i) {
4396     if (SVOp->getMaskElt(i) > 0) {
4397       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4398       break;
4399     }
4400   }
4401   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4402     if (SVOp->getMaskElt(i) > 0) {
4403       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4404       break;
4405     }
4406   }
4407
4408   return (FstHalf | (SndHalf << 4));
4409 }
4410
4411 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4412 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4413   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4414   if (EltSize < 32)
4415     return false;
4416
4417   unsigned NumElts = VT.getVectorNumElements();
4418   Imm8 = 0;
4419   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4420     for (unsigned i = 0; i != NumElts; ++i) {
4421       if (Mask[i] < 0)
4422         continue;
4423       Imm8 |= Mask[i] << (i*2);
4424     }
4425     return true;
4426   }
4427
4428   unsigned LaneSize = 4;
4429   SmallVector<int, 4> MaskVal(LaneSize, -1);
4430
4431   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4432     for (unsigned i = 0; i != LaneSize; ++i) {
4433       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4434         return false;
4435       if (Mask[i+l] < 0)
4436         continue;
4437       if (MaskVal[i] < 0) {
4438         MaskVal[i] = Mask[i+l] - l;
4439         Imm8 |= MaskVal[i] << (i*2);
4440         continue;
4441       }
4442       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4443         return false;
4444     }
4445   }
4446   return true;
4447 }
4448
4449 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4450 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4451 /// Note that VPERMIL mask matching is different depending whether theunderlying
4452 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4453 /// to the same elements of the low, but to the higher half of the source.
4454 /// In VPERMILPD the two lanes could be shuffled independently of each other
4455 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4456 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4457   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4458   if (VT.getSizeInBits() < 256 || EltSize < 32)
4459     return false;
4460   bool symetricMaskRequired = (EltSize == 32);
4461   unsigned NumElts = VT.getVectorNumElements();
4462
4463   unsigned NumLanes = VT.getSizeInBits()/128;
4464   unsigned LaneSize = NumElts/NumLanes;
4465   // 2 or 4 elements in one lane
4466
4467   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4468   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4469     for (unsigned i = 0; i != LaneSize; ++i) {
4470       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4471         return false;
4472       if (symetricMaskRequired) {
4473         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4474           ExpectedMaskVal[i] = Mask[i+l] - l;
4475           continue;
4476         }
4477         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4478           return false;
4479       }
4480     }
4481   }
4482   return true;
4483 }
4484
4485 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4486 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4487 /// element of vector 2 and the other elements to come from vector 1 in order.
4488 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4489                                bool V2IsSplat = false, bool V2IsUndef = false) {
4490   if (!VT.is128BitVector())
4491     return false;
4492
4493   unsigned NumOps = VT.getVectorNumElements();
4494   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4495     return false;
4496
4497   if (!isUndefOrEqual(Mask[0], 0))
4498     return false;
4499
4500   for (unsigned i = 1; i != NumOps; ++i)
4501     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4502           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4503           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4504       return false;
4505
4506   return true;
4507 }
4508
4509 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4510 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4511 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4512 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4513                            const X86Subtarget *Subtarget) {
4514   if (!Subtarget->hasSSE3())
4515     return false;
4516
4517   unsigned NumElems = VT.getVectorNumElements();
4518
4519   if ((VT.is128BitVector() && NumElems != 4) ||
4520       (VT.is256BitVector() && NumElems != 8) ||
4521       (VT.is512BitVector() && NumElems != 16))
4522     return false;
4523
4524   // "i+1" is the value the indexed mask element must have
4525   for (unsigned i = 0; i != NumElems; i += 2)
4526     if (!isUndefOrEqual(Mask[i], i+1) ||
4527         !isUndefOrEqual(Mask[i+1], i+1))
4528       return false;
4529
4530   return true;
4531 }
4532
4533 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4534 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4535 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4536 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4537                            const X86Subtarget *Subtarget) {
4538   if (!Subtarget->hasSSE3())
4539     return false;
4540
4541   unsigned NumElems = VT.getVectorNumElements();
4542
4543   if ((VT.is128BitVector() && NumElems != 4) ||
4544       (VT.is256BitVector() && NumElems != 8) ||
4545       (VT.is512BitVector() && NumElems != 16))
4546     return false;
4547
4548   // "i" is the value the indexed mask element must have
4549   for (unsigned i = 0; i != NumElems; i += 2)
4550     if (!isUndefOrEqual(Mask[i], i) ||
4551         !isUndefOrEqual(Mask[i+1], i))
4552       return false;
4553
4554   return true;
4555 }
4556
4557 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4558 /// specifies a shuffle of elements that is suitable for input to 256-bit
4559 /// version of MOVDDUP.
4560 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4561   if (!HasFp256 || !VT.is256BitVector())
4562     return false;
4563
4564   unsigned NumElts = VT.getVectorNumElements();
4565   if (NumElts != 4)
4566     return false;
4567
4568   for (unsigned i = 0; i != NumElts/2; ++i)
4569     if (!isUndefOrEqual(Mask[i], 0))
4570       return false;
4571   for (unsigned i = NumElts/2; i != NumElts; ++i)
4572     if (!isUndefOrEqual(Mask[i], NumElts/2))
4573       return false;
4574   return true;
4575 }
4576
4577 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4578 /// specifies a shuffle of elements that is suitable for input to 128-bit
4579 /// version of MOVDDUP.
4580 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4581   if (!VT.is128BitVector())
4582     return false;
4583
4584   unsigned e = VT.getVectorNumElements() / 2;
4585   for (unsigned i = 0; i != e; ++i)
4586     if (!isUndefOrEqual(Mask[i], i))
4587       return false;
4588   for (unsigned i = 0; i != e; ++i)
4589     if (!isUndefOrEqual(Mask[e+i], i))
4590       return false;
4591   return true;
4592 }
4593
4594 /// isVEXTRACTIndex - Return true if the specified
4595 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4596 /// suitable for instruction that extract 128 or 256 bit vectors
4597 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4598   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4599   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4600     return false;
4601
4602   // The index should be aligned on a vecWidth-bit boundary.
4603   uint64_t Index =
4604     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4605
4606   MVT VT = N->getSimpleValueType(0);
4607   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4608   bool Result = (Index * ElSize) % vecWidth == 0;
4609
4610   return Result;
4611 }
4612
4613 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4614 /// operand specifies a subvector insert that is suitable for input to
4615 /// insertion of 128 or 256-bit subvectors
4616 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4617   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4618   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4619     return false;
4620   // The index should be aligned on a vecWidth-bit boundary.
4621   uint64_t Index =
4622     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4623
4624   MVT VT = N->getSimpleValueType(0);
4625   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4626   bool Result = (Index * ElSize) % vecWidth == 0;
4627
4628   return Result;
4629 }
4630
4631 bool X86::isVINSERT128Index(SDNode *N) {
4632   return isVINSERTIndex(N, 128);
4633 }
4634
4635 bool X86::isVINSERT256Index(SDNode *N) {
4636   return isVINSERTIndex(N, 256);
4637 }
4638
4639 bool X86::isVEXTRACT128Index(SDNode *N) {
4640   return isVEXTRACTIndex(N, 128);
4641 }
4642
4643 bool X86::isVEXTRACT256Index(SDNode *N) {
4644   return isVEXTRACTIndex(N, 256);
4645 }
4646
4647 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4648 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4649 /// Handles 128-bit and 256-bit.
4650 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4651   MVT VT = N->getSimpleValueType(0);
4652
4653   assert((VT.getSizeInBits() >= 128) &&
4654          "Unsupported vector type for PSHUF/SHUFP");
4655
4656   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4657   // independently on 128-bit lanes.
4658   unsigned NumElts = VT.getVectorNumElements();
4659   unsigned NumLanes = VT.getSizeInBits()/128;
4660   unsigned NumLaneElts = NumElts/NumLanes;
4661
4662   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4663          "Only supports 2, 4 or 8 elements per lane");
4664
4665   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4666   unsigned Mask = 0;
4667   for (unsigned i = 0; i != NumElts; ++i) {
4668     int Elt = N->getMaskElt(i);
4669     if (Elt < 0) continue;
4670     Elt &= NumLaneElts - 1;
4671     unsigned ShAmt = (i << Shift) % 8;
4672     Mask |= Elt << ShAmt;
4673   }
4674
4675   return Mask;
4676 }
4677
4678 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4679 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4680 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4681   MVT VT = N->getSimpleValueType(0);
4682
4683   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4684          "Unsupported vector type for PSHUFHW");
4685
4686   unsigned NumElts = VT.getVectorNumElements();
4687
4688   unsigned Mask = 0;
4689   for (unsigned l = 0; l != NumElts; l += 8) {
4690     // 8 nodes per lane, but we only care about the last 4.
4691     for (unsigned i = 0; i < 4; ++i) {
4692       int Elt = N->getMaskElt(l+i+4);
4693       if (Elt < 0) continue;
4694       Elt &= 0x3; // only 2-bits.
4695       Mask |= Elt << (i * 2);
4696     }
4697   }
4698
4699   return Mask;
4700 }
4701
4702 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4703 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4704 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4705   MVT VT = N->getSimpleValueType(0);
4706
4707   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4708          "Unsupported vector type for PSHUFHW");
4709
4710   unsigned NumElts = VT.getVectorNumElements();
4711
4712   unsigned Mask = 0;
4713   for (unsigned l = 0; l != NumElts; l += 8) {
4714     // 8 nodes per lane, but we only care about the first 4.
4715     for (unsigned i = 0; i < 4; ++i) {
4716       int Elt = N->getMaskElt(l+i);
4717       if (Elt < 0) continue;
4718       Elt &= 0x3; // only 2-bits
4719       Mask |= Elt << (i * 2);
4720     }
4721   }
4722
4723   return Mask;
4724 }
4725
4726 /// \brief Return the appropriate immediate to shuffle the specified
4727 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4728 /// VALIGN (if Interlane is true) instructions.
4729 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4730                                            bool InterLane) {
4731   MVT VT = SVOp->getSimpleValueType(0);
4732   unsigned EltSize = InterLane ? 1 :
4733     VT.getVectorElementType().getSizeInBits() >> 3;
4734
4735   unsigned NumElts = VT.getVectorNumElements();
4736   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4737   unsigned NumLaneElts = NumElts/NumLanes;
4738
4739   int Val = 0;
4740   unsigned i;
4741   for (i = 0; i != NumElts; ++i) {
4742     Val = SVOp->getMaskElt(i);
4743     if (Val >= 0)
4744       break;
4745   }
4746   if (Val >= (int)NumElts)
4747     Val -= NumElts - NumLaneElts;
4748
4749   assert(Val - i > 0 && "PALIGNR imm should be positive");
4750   return (Val - i) * EltSize;
4751 }
4752
4753 /// \brief Return the appropriate immediate to shuffle the specified
4754 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4755 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4756   return getShuffleAlignrImmediate(SVOp, false);
4757 }
4758
4759 /// \brief Return the appropriate immediate to shuffle the specified
4760 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4761 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4762   return getShuffleAlignrImmediate(SVOp, true);
4763 }
4764
4765
4766 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4767   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4768   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4769     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4770
4771   uint64_t Index =
4772     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4773
4774   MVT VecVT = N->getOperand(0).getSimpleValueType();
4775   MVT ElVT = VecVT.getVectorElementType();
4776
4777   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4778   return Index / NumElemsPerChunk;
4779 }
4780
4781 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4782   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4783   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4784     llvm_unreachable("Illegal insert subvector for VINSERT");
4785
4786   uint64_t Index =
4787     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4788
4789   MVT VecVT = N->getSimpleValueType(0);
4790   MVT ElVT = VecVT.getVectorElementType();
4791
4792   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4793   return Index / NumElemsPerChunk;
4794 }
4795
4796 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4797 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4798 /// and VINSERTI128 instructions.
4799 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4800   return getExtractVEXTRACTImmediate(N, 128);
4801 }
4802
4803 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4804 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4805 /// and VINSERTI64x4 instructions.
4806 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4807   return getExtractVEXTRACTImmediate(N, 256);
4808 }
4809
4810 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4811 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4812 /// and VINSERTI128 instructions.
4813 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4814   return getInsertVINSERTImmediate(N, 128);
4815 }
4816
4817 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4818 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4819 /// and VINSERTI64x4 instructions.
4820 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4821   return getInsertVINSERTImmediate(N, 256);
4822 }
4823
4824 /// isZero - Returns true if Elt is a constant integer zero
4825 static bool isZero(SDValue V) {
4826   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4827   return C && C->isNullValue();
4828 }
4829
4830 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4831 /// constant +0.0.
4832 bool X86::isZeroNode(SDValue Elt) {
4833   if (isZero(Elt))
4834     return true;
4835   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4836     return CFP->getValueAPF().isPosZero();
4837   return false;
4838 }
4839
4840 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4841 /// match movhlps. The lower half elements should come from upper half of
4842 /// V1 (and in order), and the upper half elements should come from the upper
4843 /// half of V2 (and in order).
4844 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4845   if (!VT.is128BitVector())
4846     return false;
4847   if (VT.getVectorNumElements() != 4)
4848     return false;
4849   for (unsigned i = 0, e = 2; i != e; ++i)
4850     if (!isUndefOrEqual(Mask[i], i+2))
4851       return false;
4852   for (unsigned i = 2; i != 4; ++i)
4853     if (!isUndefOrEqual(Mask[i], i+4))
4854       return false;
4855   return true;
4856 }
4857
4858 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4859 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4860 /// required.
4861 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4862   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4863     return false;
4864   N = N->getOperand(0).getNode();
4865   if (!ISD::isNON_EXTLoad(N))
4866     return false;
4867   if (LD)
4868     *LD = cast<LoadSDNode>(N);
4869   return true;
4870 }
4871
4872 // Test whether the given value is a vector value which will be legalized
4873 // into a load.
4874 static bool WillBeConstantPoolLoad(SDNode *N) {
4875   if (N->getOpcode() != ISD::BUILD_VECTOR)
4876     return false;
4877
4878   // Check for any non-constant elements.
4879   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4880     switch (N->getOperand(i).getNode()->getOpcode()) {
4881     case ISD::UNDEF:
4882     case ISD::ConstantFP:
4883     case ISD::Constant:
4884       break;
4885     default:
4886       return false;
4887     }
4888
4889   // Vectors of all-zeros and all-ones are materialized with special
4890   // instructions rather than being loaded.
4891   return !ISD::isBuildVectorAllZeros(N) &&
4892          !ISD::isBuildVectorAllOnes(N);
4893 }
4894
4895 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4896 /// match movlp{s|d}. The lower half elements should come from lower half of
4897 /// V1 (and in order), and the upper half elements should come from the upper
4898 /// half of V2 (and in order). And since V1 will become the source of the
4899 /// MOVLP, it must be either a vector load or a scalar load to vector.
4900 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4901                                ArrayRef<int> Mask, MVT VT) {
4902   if (!VT.is128BitVector())
4903     return false;
4904
4905   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4906     return false;
4907   // Is V2 is a vector load, don't do this transformation. We will try to use
4908   // load folding shufps op.
4909   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4910     return false;
4911
4912   unsigned NumElems = VT.getVectorNumElements();
4913
4914   if (NumElems != 2 && NumElems != 4)
4915     return false;
4916   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4917     if (!isUndefOrEqual(Mask[i], i))
4918       return false;
4919   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4920     if (!isUndefOrEqual(Mask[i], i+NumElems))
4921       return false;
4922   return true;
4923 }
4924
4925 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4926 /// to an zero vector.
4927 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4928 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4929   SDValue V1 = N->getOperand(0);
4930   SDValue V2 = N->getOperand(1);
4931   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4932   for (unsigned i = 0; i != NumElems; ++i) {
4933     int Idx = N->getMaskElt(i);
4934     if (Idx >= (int)NumElems) {
4935       unsigned Opc = V2.getOpcode();
4936       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4937         continue;
4938       if (Opc != ISD::BUILD_VECTOR ||
4939           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4940         return false;
4941     } else if (Idx >= 0) {
4942       unsigned Opc = V1.getOpcode();
4943       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4944         continue;
4945       if (Opc != ISD::BUILD_VECTOR ||
4946           !X86::isZeroNode(V1.getOperand(Idx)))
4947         return false;
4948     }
4949   }
4950   return true;
4951 }
4952
4953 /// getZeroVector - Returns a vector of specified type with all zero elements.
4954 ///
4955 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4956                              SelectionDAG &DAG, SDLoc dl) {
4957   assert(VT.isVector() && "Expected a vector type");
4958
4959   // Always build SSE zero vectors as <4 x i32> bitcasted
4960   // to their dest type. This ensures they get CSE'd.
4961   SDValue Vec;
4962   if (VT.is128BitVector()) {  // SSE
4963     if (Subtarget->hasSSE2()) {  // SSE2
4964       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4965       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4966     } else { // SSE1
4967       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4968       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4969     }
4970   } else if (VT.is256BitVector()) { // AVX
4971     if (Subtarget->hasInt256()) { // AVX2
4972       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4973       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4974       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4975     } else {
4976       // 256-bit logic and arithmetic instructions in AVX are all
4977       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4978       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4979       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4980       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4981     }
4982   } else if (VT.is512BitVector()) { // AVX-512
4983       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4984       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4985                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4986       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4987   } else if (VT.getScalarType() == MVT::i1) {
4988     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4989     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4990     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4991     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4992   } else
4993     llvm_unreachable("Unexpected vector type");
4994
4995   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4996 }
4997
4998 /// getOnesVector - Returns a vector of specified type with all bits set.
4999 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5000 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5001 /// Then bitcast to their original type, ensuring they get CSE'd.
5002 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5003                              SDLoc dl) {
5004   assert(VT.isVector() && "Expected a vector type");
5005
5006   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5007   SDValue Vec;
5008   if (VT.is256BitVector()) {
5009     if (HasInt256) { // AVX2
5010       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5011       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5012     } else { // AVX
5013       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5014       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5015     }
5016   } else if (VT.is128BitVector()) {
5017     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5018   } else
5019     llvm_unreachable("Unexpected vector type");
5020
5021   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5022 }
5023
5024 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5025 /// that point to V2 points to its first element.
5026 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5027   for (unsigned i = 0; i != NumElems; ++i) {
5028     if (Mask[i] > (int)NumElems) {
5029       Mask[i] = NumElems;
5030     }
5031   }
5032 }
5033
5034 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5035 /// operation of specified width.
5036 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5037                        SDValue V2) {
5038   unsigned NumElems = VT.getVectorNumElements();
5039   SmallVector<int, 8> Mask;
5040   Mask.push_back(NumElems);
5041   for (unsigned i = 1; i != NumElems; ++i)
5042     Mask.push_back(i);
5043   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5044 }
5045
5046 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5047 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5048                           SDValue V2) {
5049   unsigned NumElems = VT.getVectorNumElements();
5050   SmallVector<int, 8> Mask;
5051   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5052     Mask.push_back(i);
5053     Mask.push_back(i + NumElems);
5054   }
5055   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5056 }
5057
5058 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5059 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5060                           SDValue V2) {
5061   unsigned NumElems = VT.getVectorNumElements();
5062   SmallVector<int, 8> Mask;
5063   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5064     Mask.push_back(i + Half);
5065     Mask.push_back(i + NumElems + Half);
5066   }
5067   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5068 }
5069
5070 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5071 // a generic shuffle instruction because the target has no such instructions.
5072 // Generate shuffles which repeat i16 and i8 several times until they can be
5073 // represented by v4f32 and then be manipulated by target suported shuffles.
5074 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5075   MVT VT = V.getSimpleValueType();
5076   int NumElems = VT.getVectorNumElements();
5077   SDLoc dl(V);
5078
5079   while (NumElems > 4) {
5080     if (EltNo < NumElems/2) {
5081       V = getUnpackl(DAG, dl, VT, V, V);
5082     } else {
5083       V = getUnpackh(DAG, dl, VT, V, V);
5084       EltNo -= NumElems/2;
5085     }
5086     NumElems >>= 1;
5087   }
5088   return V;
5089 }
5090
5091 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5092 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5093   MVT VT = V.getSimpleValueType();
5094   SDLoc dl(V);
5095
5096   if (VT.is128BitVector()) {
5097     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5098     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5099     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5100                              &SplatMask[0]);
5101   } else if (VT.is256BitVector()) {
5102     // To use VPERMILPS to splat scalars, the second half of indicies must
5103     // refer to the higher part, which is a duplication of the lower one,
5104     // because VPERMILPS can only handle in-lane permutations.
5105     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5106                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5107
5108     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5109     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5110                              &SplatMask[0]);
5111   } else
5112     llvm_unreachable("Vector size not supported");
5113
5114   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5115 }
5116
5117 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5118 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5119   MVT SrcVT = SV->getSimpleValueType(0);
5120   SDValue V1 = SV->getOperand(0);
5121   SDLoc dl(SV);
5122
5123   int EltNo = SV->getSplatIndex();
5124   int NumElems = SrcVT.getVectorNumElements();
5125   bool Is256BitVec = SrcVT.is256BitVector();
5126
5127   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5128          "Unknown how to promote splat for type");
5129
5130   // Extract the 128-bit part containing the splat element and update
5131   // the splat element index when it refers to the higher register.
5132   if (Is256BitVec) {
5133     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5134     if (EltNo >= NumElems/2)
5135       EltNo -= NumElems/2;
5136   }
5137
5138   // All i16 and i8 vector types can't be used directly by a generic shuffle
5139   // instruction because the target has no such instruction. Generate shuffles
5140   // which repeat i16 and i8 several times until they fit in i32, and then can
5141   // be manipulated by target suported shuffles.
5142   MVT EltVT = SrcVT.getVectorElementType();
5143   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5144     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5145
5146   // Recreate the 256-bit vector and place the same 128-bit vector
5147   // into the low and high part. This is necessary because we want
5148   // to use VPERM* to shuffle the vectors
5149   if (Is256BitVec) {
5150     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5151   }
5152
5153   return getLegalSplat(DAG, V1, EltNo);
5154 }
5155
5156 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5157 /// vector of zero or undef vector.  This produces a shuffle where the low
5158 /// element of V2 is swizzled into the zero/undef vector, landing at element
5159 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5160 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5161                                            bool IsZero,
5162                                            const X86Subtarget *Subtarget,
5163                                            SelectionDAG &DAG) {
5164   MVT VT = V2.getSimpleValueType();
5165   SDValue V1 = IsZero
5166     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5167   unsigned NumElems = VT.getVectorNumElements();
5168   SmallVector<int, 16> MaskVec;
5169   for (unsigned i = 0; i != NumElems; ++i)
5170     // If this is the insertion idx, put the low elt of V2 here.
5171     MaskVec.push_back(i == Idx ? NumElems : i);
5172   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5173 }
5174
5175 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5176 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5177 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5178 /// shuffles which use a single input multiple times, and in those cases it will
5179 /// adjust the mask to only have indices within that single input.
5180 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5181                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5182   unsigned NumElems = VT.getVectorNumElements();
5183   SDValue ImmN;
5184
5185   IsUnary = false;
5186   bool IsFakeUnary = false;
5187   switch(N->getOpcode()) {
5188   case X86ISD::SHUFP:
5189     ImmN = N->getOperand(N->getNumOperands()-1);
5190     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5191     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5192     break;
5193   case X86ISD::UNPCKH:
5194     DecodeUNPCKHMask(VT, Mask);
5195     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5196     break;
5197   case X86ISD::UNPCKL:
5198     DecodeUNPCKLMask(VT, Mask);
5199     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5200     break;
5201   case X86ISD::MOVHLPS:
5202     DecodeMOVHLPSMask(NumElems, Mask);
5203     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5204     break;
5205   case X86ISD::MOVLHPS:
5206     DecodeMOVLHPSMask(NumElems, Mask);
5207     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5208     break;
5209   case X86ISD::PALIGNR:
5210     ImmN = N->getOperand(N->getNumOperands()-1);
5211     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5212     break;
5213   case X86ISD::PSHUFD:
5214   case X86ISD::VPERMILP:
5215     ImmN = N->getOperand(N->getNumOperands()-1);
5216     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5217     IsUnary = true;
5218     break;
5219   case X86ISD::PSHUFHW:
5220     ImmN = N->getOperand(N->getNumOperands()-1);
5221     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5222     IsUnary = true;
5223     break;
5224   case X86ISD::PSHUFLW:
5225     ImmN = N->getOperand(N->getNumOperands()-1);
5226     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5227     IsUnary = true;
5228     break;
5229   case X86ISD::PSHUFB: {
5230     IsUnary = true;
5231     SDValue MaskNode = N->getOperand(1);
5232     while (MaskNode->getOpcode() == ISD::BITCAST)
5233       MaskNode = MaskNode->getOperand(0);
5234
5235     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5236       // If we have a build-vector, then things are easy.
5237       EVT VT = MaskNode.getValueType();
5238       assert(VT.isVector() &&
5239              "Can't produce a non-vector with a build_vector!");
5240       if (!VT.isInteger())
5241         return false;
5242
5243       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5244
5245       SmallVector<uint64_t, 32> RawMask;
5246       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5247         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5248         if (!CN)
5249           return false;
5250         APInt MaskElement = CN->getAPIntValue();
5251
5252         // We now have to decode the element which could be any integer size and
5253         // extract each byte of it.
5254         for (int j = 0; j < NumBytesPerElement; ++j) {
5255           // Note that this is x86 and so always little endian: the low byte is
5256           // the first byte of the mask.
5257           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5258           MaskElement = MaskElement.lshr(8);
5259         }
5260       }
5261       DecodePSHUFBMask(RawMask, Mask);
5262       break;
5263     }
5264
5265     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5266     if (!MaskLoad)
5267       return false;
5268
5269     SDValue Ptr = MaskLoad->getBasePtr();
5270     if (Ptr->getOpcode() == X86ISD::Wrapper)
5271       Ptr = Ptr->getOperand(0);
5272
5273     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5274     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5275       return false;
5276
5277     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5278       // FIXME: Support AVX-512 here.
5279       if (!C->getType()->isVectorTy() ||
5280           (C->getNumElements() != 16 && C->getNumElements() != 32))
5281         return false;
5282
5283       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5284       DecodePSHUFBMask(C, Mask);
5285       break;
5286     }
5287
5288     return false;
5289   }
5290   case X86ISD::VPERMI:
5291     ImmN = N->getOperand(N->getNumOperands()-1);
5292     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5293     IsUnary = true;
5294     break;
5295   case X86ISD::MOVSS:
5296   case X86ISD::MOVSD: {
5297     // The index 0 always comes from the first element of the second source,
5298     // this is why MOVSS and MOVSD are used in the first place. The other
5299     // elements come from the other positions of the first source vector
5300     Mask.push_back(NumElems);
5301     for (unsigned i = 1; i != NumElems; ++i) {
5302       Mask.push_back(i);
5303     }
5304     break;
5305   }
5306   case X86ISD::VPERM2X128:
5307     ImmN = N->getOperand(N->getNumOperands()-1);
5308     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5309     if (Mask.empty()) return false;
5310     break;
5311   case X86ISD::MOVDDUP:
5312   case X86ISD::MOVLHPD:
5313   case X86ISD::MOVLPD:
5314   case X86ISD::MOVLPS:
5315   case X86ISD::MOVSHDUP:
5316   case X86ISD::MOVSLDUP:
5317     // Not yet implemented
5318     return false;
5319   default: llvm_unreachable("unknown target shuffle node");
5320   }
5321
5322   // If we have a fake unary shuffle, the shuffle mask is spread across two
5323   // inputs that are actually the same node. Re-map the mask to always point
5324   // into the first input.
5325   if (IsFakeUnary)
5326     for (int &M : Mask)
5327       if (M >= (int)Mask.size())
5328         M -= Mask.size();
5329
5330   return true;
5331 }
5332
5333 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5334 /// element of the result of the vector shuffle.
5335 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5336                                    unsigned Depth) {
5337   if (Depth == 6)
5338     return SDValue();  // Limit search depth.
5339
5340   SDValue V = SDValue(N, 0);
5341   EVT VT = V.getValueType();
5342   unsigned Opcode = V.getOpcode();
5343
5344   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5345   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5346     int Elt = SV->getMaskElt(Index);
5347
5348     if (Elt < 0)
5349       return DAG.getUNDEF(VT.getVectorElementType());
5350
5351     unsigned NumElems = VT.getVectorNumElements();
5352     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5353                                          : SV->getOperand(1);
5354     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5355   }
5356
5357   // Recurse into target specific vector shuffles to find scalars.
5358   if (isTargetShuffle(Opcode)) {
5359     MVT ShufVT = V.getSimpleValueType();
5360     unsigned NumElems = ShufVT.getVectorNumElements();
5361     SmallVector<int, 16> ShuffleMask;
5362     bool IsUnary;
5363
5364     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5365       return SDValue();
5366
5367     int Elt = ShuffleMask[Index];
5368     if (Elt < 0)
5369       return DAG.getUNDEF(ShufVT.getVectorElementType());
5370
5371     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5372                                          : N->getOperand(1);
5373     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5374                                Depth+1);
5375   }
5376
5377   // Actual nodes that may contain scalar elements
5378   if (Opcode == ISD::BITCAST) {
5379     V = V.getOperand(0);
5380     EVT SrcVT = V.getValueType();
5381     unsigned NumElems = VT.getVectorNumElements();
5382
5383     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5384       return SDValue();
5385   }
5386
5387   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5388     return (Index == 0) ? V.getOperand(0)
5389                         : DAG.getUNDEF(VT.getVectorElementType());
5390
5391   if (V.getOpcode() == ISD::BUILD_VECTOR)
5392     return V.getOperand(Index);
5393
5394   return SDValue();
5395 }
5396
5397 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5398 /// shuffle operation which come from a consecutively from a zero. The
5399 /// search can start in two different directions, from left or right.
5400 /// We count undefs as zeros until PreferredNum is reached.
5401 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5402                                          unsigned NumElems, bool ZerosFromLeft,
5403                                          SelectionDAG &DAG,
5404                                          unsigned PreferredNum = -1U) {
5405   unsigned NumZeros = 0;
5406   for (unsigned i = 0; i != NumElems; ++i) {
5407     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5408     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5409     if (!Elt.getNode())
5410       break;
5411
5412     if (X86::isZeroNode(Elt))
5413       ++NumZeros;
5414     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5415       NumZeros = std::min(NumZeros + 1, PreferredNum);
5416     else
5417       break;
5418   }
5419
5420   return NumZeros;
5421 }
5422
5423 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5424 /// correspond consecutively to elements from one of the vector operands,
5425 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5426 static
5427 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5428                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5429                               unsigned NumElems, unsigned &OpNum) {
5430   bool SeenV1 = false;
5431   bool SeenV2 = false;
5432
5433   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5434     int Idx = SVOp->getMaskElt(i);
5435     // Ignore undef indicies
5436     if (Idx < 0)
5437       continue;
5438
5439     if (Idx < (int)NumElems)
5440       SeenV1 = true;
5441     else
5442       SeenV2 = true;
5443
5444     // Only accept consecutive elements from the same vector
5445     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5446       return false;
5447   }
5448
5449   OpNum = SeenV1 ? 0 : 1;
5450   return true;
5451 }
5452
5453 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5454 /// logical left shift of a vector.
5455 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5456                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5457   unsigned NumElems =
5458     SVOp->getSimpleValueType(0).getVectorNumElements();
5459   unsigned NumZeros = getNumOfConsecutiveZeros(
5460       SVOp, NumElems, false /* check zeros from right */, DAG,
5461       SVOp->getMaskElt(0));
5462   unsigned OpSrc;
5463
5464   if (!NumZeros)
5465     return false;
5466
5467   // Considering the elements in the mask that are not consecutive zeros,
5468   // check if they consecutively come from only one of the source vectors.
5469   //
5470   //               V1 = {X, A, B, C}     0
5471   //                         \  \  \    /
5472   //   vector_shuffle V1, V2 <1, 2, 3, X>
5473   //
5474   if (!isShuffleMaskConsecutive(SVOp,
5475             0,                   // Mask Start Index
5476             NumElems-NumZeros,   // Mask End Index(exclusive)
5477             NumZeros,            // Where to start looking in the src vector
5478             NumElems,            // Number of elements in vector
5479             OpSrc))              // Which source operand ?
5480     return false;
5481
5482   isLeft = false;
5483   ShAmt = NumZeros;
5484   ShVal = SVOp->getOperand(OpSrc);
5485   return true;
5486 }
5487
5488 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5489 /// logical left shift of a vector.
5490 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5491                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5492   unsigned NumElems =
5493     SVOp->getSimpleValueType(0).getVectorNumElements();
5494   unsigned NumZeros = getNumOfConsecutiveZeros(
5495       SVOp, NumElems, true /* check zeros from left */, DAG,
5496       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5497   unsigned OpSrc;
5498
5499   if (!NumZeros)
5500     return false;
5501
5502   // Considering the elements in the mask that are not consecutive zeros,
5503   // check if they consecutively come from only one of the source vectors.
5504   //
5505   //                           0    { A, B, X, X } = V2
5506   //                          / \    /  /
5507   //   vector_shuffle V1, V2 <X, X, 4, 5>
5508   //
5509   if (!isShuffleMaskConsecutive(SVOp,
5510             NumZeros,     // Mask Start Index
5511             NumElems,     // Mask End Index(exclusive)
5512             0,            // Where to start looking in the src vector
5513             NumElems,     // Number of elements in vector
5514             OpSrc))       // Which source operand ?
5515     return false;
5516
5517   isLeft = true;
5518   ShAmt = NumZeros;
5519   ShVal = SVOp->getOperand(OpSrc);
5520   return true;
5521 }
5522
5523 /// isVectorShift - Returns true if the shuffle can be implemented as a
5524 /// logical left or right shift of a vector.
5525 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5526                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5527   // Although the logic below support any bitwidth size, there are no
5528   // shift instructions which handle more than 128-bit vectors.
5529   if (!SVOp->getSimpleValueType(0).is128BitVector())
5530     return false;
5531
5532   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5533       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5534     return true;
5535
5536   return false;
5537 }
5538
5539 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5540 ///
5541 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5542                                        unsigned NumNonZero, unsigned NumZero,
5543                                        SelectionDAG &DAG,
5544                                        const X86Subtarget* Subtarget,
5545                                        const TargetLowering &TLI) {
5546   if (NumNonZero > 8)
5547     return SDValue();
5548
5549   SDLoc dl(Op);
5550   SDValue V;
5551   bool First = true;
5552   for (unsigned i = 0; i < 16; ++i) {
5553     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5554     if (ThisIsNonZero && First) {
5555       if (NumZero)
5556         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5557       else
5558         V = DAG.getUNDEF(MVT::v8i16);
5559       First = false;
5560     }
5561
5562     if ((i & 1) != 0) {
5563       SDValue ThisElt, LastElt;
5564       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5565       if (LastIsNonZero) {
5566         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5567                               MVT::i16, Op.getOperand(i-1));
5568       }
5569       if (ThisIsNonZero) {
5570         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5571         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5572                               ThisElt, DAG.getConstant(8, MVT::i8));
5573         if (LastIsNonZero)
5574           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5575       } else
5576         ThisElt = LastElt;
5577
5578       if (ThisElt.getNode())
5579         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5580                         DAG.getIntPtrConstant(i/2));
5581     }
5582   }
5583
5584   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5585 }
5586
5587 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5588 ///
5589 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5590                                      unsigned NumNonZero, unsigned NumZero,
5591                                      SelectionDAG &DAG,
5592                                      const X86Subtarget* Subtarget,
5593                                      const TargetLowering &TLI) {
5594   if (NumNonZero > 4)
5595     return SDValue();
5596
5597   SDLoc dl(Op);
5598   SDValue V;
5599   bool First = true;
5600   for (unsigned i = 0; i < 8; ++i) {
5601     bool isNonZero = (NonZeros & (1 << i)) != 0;
5602     if (isNonZero) {
5603       if (First) {
5604         if (NumZero)
5605           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5606         else
5607           V = DAG.getUNDEF(MVT::v8i16);
5608         First = false;
5609       }
5610       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5611                       MVT::v8i16, V, Op.getOperand(i),
5612                       DAG.getIntPtrConstant(i));
5613     }
5614   }
5615
5616   return V;
5617 }
5618
5619 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5620 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5621                                      unsigned NonZeros, unsigned NumNonZero,
5622                                      unsigned NumZero, SelectionDAG &DAG,
5623                                      const X86Subtarget *Subtarget,
5624                                      const TargetLowering &TLI) {
5625   // We know there's at least one non-zero element
5626   unsigned FirstNonZeroIdx = 0;
5627   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5628   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5629          X86::isZeroNode(FirstNonZero)) {
5630     ++FirstNonZeroIdx;
5631     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5632   }
5633
5634   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5635       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5636     return SDValue();
5637
5638   SDValue V = FirstNonZero.getOperand(0);
5639   MVT VVT = V.getSimpleValueType();
5640   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5641     return SDValue();
5642
5643   unsigned FirstNonZeroDst =
5644       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5645   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5646   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5647   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5648
5649   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5650     SDValue Elem = Op.getOperand(Idx);
5651     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5652       continue;
5653
5654     // TODO: What else can be here? Deal with it.
5655     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5656       return SDValue();
5657
5658     // TODO: Some optimizations are still possible here
5659     // ex: Getting one element from a vector, and the rest from another.
5660     if (Elem.getOperand(0) != V)
5661       return SDValue();
5662
5663     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5664     if (Dst == Idx)
5665       ++CorrectIdx;
5666     else if (IncorrectIdx == -1U) {
5667       IncorrectIdx = Idx;
5668       IncorrectDst = Dst;
5669     } else
5670       // There was already one element with an incorrect index.
5671       // We can't optimize this case to an insertps.
5672       return SDValue();
5673   }
5674
5675   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5676     SDLoc dl(Op);
5677     EVT VT = Op.getSimpleValueType();
5678     unsigned ElementMoveMask = 0;
5679     if (IncorrectIdx == -1U)
5680       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5681     else
5682       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5683
5684     SDValue InsertpsMask =
5685         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5686     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5687   }
5688
5689   return SDValue();
5690 }
5691
5692 /// getVShift - Return a vector logical shift node.
5693 ///
5694 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5695                          unsigned NumBits, SelectionDAG &DAG,
5696                          const TargetLowering &TLI, SDLoc dl) {
5697   assert(VT.is128BitVector() && "Unknown type for VShift");
5698   EVT ShVT = MVT::v2i64;
5699   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5700   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5701   return DAG.getNode(ISD::BITCAST, dl, VT,
5702                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5703                              DAG.getConstant(NumBits,
5704                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5705 }
5706
5707 static SDValue
5708 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5709
5710   // Check if the scalar load can be widened into a vector load. And if
5711   // the address is "base + cst" see if the cst can be "absorbed" into
5712   // the shuffle mask.
5713   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5714     SDValue Ptr = LD->getBasePtr();
5715     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5716       return SDValue();
5717     EVT PVT = LD->getValueType(0);
5718     if (PVT != MVT::i32 && PVT != MVT::f32)
5719       return SDValue();
5720
5721     int FI = -1;
5722     int64_t Offset = 0;
5723     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5724       FI = FINode->getIndex();
5725       Offset = 0;
5726     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5727                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5728       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5729       Offset = Ptr.getConstantOperandVal(1);
5730       Ptr = Ptr.getOperand(0);
5731     } else {
5732       return SDValue();
5733     }
5734
5735     // FIXME: 256-bit vector instructions don't require a strict alignment,
5736     // improve this code to support it better.
5737     unsigned RequiredAlign = VT.getSizeInBits()/8;
5738     SDValue Chain = LD->getChain();
5739     // Make sure the stack object alignment is at least 16 or 32.
5740     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5741     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5742       if (MFI->isFixedObjectIndex(FI)) {
5743         // Can't change the alignment. FIXME: It's possible to compute
5744         // the exact stack offset and reference FI + adjust offset instead.
5745         // If someone *really* cares about this. That's the way to implement it.
5746         return SDValue();
5747       } else {
5748         MFI->setObjectAlignment(FI, RequiredAlign);
5749       }
5750     }
5751
5752     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5753     // Ptr + (Offset & ~15).
5754     if (Offset < 0)
5755       return SDValue();
5756     if ((Offset % RequiredAlign) & 3)
5757       return SDValue();
5758     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5759     if (StartOffset)
5760       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5761                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5762
5763     int EltNo = (Offset - StartOffset) >> 2;
5764     unsigned NumElems = VT.getVectorNumElements();
5765
5766     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5767     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5768                              LD->getPointerInfo().getWithOffset(StartOffset),
5769                              false, false, false, 0);
5770
5771     SmallVector<int, 8> Mask;
5772     for (unsigned i = 0; i != NumElems; ++i)
5773       Mask.push_back(EltNo);
5774
5775     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5776   }
5777
5778   return SDValue();
5779 }
5780
5781 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5782 /// vector of type 'VT', see if the elements can be replaced by a single large
5783 /// load which has the same value as a build_vector whose operands are 'elts'.
5784 ///
5785 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5786 ///
5787 /// FIXME: we'd also like to handle the case where the last elements are zero
5788 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5789 /// There's even a handy isZeroNode for that purpose.
5790 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5791                                         SDLoc &DL, SelectionDAG &DAG,
5792                                         bool isAfterLegalize) {
5793   EVT EltVT = VT.getVectorElementType();
5794   unsigned NumElems = Elts.size();
5795
5796   LoadSDNode *LDBase = nullptr;
5797   unsigned LastLoadedElt = -1U;
5798
5799   // For each element in the initializer, see if we've found a load or an undef.
5800   // If we don't find an initial load element, or later load elements are
5801   // non-consecutive, bail out.
5802   for (unsigned i = 0; i < NumElems; ++i) {
5803     SDValue Elt = Elts[i];
5804
5805     if (!Elt.getNode() ||
5806         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5807       return SDValue();
5808     if (!LDBase) {
5809       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5810         return SDValue();
5811       LDBase = cast<LoadSDNode>(Elt.getNode());
5812       LastLoadedElt = i;
5813       continue;
5814     }
5815     if (Elt.getOpcode() == ISD::UNDEF)
5816       continue;
5817
5818     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5819     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5820       return SDValue();
5821     LastLoadedElt = i;
5822   }
5823
5824   // If we have found an entire vector of loads and undefs, then return a large
5825   // load of the entire vector width starting at the base pointer.  If we found
5826   // consecutive loads for the low half, generate a vzext_load node.
5827   if (LastLoadedElt == NumElems - 1) {
5828
5829     if (isAfterLegalize &&
5830         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5831       return SDValue();
5832
5833     SDValue NewLd = SDValue();
5834
5835     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5836       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5837                           LDBase->getPointerInfo(),
5838                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5839                           LDBase->isInvariant(), 0);
5840     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5841                         LDBase->getPointerInfo(),
5842                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5843                         LDBase->isInvariant(), LDBase->getAlignment());
5844
5845     if (LDBase->hasAnyUseOfValue(1)) {
5846       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5847                                      SDValue(LDBase, 1),
5848                                      SDValue(NewLd.getNode(), 1));
5849       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5850       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5851                              SDValue(NewLd.getNode(), 1));
5852     }
5853
5854     return NewLd;
5855   }
5856   if (NumElems == 4 && LastLoadedElt == 1 &&
5857       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5858     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5859     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5860     SDValue ResNode =
5861         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5862                                 LDBase->getPointerInfo(),
5863                                 LDBase->getAlignment(),
5864                                 false/*isVolatile*/, true/*ReadMem*/,
5865                                 false/*WriteMem*/);
5866
5867     // Make sure the newly-created LOAD is in the same position as LDBase in
5868     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5869     // update uses of LDBase's output chain to use the TokenFactor.
5870     if (LDBase->hasAnyUseOfValue(1)) {
5871       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5872                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5873       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5874       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5875                              SDValue(ResNode.getNode(), 1));
5876     }
5877
5878     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5879   }
5880   return SDValue();
5881 }
5882
5883 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5884 /// to generate a splat value for the following cases:
5885 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5886 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5887 /// a scalar load, or a constant.
5888 /// The VBROADCAST node is returned when a pattern is found,
5889 /// or SDValue() otherwise.
5890 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5891                                     SelectionDAG &DAG) {
5892   if (!Subtarget->hasFp256())
5893     return SDValue();
5894
5895   MVT VT = Op.getSimpleValueType();
5896   SDLoc dl(Op);
5897
5898   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5899          "Unsupported vector type for broadcast.");
5900
5901   SDValue Ld;
5902   bool ConstSplatVal;
5903
5904   switch (Op.getOpcode()) {
5905     default:
5906       // Unknown pattern found.
5907       return SDValue();
5908
5909     case ISD::BUILD_VECTOR: {
5910       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5911       BitVector UndefElements;
5912       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5913
5914       // We need a splat of a single value to use broadcast, and it doesn't
5915       // make any sense if the value is only in one element of the vector.
5916       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5917         return SDValue();
5918
5919       Ld = Splat;
5920       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5921                        Ld.getOpcode() == ISD::ConstantFP);
5922
5923       // Make sure that all of the users of a non-constant load are from the
5924       // BUILD_VECTOR node.
5925       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5926         return SDValue();
5927       break;
5928     }
5929
5930     case ISD::VECTOR_SHUFFLE: {
5931       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5932
5933       // Shuffles must have a splat mask where the first element is
5934       // broadcasted.
5935       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5936         return SDValue();
5937
5938       SDValue Sc = Op.getOperand(0);
5939       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5940           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5941
5942         if (!Subtarget->hasInt256())
5943           return SDValue();
5944
5945         // Use the register form of the broadcast instruction available on AVX2.
5946         if (VT.getSizeInBits() >= 256)
5947           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5948         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5949       }
5950
5951       Ld = Sc.getOperand(0);
5952       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5953                        Ld.getOpcode() == ISD::ConstantFP);
5954
5955       // The scalar_to_vector node and the suspected
5956       // load node must have exactly one user.
5957       // Constants may have multiple users.
5958
5959       // AVX-512 has register version of the broadcast
5960       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5961         Ld.getValueType().getSizeInBits() >= 32;
5962       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5963           !hasRegVer))
5964         return SDValue();
5965       break;
5966     }
5967   }
5968
5969   bool IsGE256 = (VT.getSizeInBits() >= 256);
5970
5971   // Handle the broadcasting a single constant scalar from the constant pool
5972   // into a vector. On Sandybridge it is still better to load a constant vector
5973   // from the constant pool and not to broadcast it from a scalar.
5974   if (ConstSplatVal && Subtarget->hasInt256()) {
5975     EVT CVT = Ld.getValueType();
5976     assert(!CVT.isVector() && "Must not broadcast a vector type");
5977     unsigned ScalarSize = CVT.getSizeInBits();
5978
5979     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5980       const Constant *C = nullptr;
5981       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5982         C = CI->getConstantIntValue();
5983       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5984         C = CF->getConstantFPValue();
5985
5986       assert(C && "Invalid constant type");
5987
5988       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5989       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5990       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5991       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5992                        MachinePointerInfo::getConstantPool(),
5993                        false, false, false, Alignment);
5994
5995       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5996     }
5997   }
5998
5999   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6000   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6001
6002   // Handle AVX2 in-register broadcasts.
6003   if (!IsLoad && Subtarget->hasInt256() &&
6004       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6005     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6006
6007   // The scalar source must be a normal load.
6008   if (!IsLoad)
6009     return SDValue();
6010
6011   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6012     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6013
6014   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6015   // double since there is no vbroadcastsd xmm
6016   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6017     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6018       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6019   }
6020
6021   // Unsupported broadcast.
6022   return SDValue();
6023 }
6024
6025 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6026 /// underlying vector and index.
6027 ///
6028 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6029 /// index.
6030 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6031                                          SDValue ExtIdx) {
6032   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6033   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6034     return Idx;
6035
6036   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6037   // lowered this:
6038   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6039   // to:
6040   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6041   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6042   //                           undef)
6043   //                       Constant<0>)
6044   // In this case the vector is the extract_subvector expression and the index
6045   // is 2, as specified by the shuffle.
6046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6047   SDValue ShuffleVec = SVOp->getOperand(0);
6048   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6049   assert(ShuffleVecVT.getVectorElementType() ==
6050          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6051
6052   int ShuffleIdx = SVOp->getMaskElt(Idx);
6053   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6054     ExtractedFromVec = ShuffleVec;
6055     return ShuffleIdx;
6056   }
6057   return Idx;
6058 }
6059
6060 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6061   MVT VT = Op.getSimpleValueType();
6062
6063   // Skip if insert_vec_elt is not supported.
6064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6065   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6066     return SDValue();
6067
6068   SDLoc DL(Op);
6069   unsigned NumElems = Op.getNumOperands();
6070
6071   SDValue VecIn1;
6072   SDValue VecIn2;
6073   SmallVector<unsigned, 4> InsertIndices;
6074   SmallVector<int, 8> Mask(NumElems, -1);
6075
6076   for (unsigned i = 0; i != NumElems; ++i) {
6077     unsigned Opc = Op.getOperand(i).getOpcode();
6078
6079     if (Opc == ISD::UNDEF)
6080       continue;
6081
6082     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6083       // Quit if more than 1 elements need inserting.
6084       if (InsertIndices.size() > 1)
6085         return SDValue();
6086
6087       InsertIndices.push_back(i);
6088       continue;
6089     }
6090
6091     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6092     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6093     // Quit if non-constant index.
6094     if (!isa<ConstantSDNode>(ExtIdx))
6095       return SDValue();
6096     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6097
6098     // Quit if extracted from vector of different type.
6099     if (ExtractedFromVec.getValueType() != VT)
6100       return SDValue();
6101
6102     if (!VecIn1.getNode())
6103       VecIn1 = ExtractedFromVec;
6104     else if (VecIn1 != ExtractedFromVec) {
6105       if (!VecIn2.getNode())
6106         VecIn2 = ExtractedFromVec;
6107       else if (VecIn2 != ExtractedFromVec)
6108         // Quit if more than 2 vectors to shuffle
6109         return SDValue();
6110     }
6111
6112     if (ExtractedFromVec == VecIn1)
6113       Mask[i] = Idx;
6114     else if (ExtractedFromVec == VecIn2)
6115       Mask[i] = Idx + NumElems;
6116   }
6117
6118   if (!VecIn1.getNode())
6119     return SDValue();
6120
6121   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6122   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6123   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6124     unsigned Idx = InsertIndices[i];
6125     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6126                      DAG.getIntPtrConstant(Idx));
6127   }
6128
6129   return NV;
6130 }
6131
6132 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6133 SDValue
6134 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6135
6136   MVT VT = Op.getSimpleValueType();
6137   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6138          "Unexpected type in LowerBUILD_VECTORvXi1!");
6139
6140   SDLoc dl(Op);
6141   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6142     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6143     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6144     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6145   }
6146
6147   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6148     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6149     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6150     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6151   }
6152
6153   bool AllContants = true;
6154   uint64_t Immediate = 0;
6155   int NonConstIdx = -1;
6156   bool IsSplat = true;
6157   unsigned NumNonConsts = 0;
6158   unsigned NumConsts = 0;
6159   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6160     SDValue In = Op.getOperand(idx);
6161     if (In.getOpcode() == ISD::UNDEF)
6162       continue;
6163     if (!isa<ConstantSDNode>(In)) {
6164       AllContants = false;
6165       NonConstIdx = idx;
6166       NumNonConsts++;
6167     }
6168     else {
6169       NumConsts++;
6170       if (cast<ConstantSDNode>(In)->getZExtValue())
6171       Immediate |= (1ULL << idx);
6172     }
6173     if (In != Op.getOperand(0))
6174       IsSplat = false;
6175   }
6176
6177   if (AllContants) {
6178     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6179       DAG.getConstant(Immediate, MVT::i16));
6180     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6181                        DAG.getIntPtrConstant(0));
6182   }
6183
6184   if (NumNonConsts == 1 && NonConstIdx != 0) {
6185     SDValue DstVec;
6186     if (NumConsts) {
6187       SDValue VecAsImm = DAG.getConstant(Immediate,
6188                                          MVT::getIntegerVT(VT.getSizeInBits()));
6189       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6190     }
6191     else 
6192       DstVec = DAG.getUNDEF(VT);
6193     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6194                        Op.getOperand(NonConstIdx),
6195                        DAG.getIntPtrConstant(NonConstIdx));
6196   }
6197   if (!IsSplat && (NonConstIdx != 0))
6198     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6199   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6200   SDValue Select;
6201   if (IsSplat)
6202     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6203                           DAG.getConstant(-1, SelectVT),
6204                           DAG.getConstant(0, SelectVT));
6205   else
6206     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6207                          DAG.getConstant((Immediate | 1), SelectVT),
6208                          DAG.getConstant(Immediate, SelectVT));
6209   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6210 }
6211
6212 /// \brief Return true if \p N implements a horizontal binop and return the
6213 /// operands for the horizontal binop into V0 and V1.
6214 /// 
6215 /// This is a helper function of PerformBUILD_VECTORCombine.
6216 /// This function checks that the build_vector \p N in input implements a
6217 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6218 /// operation to match.
6219 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6220 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6221 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6222 /// arithmetic sub.
6223 ///
6224 /// This function only analyzes elements of \p N whose indices are
6225 /// in range [BaseIdx, LastIdx).
6226 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6227                               SelectionDAG &DAG,
6228                               unsigned BaseIdx, unsigned LastIdx,
6229                               SDValue &V0, SDValue &V1) {
6230   EVT VT = N->getValueType(0);
6231
6232   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6233   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6234          "Invalid Vector in input!");
6235   
6236   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6237   bool CanFold = true;
6238   unsigned ExpectedVExtractIdx = BaseIdx;
6239   unsigned NumElts = LastIdx - BaseIdx;
6240   V0 = DAG.getUNDEF(VT);
6241   V1 = DAG.getUNDEF(VT);
6242
6243   // Check if N implements a horizontal binop.
6244   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6245     SDValue Op = N->getOperand(i + BaseIdx);
6246
6247     // Skip UNDEFs.
6248     if (Op->getOpcode() == ISD::UNDEF) {
6249       // Update the expected vector extract index.
6250       if (i * 2 == NumElts)
6251         ExpectedVExtractIdx = BaseIdx;
6252       ExpectedVExtractIdx += 2;
6253       continue;
6254     }
6255
6256     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6257
6258     if (!CanFold)
6259       break;
6260
6261     SDValue Op0 = Op.getOperand(0);
6262     SDValue Op1 = Op.getOperand(1);
6263
6264     // Try to match the following pattern:
6265     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6266     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6267         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6268         Op0.getOperand(0) == Op1.getOperand(0) &&
6269         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6270         isa<ConstantSDNode>(Op1.getOperand(1)));
6271     if (!CanFold)
6272       break;
6273
6274     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6275     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6276
6277     if (i * 2 < NumElts) {
6278       if (V0.getOpcode() == ISD::UNDEF)
6279         V0 = Op0.getOperand(0);
6280     } else {
6281       if (V1.getOpcode() == ISD::UNDEF)
6282         V1 = Op0.getOperand(0);
6283       if (i * 2 == NumElts)
6284         ExpectedVExtractIdx = BaseIdx;
6285     }
6286
6287     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6288     if (I0 == ExpectedVExtractIdx)
6289       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6290     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6291       // Try to match the following dag sequence:
6292       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6293       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6294     } else
6295       CanFold = false;
6296
6297     ExpectedVExtractIdx += 2;
6298   }
6299
6300   return CanFold;
6301 }
6302
6303 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6304 /// a concat_vector. 
6305 ///
6306 /// This is a helper function of PerformBUILD_VECTORCombine.
6307 /// This function expects two 256-bit vectors called V0 and V1.
6308 /// At first, each vector is split into two separate 128-bit vectors.
6309 /// Then, the resulting 128-bit vectors are used to implement two
6310 /// horizontal binary operations. 
6311 ///
6312 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6313 ///
6314 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6315 /// the two new horizontal binop.
6316 /// When Mode is set, the first horizontal binop dag node would take as input
6317 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6318 /// horizontal binop dag node would take as input the lower 128-bit of V1
6319 /// and the upper 128-bit of V1.
6320 ///   Example:
6321 ///     HADD V0_LO, V0_HI
6322 ///     HADD V1_LO, V1_HI
6323 ///
6324 /// Otherwise, the first horizontal binop dag node takes as input the lower
6325 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6326 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6327 ///   Example:
6328 ///     HADD V0_LO, V1_LO
6329 ///     HADD V0_HI, V1_HI
6330 ///
6331 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6332 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6333 /// the upper 128-bits of the result.
6334 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6335                                      SDLoc DL, SelectionDAG &DAG,
6336                                      unsigned X86Opcode, bool Mode,
6337                                      bool isUndefLO, bool isUndefHI) {
6338   EVT VT = V0.getValueType();
6339   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6340          "Invalid nodes in input!");
6341
6342   unsigned NumElts = VT.getVectorNumElements();
6343   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6344   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6345   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6346   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6347   EVT NewVT = V0_LO.getValueType();
6348
6349   SDValue LO = DAG.getUNDEF(NewVT);
6350   SDValue HI = DAG.getUNDEF(NewVT);
6351
6352   if (Mode) {
6353     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6354     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6355       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6356     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6357       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6358   } else {
6359     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6360     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6361                        V1_LO->getOpcode() != ISD::UNDEF))
6362       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6363
6364     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6365                        V1_HI->getOpcode() != ISD::UNDEF))
6366       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6367   }
6368
6369   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6370 }
6371
6372 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6373 /// sequence of 'vadd + vsub + blendi'.
6374 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6375                            const X86Subtarget *Subtarget) {
6376   SDLoc DL(BV);
6377   EVT VT = BV->getValueType(0);
6378   unsigned NumElts = VT.getVectorNumElements();
6379   SDValue InVec0 = DAG.getUNDEF(VT);
6380   SDValue InVec1 = DAG.getUNDEF(VT);
6381
6382   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6383           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6384
6385   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6386   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6387   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6388     return SDValue();
6389
6390   // Odd-numbered elements in the input build vector are obtained from
6391   // adding two integer/float elements.
6392   // Even-numbered elements in the input build vector are obtained from
6393   // subtracting two integer/float elements.
6394   unsigned ExpectedOpcode = ISD::FSUB;
6395   unsigned NextExpectedOpcode = ISD::FADD;
6396   bool AddFound = false;
6397   bool SubFound = false;
6398
6399   for (unsigned i = 0, e = NumElts; i != e; i++) {
6400     SDValue Op = BV->getOperand(i);
6401       
6402     // Skip 'undef' values.
6403     unsigned Opcode = Op.getOpcode();
6404     if (Opcode == ISD::UNDEF) {
6405       std::swap(ExpectedOpcode, NextExpectedOpcode);
6406       continue;
6407     }
6408       
6409     // Early exit if we found an unexpected opcode.
6410     if (Opcode != ExpectedOpcode)
6411       return SDValue();
6412
6413     SDValue Op0 = Op.getOperand(0);
6414     SDValue Op1 = Op.getOperand(1);
6415
6416     // Try to match the following pattern:
6417     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6418     // Early exit if we cannot match that sequence.
6419     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6420         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6421         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6422         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6423         Op0.getOperand(1) != Op1.getOperand(1))
6424       return SDValue();
6425
6426     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6427     if (I0 != i)
6428       return SDValue();
6429
6430     // We found a valid add/sub node. Update the information accordingly.
6431     if (i & 1)
6432       AddFound = true;
6433     else
6434       SubFound = true;
6435
6436     // Update InVec0 and InVec1.
6437     if (InVec0.getOpcode() == ISD::UNDEF)
6438       InVec0 = Op0.getOperand(0);
6439     if (InVec1.getOpcode() == ISD::UNDEF)
6440       InVec1 = Op1.getOperand(0);
6441
6442     // Make sure that operands in input to each add/sub node always
6443     // come from a same pair of vectors.
6444     if (InVec0 != Op0.getOperand(0)) {
6445       if (ExpectedOpcode == ISD::FSUB)
6446         return SDValue();
6447
6448       // FADD is commutable. Try to commute the operands
6449       // and then test again.
6450       std::swap(Op0, Op1);
6451       if (InVec0 != Op0.getOperand(0))
6452         return SDValue();
6453     }
6454
6455     if (InVec1 != Op1.getOperand(0))
6456       return SDValue();
6457
6458     // Update the pair of expected opcodes.
6459     std::swap(ExpectedOpcode, NextExpectedOpcode);
6460   }
6461
6462   // Don't try to fold this build_vector into a VSELECT if it has
6463   // too many UNDEF operands.
6464   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6465       InVec1.getOpcode() != ISD::UNDEF) {
6466     // Emit a sequence of vector add and sub followed by a VSELECT.
6467     // The new VSELECT will be lowered into a BLENDI.
6468     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6469     // and emit a single ADDSUB instruction.
6470     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6471     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6472
6473     // Construct the VSELECT mask.
6474     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6475     EVT SVT = MaskVT.getVectorElementType();
6476     unsigned SVTBits = SVT.getSizeInBits();
6477     SmallVector<SDValue, 8> Ops;
6478
6479     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6480       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6481                             APInt::getAllOnesValue(SVTBits);
6482       SDValue Constant = DAG.getConstant(Value, SVT);
6483       Ops.push_back(Constant);
6484     }
6485
6486     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6487     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6488   }
6489   
6490   return SDValue();
6491 }
6492
6493 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6494                                           const X86Subtarget *Subtarget) {
6495   SDLoc DL(N);
6496   EVT VT = N->getValueType(0);
6497   unsigned NumElts = VT.getVectorNumElements();
6498   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6499   SDValue InVec0, InVec1;
6500
6501   // Try to match an ADDSUB.
6502   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6503       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6504     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6505     if (Value.getNode())
6506       return Value;
6507   }
6508
6509   // Try to match horizontal ADD/SUB.
6510   unsigned NumUndefsLO = 0;
6511   unsigned NumUndefsHI = 0;
6512   unsigned Half = NumElts/2;
6513
6514   // Count the number of UNDEF operands in the build_vector in input.
6515   for (unsigned i = 0, e = Half; i != e; ++i)
6516     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6517       NumUndefsLO++;
6518
6519   for (unsigned i = Half, e = NumElts; i != e; ++i)
6520     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6521       NumUndefsHI++;
6522
6523   // Early exit if this is either a build_vector of all UNDEFs or all the
6524   // operands but one are UNDEF.
6525   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6526     return SDValue();
6527
6528   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6529     // Try to match an SSE3 float HADD/HSUB.
6530     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6531       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6532     
6533     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6534       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6535   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6536     // Try to match an SSSE3 integer HADD/HSUB.
6537     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6538       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6539     
6540     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6541       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6542   }
6543   
6544   if (!Subtarget->hasAVX())
6545     return SDValue();
6546
6547   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6548     // Try to match an AVX horizontal add/sub of packed single/double
6549     // precision floating point values from 256-bit vectors.
6550     SDValue InVec2, InVec3;
6551     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6552         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6553         ((InVec0.getOpcode() == ISD::UNDEF ||
6554           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6555         ((InVec1.getOpcode() == ISD::UNDEF ||
6556           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6557       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6558
6559     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6560         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6561         ((InVec0.getOpcode() == ISD::UNDEF ||
6562           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6563         ((InVec1.getOpcode() == ISD::UNDEF ||
6564           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6565       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6566   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6567     // Try to match an AVX2 horizontal add/sub of signed integers.
6568     SDValue InVec2, InVec3;
6569     unsigned X86Opcode;
6570     bool CanFold = true;
6571
6572     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6573         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6574         ((InVec0.getOpcode() == ISD::UNDEF ||
6575           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6576         ((InVec1.getOpcode() == ISD::UNDEF ||
6577           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6578       X86Opcode = X86ISD::HADD;
6579     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6580         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6581         ((InVec0.getOpcode() == ISD::UNDEF ||
6582           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6583         ((InVec1.getOpcode() == ISD::UNDEF ||
6584           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6585       X86Opcode = X86ISD::HSUB;
6586     else
6587       CanFold = false;
6588
6589     if (CanFold) {
6590       // Fold this build_vector into a single horizontal add/sub.
6591       // Do this only if the target has AVX2.
6592       if (Subtarget->hasAVX2())
6593         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6594  
6595       // Do not try to expand this build_vector into a pair of horizontal
6596       // add/sub if we can emit a pair of scalar add/sub.
6597       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6598         return SDValue();
6599
6600       // Convert this build_vector into a pair of horizontal binop followed by
6601       // a concat vector.
6602       bool isUndefLO = NumUndefsLO == Half;
6603       bool isUndefHI = NumUndefsHI == Half;
6604       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6605                                    isUndefLO, isUndefHI);
6606     }
6607   }
6608
6609   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6610        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6611     unsigned X86Opcode;
6612     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6613       X86Opcode = X86ISD::HADD;
6614     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6615       X86Opcode = X86ISD::HSUB;
6616     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6617       X86Opcode = X86ISD::FHADD;
6618     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6619       X86Opcode = X86ISD::FHSUB;
6620     else
6621       return SDValue();
6622
6623     // Don't try to expand this build_vector into a pair of horizontal add/sub
6624     // if we can simply emit a pair of scalar add/sub.
6625     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6626       return SDValue();
6627
6628     // Convert this build_vector into two horizontal add/sub followed by
6629     // a concat vector.
6630     bool isUndefLO = NumUndefsLO == Half;
6631     bool isUndefHI = NumUndefsHI == Half;
6632     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6633                                  isUndefLO, isUndefHI);
6634   }
6635
6636   return SDValue();
6637 }
6638
6639 SDValue
6640 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6641   SDLoc dl(Op);
6642
6643   MVT VT = Op.getSimpleValueType();
6644   MVT ExtVT = VT.getVectorElementType();
6645   unsigned NumElems = Op.getNumOperands();
6646
6647   // Generate vectors for predicate vectors.
6648   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6649     return LowerBUILD_VECTORvXi1(Op, DAG);
6650
6651   // Vectors containing all zeros can be matched by pxor and xorps later
6652   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6653     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6654     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6655     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6656       return Op;
6657
6658     return getZeroVector(VT, Subtarget, DAG, dl);
6659   }
6660
6661   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6662   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6663   // vpcmpeqd on 256-bit vectors.
6664   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6665     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6666       return Op;
6667
6668     if (!VT.is512BitVector())
6669       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6670   }
6671
6672   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6673   if (Broadcast.getNode())
6674     return Broadcast;
6675
6676   unsigned EVTBits = ExtVT.getSizeInBits();
6677
6678   unsigned NumZero  = 0;
6679   unsigned NumNonZero = 0;
6680   unsigned NonZeros = 0;
6681   bool IsAllConstants = true;
6682   SmallSet<SDValue, 8> Values;
6683   for (unsigned i = 0; i < NumElems; ++i) {
6684     SDValue Elt = Op.getOperand(i);
6685     if (Elt.getOpcode() == ISD::UNDEF)
6686       continue;
6687     Values.insert(Elt);
6688     if (Elt.getOpcode() != ISD::Constant &&
6689         Elt.getOpcode() != ISD::ConstantFP)
6690       IsAllConstants = false;
6691     if (X86::isZeroNode(Elt))
6692       NumZero++;
6693     else {
6694       NonZeros |= (1 << i);
6695       NumNonZero++;
6696     }
6697   }
6698
6699   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6700   if (NumNonZero == 0)
6701     return DAG.getUNDEF(VT);
6702
6703   // Special case for single non-zero, non-undef, element.
6704   if (NumNonZero == 1) {
6705     unsigned Idx = countTrailingZeros(NonZeros);
6706     SDValue Item = Op.getOperand(Idx);
6707
6708     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6709     // the value are obviously zero, truncate the value to i32 and do the
6710     // insertion that way.  Only do this if the value is non-constant or if the
6711     // value is a constant being inserted into element 0.  It is cheaper to do
6712     // a constant pool load than it is to do a movd + shuffle.
6713     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6714         (!IsAllConstants || Idx == 0)) {
6715       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6716         // Handle SSE only.
6717         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6718         EVT VecVT = MVT::v4i32;
6719         unsigned VecElts = 4;
6720
6721         // Truncate the value (which may itself be a constant) to i32, and
6722         // convert it to a vector with movd (S2V+shuffle to zero extend).
6723         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6724         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6725         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6726
6727         // Now we have our 32-bit value zero extended in the low element of
6728         // a vector.  If Idx != 0, swizzle it into place.
6729         if (Idx != 0) {
6730           SmallVector<int, 4> Mask;
6731           Mask.push_back(Idx);
6732           for (unsigned i = 1; i != VecElts; ++i)
6733             Mask.push_back(i);
6734           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6735                                       &Mask[0]);
6736         }
6737         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6738       }
6739     }
6740
6741     // If we have a constant or non-constant insertion into the low element of
6742     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6743     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6744     // depending on what the source datatype is.
6745     if (Idx == 0) {
6746       if (NumZero == 0)
6747         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6748
6749       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6750           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6751         if (VT.is256BitVector() || VT.is512BitVector()) {
6752           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6753           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6754                              Item, DAG.getIntPtrConstant(0));
6755         }
6756         assert(VT.is128BitVector() && "Expected an SSE value type!");
6757         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6758         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6759         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6760       }
6761
6762       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6763         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6764         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6765         if (VT.is256BitVector()) {
6766           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6767           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6768         } else {
6769           assert(VT.is128BitVector() && "Expected an SSE value type!");
6770           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6771         }
6772         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6773       }
6774     }
6775
6776     // Is it a vector logical left shift?
6777     if (NumElems == 2 && Idx == 1 &&
6778         X86::isZeroNode(Op.getOperand(0)) &&
6779         !X86::isZeroNode(Op.getOperand(1))) {
6780       unsigned NumBits = VT.getSizeInBits();
6781       return getVShift(true, VT,
6782                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6783                                    VT, Op.getOperand(1)),
6784                        NumBits/2, DAG, *this, dl);
6785     }
6786
6787     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6788       return SDValue();
6789
6790     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6791     // is a non-constant being inserted into an element other than the low one,
6792     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6793     // movd/movss) to move this into the low element, then shuffle it into
6794     // place.
6795     if (EVTBits == 32) {
6796       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6797
6798       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6799       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6800       SmallVector<int, 8> MaskVec;
6801       for (unsigned i = 0; i != NumElems; ++i)
6802         MaskVec.push_back(i == Idx ? 0 : 1);
6803       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6804     }
6805   }
6806
6807   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6808   if (Values.size() == 1) {
6809     if (EVTBits == 32) {
6810       // Instead of a shuffle like this:
6811       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6812       // Check if it's possible to issue this instead.
6813       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6814       unsigned Idx = countTrailingZeros(NonZeros);
6815       SDValue Item = Op.getOperand(Idx);
6816       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6817         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6818     }
6819     return SDValue();
6820   }
6821
6822   // A vector full of immediates; various special cases are already
6823   // handled, so this is best done with a single constant-pool load.
6824   if (IsAllConstants)
6825     return SDValue();
6826
6827   // For AVX-length vectors, build the individual 128-bit pieces and use
6828   // shuffles to put them in place.
6829   if (VT.is256BitVector() || VT.is512BitVector()) {
6830     SmallVector<SDValue, 64> V;
6831     for (unsigned i = 0; i != NumElems; ++i)
6832       V.push_back(Op.getOperand(i));
6833
6834     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6835
6836     // Build both the lower and upper subvector.
6837     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6838                                 makeArrayRef(&V[0], NumElems/2));
6839     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6840                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6841
6842     // Recreate the wider vector with the lower and upper part.
6843     if (VT.is256BitVector())
6844       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6845     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6846   }
6847
6848   // Let legalizer expand 2-wide build_vectors.
6849   if (EVTBits == 64) {
6850     if (NumNonZero == 1) {
6851       // One half is zero or undef.
6852       unsigned Idx = countTrailingZeros(NonZeros);
6853       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6854                                  Op.getOperand(Idx));
6855       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6856     }
6857     return SDValue();
6858   }
6859
6860   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6861   if (EVTBits == 8 && NumElems == 16) {
6862     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6863                                         Subtarget, *this);
6864     if (V.getNode()) return V;
6865   }
6866
6867   if (EVTBits == 16 && NumElems == 8) {
6868     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6869                                       Subtarget, *this);
6870     if (V.getNode()) return V;
6871   }
6872
6873   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6874   if (EVTBits == 32 && NumElems == 4) {
6875     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6876                                       NumZero, DAG, Subtarget, *this);
6877     if (V.getNode())
6878       return V;
6879   }
6880
6881   // If element VT is == 32 bits, turn it into a number of shuffles.
6882   SmallVector<SDValue, 8> V(NumElems);
6883   if (NumElems == 4 && NumZero > 0) {
6884     for (unsigned i = 0; i < 4; ++i) {
6885       bool isZero = !(NonZeros & (1 << i));
6886       if (isZero)
6887         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6888       else
6889         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6890     }
6891
6892     for (unsigned i = 0; i < 2; ++i) {
6893       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6894         default: break;
6895         case 0:
6896           V[i] = V[i*2];  // Must be a zero vector.
6897           break;
6898         case 1:
6899           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6900           break;
6901         case 2:
6902           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6903           break;
6904         case 3:
6905           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6906           break;
6907       }
6908     }
6909
6910     bool Reverse1 = (NonZeros & 0x3) == 2;
6911     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6912     int MaskVec[] = {
6913       Reverse1 ? 1 : 0,
6914       Reverse1 ? 0 : 1,
6915       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6916       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6917     };
6918     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6919   }
6920
6921   if (Values.size() > 1 && VT.is128BitVector()) {
6922     // Check for a build vector of consecutive loads.
6923     for (unsigned i = 0; i < NumElems; ++i)
6924       V[i] = Op.getOperand(i);
6925
6926     // Check for elements which are consecutive loads.
6927     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6928     if (LD.getNode())
6929       return LD;
6930
6931     // Check for a build vector from mostly shuffle plus few inserting.
6932     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6933     if (Sh.getNode())
6934       return Sh;
6935
6936     // For SSE 4.1, use insertps to put the high elements into the low element.
6937     if (getSubtarget()->hasSSE41()) {
6938       SDValue Result;
6939       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6940         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6941       else
6942         Result = DAG.getUNDEF(VT);
6943
6944       for (unsigned i = 1; i < NumElems; ++i) {
6945         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6946         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6947                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6948       }
6949       return Result;
6950     }
6951
6952     // Otherwise, expand into a number of unpckl*, start by extending each of
6953     // our (non-undef) elements to the full vector width with the element in the
6954     // bottom slot of the vector (which generates no code for SSE).
6955     for (unsigned i = 0; i < NumElems; ++i) {
6956       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6957         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6958       else
6959         V[i] = DAG.getUNDEF(VT);
6960     }
6961
6962     // Next, we iteratively mix elements, e.g. for v4f32:
6963     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6964     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6965     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6966     unsigned EltStride = NumElems >> 1;
6967     while (EltStride != 0) {
6968       for (unsigned i = 0; i < EltStride; ++i) {
6969         // If V[i+EltStride] is undef and this is the first round of mixing,
6970         // then it is safe to just drop this shuffle: V[i] is already in the
6971         // right place, the one element (since it's the first round) being
6972         // inserted as undef can be dropped.  This isn't safe for successive
6973         // rounds because they will permute elements within both vectors.
6974         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6975             EltStride == NumElems/2)
6976           continue;
6977
6978         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6979       }
6980       EltStride >>= 1;
6981     }
6982     return V[0];
6983   }
6984   return SDValue();
6985 }
6986
6987 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6988 // to create 256-bit vectors from two other 128-bit ones.
6989 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6990   SDLoc dl(Op);
6991   MVT ResVT = Op.getSimpleValueType();
6992
6993   assert((ResVT.is256BitVector() ||
6994           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6995
6996   SDValue V1 = Op.getOperand(0);
6997   SDValue V2 = Op.getOperand(1);
6998   unsigned NumElems = ResVT.getVectorNumElements();
6999   if(ResVT.is256BitVector())
7000     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7001
7002   if (Op.getNumOperands() == 4) {
7003     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7004                                 ResVT.getVectorNumElements()/2);
7005     SDValue V3 = Op.getOperand(2);
7006     SDValue V4 = Op.getOperand(3);
7007     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7008       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7009   }
7010   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7011 }
7012
7013 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7014   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7015   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7016          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7017           Op.getNumOperands() == 4)));
7018
7019   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7020   // from two other 128-bit ones.
7021
7022   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7023   return LowerAVXCONCAT_VECTORS(Op, DAG);
7024 }
7025
7026
7027 //===----------------------------------------------------------------------===//
7028 // Vector shuffle lowering
7029 //
7030 // This is an experimental code path for lowering vector shuffles on x86. It is
7031 // designed to handle arbitrary vector shuffles and blends, gracefully
7032 // degrading performance as necessary. It works hard to recognize idiomatic
7033 // shuffles and lower them to optimal instruction patterns without leaving
7034 // a framework that allows reasonably efficient handling of all vector shuffle
7035 // patterns.
7036 //===----------------------------------------------------------------------===//
7037
7038 /// \brief Tiny helper function to identify a no-op mask.
7039 ///
7040 /// This is a somewhat boring predicate function. It checks whether the mask
7041 /// array input, which is assumed to be a single-input shuffle mask of the kind
7042 /// used by the X86 shuffle instructions (not a fully general
7043 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7044 /// in-place shuffle are 'no-op's.
7045 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7046   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7047     if (Mask[i] != -1 && Mask[i] != i)
7048       return false;
7049   return true;
7050 }
7051
7052 /// \brief Helper function to classify a mask as a single-input mask.
7053 ///
7054 /// This isn't a generic single-input test because in the vector shuffle
7055 /// lowering we canonicalize single inputs to be the first input operand. This
7056 /// means we can more quickly test for a single input by only checking whether
7057 /// an input from the second operand exists. We also assume that the size of
7058 /// mask corresponds to the size of the input vectors which isn't true in the
7059 /// fully general case.
7060 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7061   for (int M : Mask)
7062     if (M >= (int)Mask.size())
7063       return false;
7064   return true;
7065 }
7066
7067 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7068 // 2013 will allow us to use it as a non-type template parameter.
7069 namespace {
7070
7071 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7072 ///
7073 /// See its documentation for details.
7074 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7075   if (Mask.size() != Args.size())
7076     return false;
7077   for (int i = 0, e = Mask.size(); i < e; ++i) {
7078     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7079     assert(*Args[i] < (int)Args.size() * 2 &&
7080            "Argument outside the range of possible shuffle inputs!");
7081     if (Mask[i] != -1 && Mask[i] != *Args[i])
7082       return false;
7083   }
7084   return true;
7085 }
7086
7087 } // namespace
7088
7089 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7090 /// arguments.
7091 ///
7092 /// This is a fast way to test a shuffle mask against a fixed pattern:
7093 ///
7094 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7095 ///
7096 /// It returns true if the mask is exactly as wide as the argument list, and
7097 /// each element of the mask is either -1 (signifying undef) or the value given
7098 /// in the argument.
7099 static const VariadicFunction1<
7100     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7101
7102 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7103 ///
7104 /// This helper function produces an 8-bit shuffle immediate corresponding to
7105 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7106 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7107 /// example.
7108 ///
7109 /// NB: We rely heavily on "undef" masks preserving the input lane.
7110 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7111                                           SelectionDAG &DAG) {
7112   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7113   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7114   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7115   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7116   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7117
7118   unsigned Imm = 0;
7119   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7120   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7121   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7122   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7123   return DAG.getConstant(Imm, MVT::i8);
7124 }
7125
7126 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7127 ///
7128 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7129 /// support for floating point shuffles but not integer shuffles. These
7130 /// instructions will incur a domain crossing penalty on some chips though so
7131 /// it is better to avoid lowering through this for integer vectors where
7132 /// possible.
7133 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7134                                        const X86Subtarget *Subtarget,
7135                                        SelectionDAG &DAG) {
7136   SDLoc DL(Op);
7137   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7138   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7139   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7140   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7141   ArrayRef<int> Mask = SVOp->getMask();
7142   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7143
7144   if (isSingleInputShuffleMask(Mask)) {
7145     // Straight shuffle of a single input vector. Simulate this by using the
7146     // single input as both of the "inputs" to this instruction..
7147     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7148     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7149                        DAG.getConstant(SHUFPDMask, MVT::i8));
7150   }
7151   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7152   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7153
7154   // Use dedicated unpack instructions for masks that match their pattern.
7155   if (isShuffleEquivalent(Mask, 0, 2))
7156     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7157   if (isShuffleEquivalent(Mask, 1, 3))
7158     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7159
7160   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7161   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7162                      DAG.getConstant(SHUFPDMask, MVT::i8));
7163 }
7164
7165 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7166 ///
7167 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7168 /// the integer unit to minimize domain crossing penalties. However, for blends
7169 /// it falls back to the floating point shuffle operation with appropriate bit
7170 /// casting.
7171 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7172                                        const X86Subtarget *Subtarget,
7173                                        SelectionDAG &DAG) {
7174   SDLoc DL(Op);
7175   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7176   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7177   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7178   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7179   ArrayRef<int> Mask = SVOp->getMask();
7180   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7181
7182   if (isSingleInputShuffleMask(Mask)) {
7183     // Straight shuffle of a single input vector. For everything from SSE2
7184     // onward this has a single fast instruction with no scary immediates.
7185     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7186     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7187     int WidenedMask[4] = {
7188         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7189         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7190     return DAG.getNode(
7191         ISD::BITCAST, DL, MVT::v2i64,
7192         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7193                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7194   }
7195
7196   // Use dedicated unpack instructions for masks that match their pattern.
7197   if (isShuffleEquivalent(Mask, 0, 2))
7198     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7199   if (isShuffleEquivalent(Mask, 1, 3))
7200     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7201
7202   // We implement this with SHUFPD which is pretty lame because it will likely
7203   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7204   // However, all the alternatives are still more cycles and newer chips don't
7205   // have this problem. It would be really nice if x86 had better shuffles here.
7206   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7207   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7208   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7209                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7210 }
7211
7212 /// \brief Lower 4-lane 32-bit floating point shuffles.
7213 ///
7214 /// Uses instructions exclusively from the floating point unit to minimize
7215 /// domain crossing penalties, as these are sufficient to implement all v4f32
7216 /// shuffles.
7217 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7218                                        const X86Subtarget *Subtarget,
7219                                        SelectionDAG &DAG) {
7220   SDLoc DL(Op);
7221   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7222   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7223   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7224   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7225   ArrayRef<int> Mask = SVOp->getMask();
7226   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7227
7228   SDValue LowV = V1, HighV = V2;
7229   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7230
7231   int NumV2Elements =
7232       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7233
7234   if (NumV2Elements == 0)
7235     // Straight shuffle of a single input vector. We pass the input vector to
7236     // both operands to simulate this with a SHUFPS.
7237     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7238                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7239
7240   // Use dedicated unpack instructions for masks that match their pattern.
7241   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7242     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7243   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7244     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7245
7246   if (NumV2Elements == 1) {
7247     int V2Index =
7248         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7249         Mask.begin();
7250     // Compute the index adjacent to V2Index and in the same half by toggling
7251     // the low bit.
7252     int V2AdjIndex = V2Index ^ 1;
7253
7254     if (Mask[V2AdjIndex] == -1) {
7255       // Handles all the cases where we have a single V2 element and an undef.
7256       // This will only ever happen in the high lanes because we commute the
7257       // vector otherwise.
7258       if (V2Index < 2)
7259         std::swap(LowV, HighV);
7260       NewMask[V2Index] -= 4;
7261     } else {
7262       // Handle the case where the V2 element ends up adjacent to a V1 element.
7263       // To make this work, blend them together as the first step.
7264       int V1Index = V2AdjIndex;
7265       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7266       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7267                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7268
7269       // Now proceed to reconstruct the final blend as we have the necessary
7270       // high or low half formed.
7271       if (V2Index < 2) {
7272         LowV = V2;
7273         HighV = V1;
7274       } else {
7275         HighV = V2;
7276       }
7277       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7278       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7279     }
7280   } else if (NumV2Elements == 2) {
7281     if (Mask[0] < 4 && Mask[1] < 4) {
7282       // Handle the easy case where we have V1 in the low lanes and V2 in the
7283       // high lanes. We never see this reversed because we sort the shuffle.
7284       NewMask[2] -= 4;
7285       NewMask[3] -= 4;
7286     } else {
7287       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7288       // trying to place elements directly, just blend them and set up the final
7289       // shuffle to place them.
7290
7291       // The first two blend mask elements are for V1, the second two are for
7292       // V2.
7293       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7294                           Mask[2] < 4 ? Mask[2] : Mask[3],
7295                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7296                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7297       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7298                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7299
7300       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7301       // a blend.
7302       LowV = HighV = V1;
7303       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7304       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7305       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7306       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7307     }
7308   }
7309   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7310                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7311 }
7312
7313 /// \brief Lower 4-lane i32 vector shuffles.
7314 ///
7315 /// We try to handle these with integer-domain shuffles where we can, but for
7316 /// blends we use the floating point domain blend instructions.
7317 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7318                                        const X86Subtarget *Subtarget,
7319                                        SelectionDAG &DAG) {
7320   SDLoc DL(Op);
7321   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7322   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7323   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7324   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7325   ArrayRef<int> Mask = SVOp->getMask();
7326   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7327
7328   if (isSingleInputShuffleMask(Mask))
7329     // Straight shuffle of a single input vector. For everything from SSE2
7330     // onward this has a single fast instruction with no scary immediates.
7331     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7332                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7333
7334   // Use dedicated unpack instructions for masks that match their pattern.
7335   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7336     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7337   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7338     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7339
7340   // We implement this with SHUFPS because it can blend from two vectors.
7341   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7342   // up the inputs, bypassing domain shift penalties that we would encur if we
7343   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7344   // relevant.
7345   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7346                      DAG.getVectorShuffle(
7347                          MVT::v4f32, DL,
7348                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7349                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7350 }
7351
7352 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7353 /// shuffle lowering, and the most complex part.
7354 ///
7355 /// The lowering strategy is to try to form pairs of input lanes which are
7356 /// targeted at the same half of the final vector, and then use a dword shuffle
7357 /// to place them onto the right half, and finally unpack the paired lanes into
7358 /// their final position.
7359 ///
7360 /// The exact breakdown of how to form these dword pairs and align them on the
7361 /// correct sides is really tricky. See the comments within the function for
7362 /// more of the details.
7363 static SDValue lowerV8I16SingleInputVectorShuffle(
7364     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7365     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7366   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7367   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7368   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7369
7370   SmallVector<int, 4> LoInputs;
7371   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7372                [](int M) { return M >= 0; });
7373   std::sort(LoInputs.begin(), LoInputs.end());
7374   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7375   SmallVector<int, 4> HiInputs;
7376   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7377                [](int M) { return M >= 0; });
7378   std::sort(HiInputs.begin(), HiInputs.end());
7379   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7380   int NumLToL =
7381       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7382   int NumHToL = LoInputs.size() - NumLToL;
7383   int NumLToH =
7384       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7385   int NumHToH = HiInputs.size() - NumLToH;
7386   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7387   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7388   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7389   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7390
7391   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7392   // such inputs we can swap two of the dwords across the half mark and end up
7393   // with <=2 inputs to each half in each half. Once there, we can fall through
7394   // to the generic code below. For example:
7395   //
7396   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7397   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7398   //
7399   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7400   // and an existing 2-into-2 on the other half. In this case we may have to
7401   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7402   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7403   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7404   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7405   // half than the one we target for fixing) will be fixed when we re-enter this
7406   // path. We will also combine away any sequence of PSHUFD instructions that
7407   // result into a single instruction. Here is an example of the tricky case:
7408   //
7409   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7410   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7411   //
7412   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7413   //
7414   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7415   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7416   //
7417   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7418   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7419   //
7420   // The result is fine to be handled by the generic logic.
7421   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7422                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7423                           int AOffset, int BOffset) {
7424     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7425            "Must call this with A having 3 or 1 inputs from the A half.");
7426     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7427            "Must call this with B having 1 or 3 inputs from the B half.");
7428     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7429            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7430
7431     // Compute the index of dword with only one word among the three inputs in
7432     // a half by taking the sum of the half with three inputs and subtracting
7433     // the sum of the actual three inputs. The difference is the remaining
7434     // slot.
7435     int ADWord, BDWord;
7436     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7437     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7438     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7439     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7440     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7441     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7442     int TripleNonInputIdx =
7443         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7444     TripleDWord = TripleNonInputIdx / 2;
7445
7446     // We use xor with one to compute the adjacent DWord to whichever one the
7447     // OneInput is in.
7448     OneInputDWord = (OneInput / 2) ^ 1;
7449
7450     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7451     // and BToA inputs. If there is also such a problem with the BToB and AToB
7452     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7453     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7454     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7455     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7456       // Compute how many inputs will be flipped by swapping these DWords. We
7457       // need
7458       // to balance this to ensure we don't form a 3-1 shuffle in the other
7459       // half.
7460       int NumFlippedAToBInputs =
7461           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7462           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7463       int NumFlippedBToBInputs =
7464           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7465           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7466       if ((NumFlippedAToBInputs == 1 &&
7467            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7468           (NumFlippedBToBInputs == 1 &&
7469            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7470         // We choose whether to fix the A half or B half based on whether that
7471         // half has zero flipped inputs. At zero, we may not be able to fix it
7472         // with that half. We also bias towards fixing the B half because that
7473         // will more commonly be the high half, and we have to bias one way.
7474         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7475                                                        ArrayRef<int> Inputs) {
7476           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7477           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7478                                          PinnedIdx ^ 1) != Inputs.end();
7479           // Determine whether the free index is in the flipped dword or the
7480           // unflipped dword based on where the pinned index is. We use this bit
7481           // in an xor to conditionally select the adjacent dword.
7482           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7483           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7484                                              FixFreeIdx) != Inputs.end();
7485           if (IsFixIdxInput == IsFixFreeIdxInput)
7486             FixFreeIdx += 1;
7487           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7488                                         FixFreeIdx) != Inputs.end();
7489           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7490                  "We need to be changing the number of flipped inputs!");
7491           int PSHUFHalfMask[] = {0, 1, 2, 3};
7492           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7493           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7494                           MVT::v8i16, V,
7495                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7496
7497           for (int &M : Mask)
7498             if (M != -1 && M == FixIdx)
7499               M = FixFreeIdx;
7500             else if (M != -1 && M == FixFreeIdx)
7501               M = FixIdx;
7502         };
7503         if (NumFlippedBToBInputs != 0) {
7504           int BPinnedIdx =
7505               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7506           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7507         } else {
7508           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7509           int APinnedIdx =
7510               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7511           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7512         }
7513       }
7514     }
7515
7516     int PSHUFDMask[] = {0, 1, 2, 3};
7517     PSHUFDMask[ADWord] = BDWord;
7518     PSHUFDMask[BDWord] = ADWord;
7519     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7520                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7521                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7522                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7523
7524     // Adjust the mask to match the new locations of A and B.
7525     for (int &M : Mask)
7526       if (M != -1 && M/2 == ADWord)
7527         M = 2 * BDWord + M % 2;
7528       else if (M != -1 && M/2 == BDWord)
7529         M = 2 * ADWord + M % 2;
7530
7531     // Recurse back into this routine to re-compute state now that this isn't
7532     // a 3 and 1 problem.
7533     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7534                                 Mask);
7535   };
7536   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7537     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7538   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7539     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7540
7541   // At this point there are at most two inputs to the low and high halves from
7542   // each half. That means the inputs can always be grouped into dwords and
7543   // those dwords can then be moved to the correct half with a dword shuffle.
7544   // We use at most one low and one high word shuffle to collect these paired
7545   // inputs into dwords, and finally a dword shuffle to place them.
7546   int PSHUFLMask[4] = {-1, -1, -1, -1};
7547   int PSHUFHMask[4] = {-1, -1, -1, -1};
7548   int PSHUFDMask[4] = {-1, -1, -1, -1};
7549
7550   // First fix the masks for all the inputs that are staying in their
7551   // original halves. This will then dictate the targets of the cross-half
7552   // shuffles.
7553   auto fixInPlaceInputs =
7554       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7555                     MutableArrayRef<int> SourceHalfMask,
7556                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7557     if (InPlaceInputs.empty())
7558       return;
7559     if (InPlaceInputs.size() == 1) {
7560       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7561           InPlaceInputs[0] - HalfOffset;
7562       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7563       return;
7564     }
7565     if (IncomingInputs.empty()) {
7566       // Just fix all of the in place inputs.
7567       for (int Input : InPlaceInputs) {
7568         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7569         PSHUFDMask[Input / 2] = Input / 2;
7570       }
7571       return;
7572     }
7573
7574     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7575     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7576         InPlaceInputs[0] - HalfOffset;
7577     // Put the second input next to the first so that they are packed into
7578     // a dword. We find the adjacent index by toggling the low bit.
7579     int AdjIndex = InPlaceInputs[0] ^ 1;
7580     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7581     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7582     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7583   };
7584   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7585   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7586
7587   // Now gather the cross-half inputs and place them into a free dword of
7588   // their target half.
7589   // FIXME: This operation could almost certainly be simplified dramatically to
7590   // look more like the 3-1 fixing operation.
7591   auto moveInputsToRightHalf = [&PSHUFDMask](
7592       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7593       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7594       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7595       int DestOffset) {
7596     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7597       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7598     };
7599     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7600                                                int Word) {
7601       int LowWord = Word & ~1;
7602       int HighWord = Word | 1;
7603       return isWordClobbered(SourceHalfMask, LowWord) ||
7604              isWordClobbered(SourceHalfMask, HighWord);
7605     };
7606
7607     if (IncomingInputs.empty())
7608       return;
7609
7610     if (ExistingInputs.empty()) {
7611       // Map any dwords with inputs from them into the right half.
7612       for (int Input : IncomingInputs) {
7613         // If the source half mask maps over the inputs, turn those into
7614         // swaps and use the swapped lane.
7615         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7616           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7617             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7618                 Input - SourceOffset;
7619             // We have to swap the uses in our half mask in one sweep.
7620             for (int &M : HalfMask)
7621               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7622                 M = Input;
7623               else if (M == Input)
7624                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7625           } else {
7626             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7627                        Input - SourceOffset &&
7628                    "Previous placement doesn't match!");
7629           }
7630           // Note that this correctly re-maps both when we do a swap and when
7631           // we observe the other side of the swap above. We rely on that to
7632           // avoid swapping the members of the input list directly.
7633           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7634         }
7635
7636         // Map the input's dword into the correct half.
7637         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7638           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7639         else
7640           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7641                      Input / 2 &&
7642                  "Previous placement doesn't match!");
7643       }
7644
7645       // And just directly shift any other-half mask elements to be same-half
7646       // as we will have mirrored the dword containing the element into the
7647       // same position within that half.
7648       for (int &M : HalfMask)
7649         if (M >= SourceOffset && M < SourceOffset + 4) {
7650           M = M - SourceOffset + DestOffset;
7651           assert(M >= 0 && "This should never wrap below zero!");
7652         }
7653       return;
7654     }
7655
7656     // Ensure we have the input in a viable dword of its current half. This
7657     // is particularly tricky because the original position may be clobbered
7658     // by inputs being moved and *staying* in that half.
7659     if (IncomingInputs.size() == 1) {
7660       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7661         int InputFixed = std::find(std::begin(SourceHalfMask),
7662                                    std::end(SourceHalfMask), -1) -
7663                          std::begin(SourceHalfMask) + SourceOffset;
7664         SourceHalfMask[InputFixed - SourceOffset] =
7665             IncomingInputs[0] - SourceOffset;
7666         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7667                      InputFixed);
7668         IncomingInputs[0] = InputFixed;
7669       }
7670     } else if (IncomingInputs.size() == 2) {
7671       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7672           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7673         // We have two non-adjacent or clobbered inputs we need to extract from
7674         // the source half. To do this, we need to map them into some adjacent
7675         // dword slot in the source mask.
7676         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7677                               IncomingInputs[1] - SourceOffset};
7678
7679         // If there is a free slot in the source half mask adjacent to one of
7680         // the inputs, place the other input in it. We use (Index XOR 1) to
7681         // compute an adjacent index.
7682         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7683             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7684           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7685           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7686           InputsFixed[1] = InputsFixed[0] ^ 1;
7687         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7688                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7689           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7690           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7691           InputsFixed[0] = InputsFixed[1] ^ 1;
7692         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7693                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7694           // The two inputs are in the same DWord but it is clobbered and the
7695           // adjacent DWord isn't used at all. Move both inputs to the free
7696           // slot.
7697           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7698           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7699           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7700           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7701         } else {
7702           // The only way we hit this point is if there is no clobbering
7703           // (because there are no off-half inputs to this half) and there is no
7704           // free slot adjacent to one of the inputs. In this case, we have to
7705           // swap an input with a non-input.
7706           for (int i = 0; i < 4; ++i)
7707             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7708                    "We can't handle any clobbers here!");
7709           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7710                  "Cannot have adjacent inputs here!");
7711
7712           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7713           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7714
7715           // We also have to update the final source mask in this case because
7716           // it may need to undo the above swap.
7717           for (int &M : FinalSourceHalfMask)
7718             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7719               M = InputsFixed[1] + SourceOffset;
7720             else if (M == InputsFixed[1] + SourceOffset)
7721               M = (InputsFixed[0] ^ 1) + SourceOffset;
7722
7723           InputsFixed[1] = InputsFixed[0] ^ 1;
7724         }
7725
7726         // Point everything at the fixed inputs.
7727         for (int &M : HalfMask)
7728           if (M == IncomingInputs[0])
7729             M = InputsFixed[0] + SourceOffset;
7730           else if (M == IncomingInputs[1])
7731             M = InputsFixed[1] + SourceOffset;
7732
7733         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7734         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7735       }
7736     } else {
7737       llvm_unreachable("Unhandled input size!");
7738     }
7739
7740     // Now hoist the DWord down to the right half.
7741     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7742     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7743     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7744     for (int &M : HalfMask)
7745       for (int Input : IncomingInputs)
7746         if (M == Input)
7747           M = FreeDWord * 2 + Input % 2;
7748   };
7749   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7750                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7751   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7752                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7753
7754   // Now enact all the shuffles we've computed to move the inputs into their
7755   // target half.
7756   if (!isNoopShuffleMask(PSHUFLMask))
7757     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7758                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7759   if (!isNoopShuffleMask(PSHUFHMask))
7760     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7761                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7762   if (!isNoopShuffleMask(PSHUFDMask))
7763     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7764                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7765                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7766                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7767
7768   // At this point, each half should contain all its inputs, and we can then
7769   // just shuffle them into their final position.
7770   assert(std::count_if(LoMask.begin(), LoMask.end(),
7771                        [](int M) { return M >= 4; }) == 0 &&
7772          "Failed to lift all the high half inputs to the low mask!");
7773   assert(std::count_if(HiMask.begin(), HiMask.end(),
7774                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7775          "Failed to lift all the low half inputs to the high mask!");
7776
7777   // Do a half shuffle for the low mask.
7778   if (!isNoopShuffleMask(LoMask))
7779     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7780                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7781
7782   // Do a half shuffle with the high mask after shifting its values down.
7783   for (int &M : HiMask)
7784     if (M >= 0)
7785       M -= 4;
7786   if (!isNoopShuffleMask(HiMask))
7787     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7788                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7789
7790   return V;
7791 }
7792
7793 /// \brief Detect whether the mask pattern should be lowered through
7794 /// interleaving.
7795 ///
7796 /// This essentially tests whether viewing the mask as an interleaving of two
7797 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7798 /// lowering it through interleaving is a significantly better strategy.
7799 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7800   int NumEvenInputs[2] = {0, 0};
7801   int NumOddInputs[2] = {0, 0};
7802   int NumLoInputs[2] = {0, 0};
7803   int NumHiInputs[2] = {0, 0};
7804   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7805     if (Mask[i] < 0)
7806       continue;
7807
7808     int InputIdx = Mask[i] >= Size;
7809
7810     if (i < Size / 2)
7811       ++NumLoInputs[InputIdx];
7812     else
7813       ++NumHiInputs[InputIdx];
7814
7815     if ((i % 2) == 0)
7816       ++NumEvenInputs[InputIdx];
7817     else
7818       ++NumOddInputs[InputIdx];
7819   }
7820
7821   // The minimum number of cross-input results for both the interleaved and
7822   // split cases. If interleaving results in fewer cross-input results, return
7823   // true.
7824   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7825                                     NumEvenInputs[0] + NumOddInputs[1]);
7826   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7827                               NumLoInputs[0] + NumHiInputs[1]);
7828   return InterleavedCrosses < SplitCrosses;
7829 }
7830
7831 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7832 ///
7833 /// This strategy only works when the inputs from each vector fit into a single
7834 /// half of that vector, and generally there are not so many inputs as to leave
7835 /// the in-place shuffles required highly constrained (and thus expensive). It
7836 /// shifts all the inputs into a single side of both input vectors and then
7837 /// uses an unpack to interleave these inputs in a single vector. At that
7838 /// point, we will fall back on the generic single input shuffle lowering.
7839 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7840                                                  SDValue V2,
7841                                                  MutableArrayRef<int> Mask,
7842                                                  const X86Subtarget *Subtarget,
7843                                                  SelectionDAG &DAG) {
7844   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7845   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7846   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7847   for (int i = 0; i < 8; ++i)
7848     if (Mask[i] >= 0 && Mask[i] < 4)
7849       LoV1Inputs.push_back(i);
7850     else if (Mask[i] >= 4 && Mask[i] < 8)
7851       HiV1Inputs.push_back(i);
7852     else if (Mask[i] >= 8 && Mask[i] < 12)
7853       LoV2Inputs.push_back(i);
7854     else if (Mask[i] >= 12)
7855       HiV2Inputs.push_back(i);
7856
7857   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7858   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7859   (void)NumV1Inputs;
7860   (void)NumV2Inputs;
7861   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7862   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7863   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7864
7865   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7866                      HiV1Inputs.size() + HiV2Inputs.size();
7867
7868   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7869                               ArrayRef<int> HiInputs, bool MoveToLo,
7870                               int MaskOffset) {
7871     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7872     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7873     if (BadInputs.empty())
7874       return V;
7875
7876     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7877     int MoveOffset = MoveToLo ? 0 : 4;
7878
7879     if (GoodInputs.empty()) {
7880       for (int BadInput : BadInputs) {
7881         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7882         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7883       }
7884     } else {
7885       if (GoodInputs.size() == 2) {
7886         // If the low inputs are spread across two dwords, pack them into
7887         // a single dword.
7888         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7889         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7890         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7891         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7892       } else {
7893         // Otherwise pin the good inputs.
7894         for (int GoodInput : GoodInputs)
7895           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7896       }
7897
7898       if (BadInputs.size() == 2) {
7899         // If we have two bad inputs then there may be either one or two good
7900         // inputs fixed in place. Find a fixed input, and then find the *other*
7901         // two adjacent indices by using modular arithmetic.
7902         int GoodMaskIdx =
7903             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7904                          [](int M) { return M >= 0; }) -
7905             std::begin(MoveMask);
7906         int MoveMaskIdx =
7907             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
7908         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7909         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7910         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7911         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7912         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7913         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7914       } else {
7915         assert(BadInputs.size() == 1 && "All sizes handled");
7916         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7917                                     std::end(MoveMask), -1) -
7918                           std::begin(MoveMask);
7919         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7920         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7921       }
7922     }
7923
7924     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7925                                 MoveMask);
7926   };
7927   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7928                         /*MaskOffset*/ 0);
7929   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7930                         /*MaskOffset*/ 8);
7931
7932   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7933   // cross-half traffic in the final shuffle.
7934
7935   // Munge the mask to be a single-input mask after the unpack merges the
7936   // results.
7937   for (int &M : Mask)
7938     if (M != -1)
7939       M = 2 * (M % 4) + (M / 8);
7940
7941   return DAG.getVectorShuffle(
7942       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7943                                   DL, MVT::v8i16, V1, V2),
7944       DAG.getUNDEF(MVT::v8i16), Mask);
7945 }
7946
7947 /// \brief Generic lowering of 8-lane i16 shuffles.
7948 ///
7949 /// This handles both single-input shuffles and combined shuffle/blends with
7950 /// two inputs. The single input shuffles are immediately delegated to
7951 /// a dedicated lowering routine.
7952 ///
7953 /// The blends are lowered in one of three fundamental ways. If there are few
7954 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7955 /// of the input is significantly cheaper when lowered as an interleaving of
7956 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7957 /// halves of the inputs separately (making them have relatively few inputs)
7958 /// and then concatenate them.
7959 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7960                                        const X86Subtarget *Subtarget,
7961                                        SelectionDAG &DAG) {
7962   SDLoc DL(Op);
7963   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7964   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7965   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7966   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7967   ArrayRef<int> OrigMask = SVOp->getMask();
7968   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7969                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7970   MutableArrayRef<int> Mask(MaskStorage);
7971
7972   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7973
7974   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7975   auto isV2 = [](int M) { return M >= 8; };
7976
7977   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7978   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7979
7980   if (NumV2Inputs == 0)
7981     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7982
7983   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7984                             "to be V1-input shuffles.");
7985
7986   if (NumV1Inputs + NumV2Inputs <= 4)
7987     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7988
7989   // Check whether an interleaving lowering is likely to be more efficient.
7990   // This isn't perfect but it is a strong heuristic that tends to work well on
7991   // the kinds of shuffles that show up in practice.
7992   //
7993   // FIXME: Handle 1x, 2x, and 4x interleaving.
7994   if (shouldLowerAsInterleaving(Mask)) {
7995     // FIXME: Figure out whether we should pack these into the low or high
7996     // halves.
7997
7998     int EMask[8], OMask[8];
7999     for (int i = 0; i < 4; ++i) {
8000       EMask[i] = Mask[2*i];
8001       OMask[i] = Mask[2*i + 1];
8002       EMask[i + 4] = -1;
8003       OMask[i + 4] = -1;
8004     }
8005
8006     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8007     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8008
8009     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8010   }
8011
8012   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8013   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8014
8015   for (int i = 0; i < 4; ++i) {
8016     LoBlendMask[i] = Mask[i];
8017     HiBlendMask[i] = Mask[i + 4];
8018   }
8019
8020   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8021   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8022   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8023   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8024
8025   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8026                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8027 }
8028
8029 /// \brief Check whether a compaction lowering can be done by dropping even
8030 /// elements and compute how many times even elements must be dropped.
8031 ///
8032 /// This handles shuffles which take every Nth element where N is a power of
8033 /// two. Example shuffle masks:
8034 ///
8035 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8036 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8037 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8038 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8039 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8040 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8041 ///
8042 /// Any of these lanes can of course be undef.
8043 ///
8044 /// This routine only supports N <= 3.
8045 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8046 /// for larger N.
8047 ///
8048 /// \returns N above, or the number of times even elements must be dropped if
8049 /// there is such a number. Otherwise returns zero.
8050 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8051   // Figure out whether we're looping over two inputs or just one.
8052   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8053
8054   // The modulus for the shuffle vector entries is based on whether this is
8055   // a single input or not.
8056   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8057   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8058          "We should only be called with masks with a power-of-2 size!");
8059
8060   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8061
8062   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8063   // and 2^3 simultaneously. This is because we may have ambiguity with
8064   // partially undef inputs.
8065   bool ViableForN[3] = {true, true, true};
8066
8067   for (int i = 0, e = Mask.size(); i < e; ++i) {
8068     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8069     // want.
8070     if (Mask[i] == -1)
8071       continue;
8072
8073     bool IsAnyViable = false;
8074     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8075       if (ViableForN[j]) {
8076         uint64_t N = j + 1;
8077
8078         // The shuffle mask must be equal to (i * 2^N) % M.
8079         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8080           IsAnyViable = true;
8081         else
8082           ViableForN[j] = false;
8083       }
8084     // Early exit if we exhaust the possible powers of two.
8085     if (!IsAnyViable)
8086       break;
8087   }
8088
8089   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8090     if (ViableForN[j])
8091       return j + 1;
8092
8093   // Return 0 as there is no viable power of two.
8094   return 0;
8095 }
8096
8097 /// \brief Generic lowering of v16i8 shuffles.
8098 ///
8099 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8100 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8101 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8102 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8103 /// back together.
8104 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8105                                        const X86Subtarget *Subtarget,
8106                                        SelectionDAG &DAG) {
8107   SDLoc DL(Op);
8108   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8109   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8110   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8111   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8112   ArrayRef<int> OrigMask = SVOp->getMask();
8113   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8114   int MaskStorage[16] = {
8115       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8116       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8117       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8118       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8119   MutableArrayRef<int> Mask(MaskStorage);
8120   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8121   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8122
8123   // For single-input shuffles, there are some nicer lowering tricks we can use.
8124   if (isSingleInputShuffleMask(Mask)) {
8125     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8126     // Notably, this handles splat and partial-splat shuffles more efficiently.
8127     // However, it only makes sense if the pre-duplication shuffle simplifies
8128     // things significantly. Currently, this means we need to be able to
8129     // express the pre-duplication shuffle as an i16 shuffle.
8130     //
8131     // FIXME: We should check for other patterns which can be widened into an
8132     // i16 shuffle as well.
8133     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8134       for (int i = 0; i < 16; i += 2) {
8135         if (Mask[i] != Mask[i + 1])
8136           return false;
8137       }
8138       return true;
8139     };
8140     auto tryToWidenViaDuplication = [&]() -> SDValue {
8141       if (!canWidenViaDuplication(Mask))
8142         return SDValue();
8143       SmallVector<int, 4> LoInputs;
8144       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8145                    [](int M) { return M >= 0 && M < 8; });
8146       std::sort(LoInputs.begin(), LoInputs.end());
8147       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8148                      LoInputs.end());
8149       SmallVector<int, 4> HiInputs;
8150       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8151                    [](int M) { return M >= 8; });
8152       std::sort(HiInputs.begin(), HiInputs.end());
8153       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8154                      HiInputs.end());
8155
8156       bool TargetLo = LoInputs.size() >= HiInputs.size();
8157       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8158       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8159
8160       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8161       SmallDenseMap<int, int, 8> LaneMap;
8162       for (int I : InPlaceInputs) {
8163         PreDupI16Shuffle[I/2] = I/2;
8164         LaneMap[I] = I;
8165       }
8166       int j = TargetLo ? 0 : 4, je = j + 4;
8167       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8168         // Check if j is already a shuffle of this input. This happens when
8169         // there are two adjacent bytes after we move the low one.
8170         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8171           // If we haven't yet mapped the input, search for a slot into which
8172           // we can map it.
8173           while (j < je && PreDupI16Shuffle[j] != -1)
8174             ++j;
8175
8176           if (j == je)
8177             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8178             return SDValue();
8179
8180           // Map this input with the i16 shuffle.
8181           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8182         }
8183
8184         // Update the lane map based on the mapping we ended up with.
8185         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8186       }
8187       V1 = DAG.getNode(
8188           ISD::BITCAST, DL, MVT::v16i8,
8189           DAG.getVectorShuffle(MVT::v8i16, DL,
8190                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8191                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8192
8193       // Unpack the bytes to form the i16s that will be shuffled into place.
8194       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8195                        MVT::v16i8, V1, V1);
8196
8197       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8198       for (int i = 0; i < 16; i += 2) {
8199         if (Mask[i] != -1)
8200           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8201         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8202       }
8203       return DAG.getNode(
8204           ISD::BITCAST, DL, MVT::v16i8,
8205           DAG.getVectorShuffle(MVT::v8i16, DL,
8206                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8207                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8208     };
8209     if (SDValue V = tryToWidenViaDuplication())
8210       return V;
8211   }
8212
8213   // Check whether an interleaving lowering is likely to be more efficient.
8214   // This isn't perfect but it is a strong heuristic that tends to work well on
8215   // the kinds of shuffles that show up in practice.
8216   //
8217   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8218   if (shouldLowerAsInterleaving(Mask)) {
8219     // FIXME: Figure out whether we should pack these into the low or high
8220     // halves.
8221
8222     int EMask[16], OMask[16];
8223     for (int i = 0; i < 8; ++i) {
8224       EMask[i] = Mask[2*i];
8225       OMask[i] = Mask[2*i + 1];
8226       EMask[i + 8] = -1;
8227       OMask[i + 8] = -1;
8228     }
8229
8230     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8231     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8232
8233     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8234   }
8235
8236   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8237   // with PSHUFB. It is important to do this before we attempt to generate any
8238   // blends but after all of the single-input lowerings. If the single input
8239   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8240   // want to preserve that and we can DAG combine any longer sequences into
8241   // a PSHUFB in the end. But once we start blending from multiple inputs,
8242   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8243   // and there are *very* few patterns that would actually be faster than the
8244   // PSHUFB approach because of its ability to zero lanes.
8245   //
8246   // FIXME: The only exceptions to the above are blends which are exact
8247   // interleavings with direct instructions supporting them. We currently don't
8248   // handle those well here.
8249   if (Subtarget->hasSSSE3()) {
8250     SDValue V1Mask[16];
8251     SDValue V2Mask[16];
8252     for (int i = 0; i < 16; ++i)
8253       if (Mask[i] == -1) {
8254         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8255       } else {
8256         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8257         V2Mask[i] =
8258             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8259       }
8260     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8261                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8262     if (isSingleInputShuffleMask(Mask))
8263       return V1; // Single inputs are easy.
8264
8265     // Otherwise, blend the two.
8266     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8267                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8268     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8269   }
8270
8271   // Check whether a compaction lowering can be done. This handles shuffles
8272   // which take every Nth element for some even N. See the helper function for
8273   // details.
8274   //
8275   // We special case these as they can be particularly efficiently handled with
8276   // the PACKUSB instruction on x86 and they show up in common patterns of
8277   // rearranging bytes to truncate wide elements.
8278   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8279     // NumEvenDrops is the power of two stride of the elements. Another way of
8280     // thinking about it is that we need to drop the even elements this many
8281     // times to get the original input.
8282     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8283
8284     // First we need to zero all the dropped bytes.
8285     assert(NumEvenDrops <= 3 &&
8286            "No support for dropping even elements more than 3 times.");
8287     // We use the mask type to pick which bytes are preserved based on how many
8288     // elements are dropped.
8289     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8290     SDValue ByteClearMask =
8291         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8292                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8293     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8294     if (!IsSingleInput)
8295       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8296
8297     // Now pack things back together.
8298     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8299     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8300     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8301     for (int i = 1; i < NumEvenDrops; ++i) {
8302       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8303       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8304     }
8305
8306     return Result;
8307   }
8308
8309   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8310   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8311   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8312   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8313
8314   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8315                             MutableArrayRef<int> V1HalfBlendMask,
8316                             MutableArrayRef<int> V2HalfBlendMask) {
8317     for (int i = 0; i < 8; ++i)
8318       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8319         V1HalfBlendMask[i] = HalfMask[i];
8320         HalfMask[i] = i;
8321       } else if (HalfMask[i] >= 16) {
8322         V2HalfBlendMask[i] = HalfMask[i] - 16;
8323         HalfMask[i] = i + 8;
8324       }
8325   };
8326   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8327   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8328
8329   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8330
8331   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8332                              MutableArrayRef<int> HiBlendMask) {
8333     SDValue V1, V2;
8334     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8335     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8336     // i16s.
8337     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8338                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8339         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8340                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8341       // Use a mask to drop the high bytes.
8342       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8343       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8344                        DAG.getConstant(0x00FF, MVT::v8i16));
8345
8346       // This will be a single vector shuffle instead of a blend so nuke V2.
8347       V2 = DAG.getUNDEF(MVT::v8i16);
8348
8349       // Squash the masks to point directly into V1.
8350       for (int &M : LoBlendMask)
8351         if (M >= 0)
8352           M /= 2;
8353       for (int &M : HiBlendMask)
8354         if (M >= 0)
8355           M /= 2;
8356     } else {
8357       // Otherwise just unpack the low half of V into V1 and the high half into
8358       // V2 so that we can blend them as i16s.
8359       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8360                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8361       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8362                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8363     }
8364
8365     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8366     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8367     return std::make_pair(BlendedLo, BlendedHi);
8368   };
8369   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8370   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8371   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8372
8373   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8374   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8375
8376   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8377 }
8378
8379 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8380 ///
8381 /// This routine breaks down the specific type of 128-bit shuffle and
8382 /// dispatches to the lowering routines accordingly.
8383 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8384                                         MVT VT, const X86Subtarget *Subtarget,
8385                                         SelectionDAG &DAG) {
8386   switch (VT.SimpleTy) {
8387   case MVT::v2i64:
8388     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8389   case MVT::v2f64:
8390     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8391   case MVT::v4i32:
8392     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8393   case MVT::v4f32:
8394     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8395   case MVT::v8i16:
8396     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8397   case MVT::v16i8:
8398     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8399
8400   default:
8401     llvm_unreachable("Unimplemented!");
8402   }
8403 }
8404
8405 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8406   int Size = Mask.size();
8407   for (int M : Mask.slice(0, Size / 2))
8408     if (M >= 0 && (M % Size) >= Size / 2)
8409       return true;
8410   for (int M : Mask.slice(Size / 2, Size / 2))
8411     if (M >= 0 && (M % Size) < Size / 2)
8412       return true;
8413   return false;
8414 }
8415
8416 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8417 /// shuffles.
8418 ///
8419 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8420 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8421 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8422 /// we encode the logic here for specific shuffle lowering routines to bail to
8423 /// when they exhaust the features avaible to more directly handle the shuffle.
8424 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8425                                                 SDValue V2,
8426                                                 const X86Subtarget *Subtarget,
8427                                                 SelectionDAG &DAG) {
8428   SDLoc DL(Op);
8429   MVT VT = Op.getSimpleValueType();
8430   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8431   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8432   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8433   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8434   ArrayRef<int> Mask = SVOp->getMask();
8435
8436   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8437   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8438
8439   int NumElements = VT.getVectorNumElements();
8440   int SplitNumElements = NumElements / 2;
8441   MVT ScalarVT = VT.getScalarType();
8442   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8443
8444   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8445                              DAG.getIntPtrConstant(0));
8446   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8447                              DAG.getIntPtrConstant(SplitNumElements));
8448   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8449                              DAG.getIntPtrConstant(0));
8450   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8451                              DAG.getIntPtrConstant(SplitNumElements));
8452
8453   // Now create two 4-way blends of these half-width vectors.
8454   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8455     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8456     for (int i = 0; i < SplitNumElements; ++i) {
8457       int M = HalfMask[i];
8458       if (M >= NumElements) {
8459         V2BlendMask.push_back(M - NumElements);
8460         V1BlendMask.push_back(-1);
8461         BlendMask.push_back(SplitNumElements + i);
8462       } else if (M >= 0) {
8463         V2BlendMask.push_back(-1);
8464         V1BlendMask.push_back(M);
8465         BlendMask.push_back(i);
8466       } else {
8467         V2BlendMask.push_back(-1);
8468         V1BlendMask.push_back(-1);
8469         BlendMask.push_back(-1);
8470       }
8471     }
8472     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8473     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8474     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8475   };
8476   SDValue Lo = HalfBlend(LoMask);
8477   SDValue Hi = HalfBlend(HiMask);
8478   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8479 }
8480
8481 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8482 ///
8483 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8484 /// isn't available.
8485 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8486                                        const X86Subtarget *Subtarget,
8487                                        SelectionDAG &DAG) {
8488   SDLoc DL(Op);
8489   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8490   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8491   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8492   ArrayRef<int> Mask = SVOp->getMask();
8493   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8494
8495   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8496   // shuffles aren't a problem and FP and int have the same patterns.
8497
8498   // FIXME: We can handle these more cleverly than splitting for v4f64.
8499   if (isHalfCrossingShuffleMask(Mask))
8500     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8501
8502   if (isSingleInputShuffleMask(Mask)) {
8503     // Non-half-crossing single input shuffles can be lowerid with an
8504     // interleaved permutation.
8505     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8506                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8507     return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8508                        DAG.getConstant(VPERMILPMask, MVT::i8));
8509   }
8510
8511   // X86 has dedicated unpack instructions that can handle specific blend
8512   // operations: UNPCKH and UNPCKL.
8513   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8514     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8515   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8516     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8517   // FIXME: It would be nice to find a way to get canonicalization to commute
8518   // these patterns.
8519   if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8520     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8521   if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8522     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8523
8524   // Check if the blend happens to exactly fit that of SHUFPD.
8525   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8526       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8527     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8528                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8529     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8530                        DAG.getConstant(SHUFPDMask, MVT::i8));
8531   }
8532   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8533       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8534     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8535                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8536     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8537                        DAG.getConstant(SHUFPDMask, MVT::i8));
8538   }
8539
8540   // Shuffle the input elements into the desired positions in V1 and V2 and
8541   // blend them together.
8542   int V1Mask[] = {-1, -1, -1, -1};
8543   int V2Mask[] = {-1, -1, -1, -1};
8544   for (int i = 0; i < 4; ++i)
8545     if (Mask[i] >= 0 && Mask[i] < 4)
8546       V1Mask[i] = Mask[i];
8547     else if (Mask[i] >= 4)
8548       V2Mask[i] = Mask[i] - 4;
8549
8550   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8551   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8552
8553   unsigned BlendMask = 0;
8554   for (int i = 0; i < 4; ++i)
8555     if (Mask[i] >= 4)
8556       BlendMask |= 1 << i;
8557
8558   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8559                      DAG.getConstant(BlendMask, MVT::i8));
8560 }
8561
8562 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8563 ///
8564 /// Largely delegates to common code when we have AVX2 and to the floating-point
8565 /// code when we only have AVX.
8566 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8567                                        const X86Subtarget *Subtarget,
8568                                        SelectionDAG &DAG) {
8569   SDLoc DL(Op);
8570   assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8571   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8572   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8573   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8574   ArrayRef<int> Mask = SVOp->getMask();
8575   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8576
8577   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8578   // shuffles aren't a problem and FP and int have the same patterns.
8579
8580   if (isHalfCrossingShuffleMask(Mask))
8581     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8582
8583   // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8584   // delegate to floating point code.
8585   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8586   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8587   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8588                      lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8589 }
8590
8591 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8592 ///
8593 /// This routine either breaks down the specific type of a 256-bit x86 vector
8594 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8595 /// together based on the available instructions.
8596 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8597                                         MVT VT, const X86Subtarget *Subtarget,
8598                                         SelectionDAG &DAG) {
8599   switch (VT.SimpleTy) {
8600   case MVT::v4f64:
8601     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8602   case MVT::v4i64:
8603     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8604   case MVT::v8i32:
8605   case MVT::v8f32:
8606   case MVT::v16i16:
8607   case MVT::v32i8:
8608     // Fall back to the basic pattern of extracting the high half and forming
8609     // a 4-way blend.
8610     // FIXME: Add targeted lowering for each type that can document rationale
8611     // for delegating to this when necessary.
8612     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8613
8614   default:
8615     llvm_unreachable("Not a valid 256-bit x86 vector type!");
8616   }
8617 }
8618
8619 /// \brief Tiny helper function to test whether a shuffle mask could be
8620 /// simplified by widening the elements being shuffled.
8621 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8622   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8623     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8624       return false;
8625
8626   return true;
8627 }
8628
8629 /// \brief Top-level lowering for x86 vector shuffles.
8630 ///
8631 /// This handles decomposition, canonicalization, and lowering of all x86
8632 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8633 /// above in helper routines. The canonicalization attempts to widen shuffles
8634 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8635 /// s.t. only one of the two inputs needs to be tested, etc.
8636 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8637                                   SelectionDAG &DAG) {
8638   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8639   ArrayRef<int> Mask = SVOp->getMask();
8640   SDValue V1 = Op.getOperand(0);
8641   SDValue V2 = Op.getOperand(1);
8642   MVT VT = Op.getSimpleValueType();
8643   int NumElements = VT.getVectorNumElements();
8644   SDLoc dl(Op);
8645
8646   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8647
8648   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8649   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8650   if (V1IsUndef && V2IsUndef)
8651     return DAG.getUNDEF(VT);
8652
8653   // When we create a shuffle node we put the UNDEF node to second operand,
8654   // but in some cases the first operand may be transformed to UNDEF.
8655   // In this case we should just commute the node.
8656   if (V1IsUndef)
8657     return DAG.getCommutedVectorShuffle(*SVOp);
8658
8659   // Check for non-undef masks pointing at an undef vector and make the masks
8660   // undef as well. This makes it easier to match the shuffle based solely on
8661   // the mask.
8662   if (V2IsUndef)
8663     for (int M : Mask)
8664       if (M >= NumElements) {
8665         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8666         for (int &M : NewMask)
8667           if (M >= NumElements)
8668             M = -1;
8669         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8670       }
8671
8672   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8673   // lanes but wider integers. We cap this to not form integers larger than i64
8674   // but it might be interesting to form i128 integers to handle flipping the
8675   // low and high halves of AVX 256-bit vectors.
8676   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8677       canWidenShuffleElements(Mask)) {
8678     SmallVector<int, 8> NewMask;
8679     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8680       NewMask.push_back(Mask[i] / 2);
8681     MVT NewVT =
8682         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8683                          VT.getVectorNumElements() / 2);
8684     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8685     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8686     return DAG.getNode(ISD::BITCAST, dl, VT,
8687                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8688   }
8689
8690   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8691   for (int M : SVOp->getMask())
8692     if (M < 0)
8693       ++NumUndefElements;
8694     else if (M < NumElements)
8695       ++NumV1Elements;
8696     else
8697       ++NumV2Elements;
8698
8699   // Commute the shuffle as needed such that more elements come from V1 than
8700   // V2. This allows us to match the shuffle pattern strictly on how many
8701   // elements come from V1 without handling the symmetric cases.
8702   if (NumV2Elements > NumV1Elements)
8703     return DAG.getCommutedVectorShuffle(*SVOp);
8704
8705   // When the number of V1 and V2 elements are the same, try to minimize the
8706   // number of uses of V2 in the low half of the vector.
8707   if (NumV1Elements == NumV2Elements) {
8708     int LowV1Elements = 0, LowV2Elements = 0;
8709     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8710       if (M >= NumElements)
8711         ++LowV2Elements;
8712       else if (M >= 0)
8713         ++LowV1Elements;
8714     if (LowV2Elements > LowV1Elements)
8715       return DAG.getCommutedVectorShuffle(*SVOp);
8716   }
8717
8718   // For each vector width, delegate to a specialized lowering routine.
8719   if (VT.getSizeInBits() == 128)
8720     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8721
8722   if (VT.getSizeInBits() == 256)
8723     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8724
8725   llvm_unreachable("Unimplemented!");
8726 }
8727
8728
8729 //===----------------------------------------------------------------------===//
8730 // Legacy vector shuffle lowering
8731 //
8732 // This code is the legacy code handling vector shuffles until the above
8733 // replaces its functionality and performance.
8734 //===----------------------------------------------------------------------===//
8735
8736 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8737                         bool hasInt256, unsigned *MaskOut = nullptr) {
8738   MVT EltVT = VT.getVectorElementType();
8739
8740   // There is no blend with immediate in AVX-512.
8741   if (VT.is512BitVector())
8742     return false;
8743
8744   if (!hasSSE41 || EltVT == MVT::i8)
8745     return false;
8746   if (!hasInt256 && VT == MVT::v16i16)
8747     return false;
8748
8749   unsigned MaskValue = 0;
8750   unsigned NumElems = VT.getVectorNumElements();
8751   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8752   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8753   unsigned NumElemsInLane = NumElems / NumLanes;
8754
8755   // Blend for v16i16 should be symetric for the both lanes.
8756   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8757
8758     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8759     int EltIdx = MaskVals[i];
8760
8761     if ((EltIdx < 0 || EltIdx == (int)i) &&
8762         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8763       continue;
8764
8765     if (((unsigned)EltIdx == (i + NumElems)) &&
8766         (SndLaneEltIdx < 0 ||
8767          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8768       MaskValue |= (1 << i);
8769     else
8770       return false;
8771   }
8772
8773   if (MaskOut)
8774     *MaskOut = MaskValue;
8775   return true;
8776 }
8777
8778 // Try to lower a shuffle node into a simple blend instruction.
8779 // This function assumes isBlendMask returns true for this
8780 // SuffleVectorSDNode
8781 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8782                                           unsigned MaskValue,
8783                                           const X86Subtarget *Subtarget,
8784                                           SelectionDAG &DAG) {
8785   MVT VT = SVOp->getSimpleValueType(0);
8786   MVT EltVT = VT.getVectorElementType();
8787   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8788                      Subtarget->hasInt256() && "Trying to lower a "
8789                                                "VECTOR_SHUFFLE to a Blend but "
8790                                                "with the wrong mask"));
8791   SDValue V1 = SVOp->getOperand(0);
8792   SDValue V2 = SVOp->getOperand(1);
8793   SDLoc dl(SVOp);
8794   unsigned NumElems = VT.getVectorNumElements();
8795
8796   // Convert i32 vectors to floating point if it is not AVX2.
8797   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8798   MVT BlendVT = VT;
8799   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8800     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8801                                NumElems);
8802     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8803     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8804   }
8805
8806   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8807                             DAG.getConstant(MaskValue, MVT::i32));
8808   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8809 }
8810
8811 /// In vector type \p VT, return true if the element at index \p InputIdx
8812 /// falls on a different 128-bit lane than \p OutputIdx.
8813 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8814                                      unsigned OutputIdx) {
8815   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8816   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8817 }
8818
8819 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8820 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8821 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8822 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8823 /// zero.
8824 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8825                          SelectionDAG &DAG) {
8826   MVT VT = V1.getSimpleValueType();
8827   assert(VT.is128BitVector() || VT.is256BitVector());
8828
8829   MVT EltVT = VT.getVectorElementType();
8830   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8831   unsigned NumElts = VT.getVectorNumElements();
8832
8833   SmallVector<SDValue, 32> PshufbMask;
8834   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8835     int InputIdx = MaskVals[OutputIdx];
8836     unsigned InputByteIdx;
8837
8838     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8839       InputByteIdx = 0x80;
8840     else {
8841       // Cross lane is not allowed.
8842       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8843         return SDValue();
8844       InputByteIdx = InputIdx * EltSizeInBytes;
8845       // Index is an byte offset within the 128-bit lane.
8846       InputByteIdx &= 0xf;
8847     }
8848
8849     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8850       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8851       if (InputByteIdx != 0x80)
8852         ++InputByteIdx;
8853     }
8854   }
8855
8856   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8857   if (ShufVT != VT)
8858     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8859   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8860                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8861 }
8862
8863 // v8i16 shuffles - Prefer shuffles in the following order:
8864 // 1. [all]   pshuflw, pshufhw, optional move
8865 // 2. [ssse3] 1 x pshufb
8866 // 3. [ssse3] 2 x pshufb + 1 x por
8867 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8868 static SDValue
8869 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8870                          SelectionDAG &DAG) {
8871   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8872   SDValue V1 = SVOp->getOperand(0);
8873   SDValue V2 = SVOp->getOperand(1);
8874   SDLoc dl(SVOp);
8875   SmallVector<int, 8> MaskVals;
8876
8877   // Determine if more than 1 of the words in each of the low and high quadwords
8878   // of the result come from the same quadword of one of the two inputs.  Undef
8879   // mask values count as coming from any quadword, for better codegen.
8880   //
8881   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8882   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8883   unsigned LoQuad[] = { 0, 0, 0, 0 };
8884   unsigned HiQuad[] = { 0, 0, 0, 0 };
8885   // Indices of quads used.
8886   std::bitset<4> InputQuads;
8887   for (unsigned i = 0; i < 8; ++i) {
8888     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8889     int EltIdx = SVOp->getMaskElt(i);
8890     MaskVals.push_back(EltIdx);
8891     if (EltIdx < 0) {
8892       ++Quad[0];
8893       ++Quad[1];
8894       ++Quad[2];
8895       ++Quad[3];
8896       continue;
8897     }
8898     ++Quad[EltIdx / 4];
8899     InputQuads.set(EltIdx / 4);
8900   }
8901
8902   int BestLoQuad = -1;
8903   unsigned MaxQuad = 1;
8904   for (unsigned i = 0; i < 4; ++i) {
8905     if (LoQuad[i] > MaxQuad) {
8906       BestLoQuad = i;
8907       MaxQuad = LoQuad[i];
8908     }
8909   }
8910
8911   int BestHiQuad = -1;
8912   MaxQuad = 1;
8913   for (unsigned i = 0; i < 4; ++i) {
8914     if (HiQuad[i] > MaxQuad) {
8915       BestHiQuad = i;
8916       MaxQuad = HiQuad[i];
8917     }
8918   }
8919
8920   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8921   // of the two input vectors, shuffle them into one input vector so only a
8922   // single pshufb instruction is necessary. If there are more than 2 input
8923   // quads, disable the next transformation since it does not help SSSE3.
8924   bool V1Used = InputQuads[0] || InputQuads[1];
8925   bool V2Used = InputQuads[2] || InputQuads[3];
8926   if (Subtarget->hasSSSE3()) {
8927     if (InputQuads.count() == 2 && V1Used && V2Used) {
8928       BestLoQuad = InputQuads[0] ? 0 : 1;
8929       BestHiQuad = InputQuads[2] ? 2 : 3;
8930     }
8931     if (InputQuads.count() > 2) {
8932       BestLoQuad = -1;
8933       BestHiQuad = -1;
8934     }
8935   }
8936
8937   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8938   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8939   // words from all 4 input quadwords.
8940   SDValue NewV;
8941   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8942     int MaskV[] = {
8943       BestLoQuad < 0 ? 0 : BestLoQuad,
8944       BestHiQuad < 0 ? 1 : BestHiQuad
8945     };
8946     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8947                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8948                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8949     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8950
8951     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8952     // source words for the shuffle, to aid later transformations.
8953     bool AllWordsInNewV = true;
8954     bool InOrder[2] = { true, true };
8955     for (unsigned i = 0; i != 8; ++i) {
8956       int idx = MaskVals[i];
8957       if (idx != (int)i)
8958         InOrder[i/4] = false;
8959       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8960         continue;
8961       AllWordsInNewV = false;
8962       break;
8963     }
8964
8965     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8966     if (AllWordsInNewV) {
8967       for (int i = 0; i != 8; ++i) {
8968         int idx = MaskVals[i];
8969         if (idx < 0)
8970           continue;
8971         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8972         if ((idx != i) && idx < 4)
8973           pshufhw = false;
8974         if ((idx != i) && idx > 3)
8975           pshuflw = false;
8976       }
8977       V1 = NewV;
8978       V2Used = false;
8979       BestLoQuad = 0;
8980       BestHiQuad = 1;
8981     }
8982
8983     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8984     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8985     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8986       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8987       unsigned TargetMask = 0;
8988       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8989                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8990       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8991       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8992                              getShufflePSHUFLWImmediate(SVOp);
8993       V1 = NewV.getOperand(0);
8994       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8995     }
8996   }
8997
8998   // Promote splats to a larger type which usually leads to more efficient code.
8999   // FIXME: Is this true if pshufb is available?
9000   if (SVOp->isSplat())
9001     return PromoteSplat(SVOp, DAG);
9002
9003   // If we have SSSE3, and all words of the result are from 1 input vector,
9004   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
9005   // is present, fall back to case 4.
9006   if (Subtarget->hasSSSE3()) {
9007     SmallVector<SDValue,16> pshufbMask;
9008
9009     // If we have elements from both input vectors, set the high bit of the
9010     // shuffle mask element to zero out elements that come from V2 in the V1
9011     // mask, and elements that come from V1 in the V2 mask, so that the two
9012     // results can be OR'd together.
9013     bool TwoInputs = V1Used && V2Used;
9014     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9015     if (!TwoInputs)
9016       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9017
9018     // Calculate the shuffle mask for the second input, shuffle it, and
9019     // OR it with the first shuffled input.
9020     CommuteVectorShuffleMask(MaskVals, 8);
9021     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9022     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9023     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9024   }
9025
9026   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9027   // and update MaskVals with new element order.
9028   std::bitset<8> InOrder;
9029   if (BestLoQuad >= 0) {
9030     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9031     for (int i = 0; i != 4; ++i) {
9032       int idx = MaskVals[i];
9033       if (idx < 0) {
9034         InOrder.set(i);
9035       } else if ((idx / 4) == BestLoQuad) {
9036         MaskV[i] = idx & 3;
9037         InOrder.set(i);
9038       }
9039     }
9040     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9041                                 &MaskV[0]);
9042
9043     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9044       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9045       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9046                                   NewV.getOperand(0),
9047                                   getShufflePSHUFLWImmediate(SVOp), DAG);
9048     }
9049   }
9050
9051   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9052   // and update MaskVals with the new element order.
9053   if (BestHiQuad >= 0) {
9054     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9055     for (unsigned i = 4; i != 8; ++i) {
9056       int idx = MaskVals[i];
9057       if (idx < 0) {
9058         InOrder.set(i);
9059       } else if ((idx / 4) == BestHiQuad) {
9060         MaskV[i] = (idx & 3) + 4;
9061         InOrder.set(i);
9062       }
9063     }
9064     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9065                                 &MaskV[0]);
9066
9067     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9068       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9069       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9070                                   NewV.getOperand(0),
9071                                   getShufflePSHUFHWImmediate(SVOp), DAG);
9072     }
9073   }
9074
9075   // In case BestHi & BestLo were both -1, which means each quadword has a word
9076   // from each of the four input quadwords, calculate the InOrder bitvector now
9077   // before falling through to the insert/extract cleanup.
9078   if (BestLoQuad == -1 && BestHiQuad == -1) {
9079     NewV = V1;
9080     for (int i = 0; i != 8; ++i)
9081       if (MaskVals[i] < 0 || MaskVals[i] == i)
9082         InOrder.set(i);
9083   }
9084
9085   // The other elements are put in the right place using pextrw and pinsrw.
9086   for (unsigned i = 0; i != 8; ++i) {
9087     if (InOrder[i])
9088       continue;
9089     int EltIdx = MaskVals[i];
9090     if (EltIdx < 0)
9091       continue;
9092     SDValue ExtOp = (EltIdx < 8) ?
9093       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9094                   DAG.getIntPtrConstant(EltIdx)) :
9095       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9096                   DAG.getIntPtrConstant(EltIdx - 8));
9097     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9098                        DAG.getIntPtrConstant(i));
9099   }
9100   return NewV;
9101 }
9102
9103 /// \brief v16i16 shuffles
9104 ///
9105 /// FIXME: We only support generation of a single pshufb currently.  We can
9106 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9107 /// well (e.g 2 x pshufb + 1 x por).
9108 static SDValue
9109 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9110   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9111   SDValue V1 = SVOp->getOperand(0);
9112   SDValue V2 = SVOp->getOperand(1);
9113   SDLoc dl(SVOp);
9114
9115   if (V2.getOpcode() != ISD::UNDEF)
9116     return SDValue();
9117
9118   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9119   return getPSHUFB(MaskVals, V1, dl, DAG);
9120 }
9121
9122 // v16i8 shuffles - Prefer shuffles in the following order:
9123 // 1. [ssse3] 1 x pshufb
9124 // 2. [ssse3] 2 x pshufb + 1 x por
9125 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
9126 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9127                                         const X86Subtarget* Subtarget,
9128                                         SelectionDAG &DAG) {
9129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9130   SDValue V1 = SVOp->getOperand(0);
9131   SDValue V2 = SVOp->getOperand(1);
9132   SDLoc dl(SVOp);
9133   ArrayRef<int> MaskVals = SVOp->getMask();
9134
9135   // Promote splats to a larger type which usually leads to more efficient code.
9136   // FIXME: Is this true if pshufb is available?
9137   if (SVOp->isSplat())
9138     return PromoteSplat(SVOp, DAG);
9139
9140   // If we have SSSE3, case 1 is generated when all result bytes come from
9141   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
9142   // present, fall back to case 3.
9143
9144   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9145   if (Subtarget->hasSSSE3()) {
9146     SmallVector<SDValue,16> pshufbMask;
9147
9148     // If all result elements are from one input vector, then only translate
9149     // undef mask values to 0x80 (zero out result) in the pshufb mask.
9150     //
9151     // Otherwise, we have elements from both input vectors, and must zero out
9152     // elements that come from V2 in the first mask, and V1 in the second mask
9153     // so that we can OR them together.
9154     for (unsigned i = 0; i != 16; ++i) {
9155       int EltIdx = MaskVals[i];
9156       if (EltIdx < 0 || EltIdx >= 16)
9157         EltIdx = 0x80;
9158       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9159     }
9160     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9161                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9162                                  MVT::v16i8, pshufbMask));
9163
9164     // As PSHUFB will zero elements with negative indices, it's safe to ignore
9165     // the 2nd operand if it's undefined or zero.
9166     if (V2.getOpcode() == ISD::UNDEF ||
9167         ISD::isBuildVectorAllZeros(V2.getNode()))
9168       return V1;
9169
9170     // Calculate the shuffle mask for the second input, shuffle it, and
9171     // OR it with the first shuffled input.
9172     pshufbMask.clear();
9173     for (unsigned i = 0; i != 16; ++i) {
9174       int EltIdx = MaskVals[i];
9175       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9176       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9177     }
9178     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9179                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9180                                  MVT::v16i8, pshufbMask));
9181     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9182   }
9183
9184   // No SSSE3 - Calculate in place words and then fix all out of place words
9185   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
9186   // the 16 different words that comprise the two doublequadword input vectors.
9187   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9188   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9189   SDValue NewV = V1;
9190   for (int i = 0; i != 8; ++i) {
9191     int Elt0 = MaskVals[i*2];
9192     int Elt1 = MaskVals[i*2+1];
9193
9194     // This word of the result is all undef, skip it.
9195     if (Elt0 < 0 && Elt1 < 0)
9196       continue;
9197
9198     // This word of the result is already in the correct place, skip it.
9199     if ((Elt0 == i*2) && (Elt1 == i*2+1))
9200       continue;
9201
9202     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9203     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9204     SDValue InsElt;
9205
9206     // If Elt0 and Elt1 are defined, are consecutive, and can be load
9207     // using a single extract together, load it and store it.
9208     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9209       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9210                            DAG.getIntPtrConstant(Elt1 / 2));
9211       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9212                         DAG.getIntPtrConstant(i));
9213       continue;
9214     }
9215
9216     // If Elt1 is defined, extract it from the appropriate source.  If the
9217     // source byte is not also odd, shift the extracted word left 8 bits
9218     // otherwise clear the bottom 8 bits if we need to do an or.
9219     if (Elt1 >= 0) {
9220       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9221                            DAG.getIntPtrConstant(Elt1 / 2));
9222       if ((Elt1 & 1) == 0)
9223         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9224                              DAG.getConstant(8,
9225                                   TLI.getShiftAmountTy(InsElt.getValueType())));
9226       else if (Elt0 >= 0)
9227         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9228                              DAG.getConstant(0xFF00, MVT::i16));
9229     }
9230     // If Elt0 is defined, extract it from the appropriate source.  If the
9231     // source byte is not also even, shift the extracted word right 8 bits. If
9232     // Elt1 was also defined, OR the extracted values together before
9233     // inserting them in the result.
9234     if (Elt0 >= 0) {
9235       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9236                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9237       if ((Elt0 & 1) != 0)
9238         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9239                               DAG.getConstant(8,
9240                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
9241       else if (Elt1 >= 0)
9242         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9243                              DAG.getConstant(0x00FF, MVT::i16));
9244       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9245                          : InsElt0;
9246     }
9247     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9248                        DAG.getIntPtrConstant(i));
9249   }
9250   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9251 }
9252
9253 // v32i8 shuffles - Translate to VPSHUFB if possible.
9254 static
9255 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9256                                  const X86Subtarget *Subtarget,
9257                                  SelectionDAG &DAG) {
9258   MVT VT = SVOp->getSimpleValueType(0);
9259   SDValue V1 = SVOp->getOperand(0);
9260   SDValue V2 = SVOp->getOperand(1);
9261   SDLoc dl(SVOp);
9262   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9263
9264   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9265   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9266   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9267
9268   // VPSHUFB may be generated if
9269   // (1) one of input vector is undefined or zeroinitializer.
9270   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9271   // And (2) the mask indexes don't cross the 128-bit lane.
9272   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9273       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9274     return SDValue();
9275
9276   if (V1IsAllZero && !V2IsAllZero) {
9277     CommuteVectorShuffleMask(MaskVals, 32);
9278     V1 = V2;
9279   }
9280   return getPSHUFB(MaskVals, V1, dl, DAG);
9281 }
9282
9283 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9284 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9285 /// done when every pair / quad of shuffle mask elements point to elements in
9286 /// the right sequence. e.g.
9287 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9288 static
9289 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9290                                  SelectionDAG &DAG) {
9291   MVT VT = SVOp->getSimpleValueType(0);
9292   SDLoc dl(SVOp);
9293   unsigned NumElems = VT.getVectorNumElements();
9294   MVT NewVT;
9295   unsigned Scale;
9296   switch (VT.SimpleTy) {
9297   default: llvm_unreachable("Unexpected!");
9298   case MVT::v2i64:
9299   case MVT::v2f64:
9300            return SDValue(SVOp, 0);
9301   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9302   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9303   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9304   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9305   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9306   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9307   }
9308
9309   SmallVector<int, 8> MaskVec;
9310   for (unsigned i = 0; i != NumElems; i += Scale) {
9311     int StartIdx = -1;
9312     for (unsigned j = 0; j != Scale; ++j) {
9313       int EltIdx = SVOp->getMaskElt(i+j);
9314       if (EltIdx < 0)
9315         continue;
9316       if (StartIdx < 0)
9317         StartIdx = (EltIdx / Scale);
9318       if (EltIdx != (int)(StartIdx*Scale + j))
9319         return SDValue();
9320     }
9321     MaskVec.push_back(StartIdx);
9322   }
9323
9324   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9325   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9326   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9327 }
9328
9329 /// getVZextMovL - Return a zero-extending vector move low node.
9330 ///
9331 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9332                             SDValue SrcOp, SelectionDAG &DAG,
9333                             const X86Subtarget *Subtarget, SDLoc dl) {
9334   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9335     LoadSDNode *LD = nullptr;
9336     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9337       LD = dyn_cast<LoadSDNode>(SrcOp);
9338     if (!LD) {
9339       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9340       // instead.
9341       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9342       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9343           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9344           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9345           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9346         // PR2108
9347         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9348         return DAG.getNode(ISD::BITCAST, dl, VT,
9349                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9350                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9351                                                    OpVT,
9352                                                    SrcOp.getOperand(0)
9353                                                           .getOperand(0))));
9354       }
9355     }
9356   }
9357
9358   return DAG.getNode(ISD::BITCAST, dl, VT,
9359                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9360                                  DAG.getNode(ISD::BITCAST, dl,
9361                                              OpVT, SrcOp)));
9362 }
9363
9364 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9365 /// which could not be matched by any known target speficic shuffle
9366 static SDValue
9367 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9368
9369   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9370   if (NewOp.getNode())
9371     return NewOp;
9372
9373   MVT VT = SVOp->getSimpleValueType(0);
9374
9375   unsigned NumElems = VT.getVectorNumElements();
9376   unsigned NumLaneElems = NumElems / 2;
9377
9378   SDLoc dl(SVOp);
9379   MVT EltVT = VT.getVectorElementType();
9380   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9381   SDValue Output[2];
9382
9383   SmallVector<int, 16> Mask;
9384   for (unsigned l = 0; l < 2; ++l) {
9385     // Build a shuffle mask for the output, discovering on the fly which
9386     // input vectors to use as shuffle operands (recorded in InputUsed).
9387     // If building a suitable shuffle vector proves too hard, then bail
9388     // out with UseBuildVector set.
9389     bool UseBuildVector = false;
9390     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9391     unsigned LaneStart = l * NumLaneElems;
9392     for (unsigned i = 0; i != NumLaneElems; ++i) {
9393       // The mask element.  This indexes into the input.
9394       int Idx = SVOp->getMaskElt(i+LaneStart);
9395       if (Idx < 0) {
9396         // the mask element does not index into any input vector.
9397         Mask.push_back(-1);
9398         continue;
9399       }
9400
9401       // The input vector this mask element indexes into.
9402       int Input = Idx / NumLaneElems;
9403
9404       // Turn the index into an offset from the start of the input vector.
9405       Idx -= Input * NumLaneElems;
9406
9407       // Find or create a shuffle vector operand to hold this input.
9408       unsigned OpNo;
9409       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9410         if (InputUsed[OpNo] == Input)
9411           // This input vector is already an operand.
9412           break;
9413         if (InputUsed[OpNo] < 0) {
9414           // Create a new operand for this input vector.
9415           InputUsed[OpNo] = Input;
9416           break;
9417         }
9418       }
9419
9420       if (OpNo >= array_lengthof(InputUsed)) {
9421         // More than two input vectors used!  Give up on trying to create a
9422         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9423         UseBuildVector = true;
9424         break;
9425       }
9426
9427       // Add the mask index for the new shuffle vector.
9428       Mask.push_back(Idx + OpNo * NumLaneElems);
9429     }
9430
9431     if (UseBuildVector) {
9432       SmallVector<SDValue, 16> SVOps;
9433       for (unsigned i = 0; i != NumLaneElems; ++i) {
9434         // The mask element.  This indexes into the input.
9435         int Idx = SVOp->getMaskElt(i+LaneStart);
9436         if (Idx < 0) {
9437           SVOps.push_back(DAG.getUNDEF(EltVT));
9438           continue;
9439         }
9440
9441         // The input vector this mask element indexes into.
9442         int Input = Idx / NumElems;
9443
9444         // Turn the index into an offset from the start of the input vector.
9445         Idx -= Input * NumElems;
9446
9447         // Extract the vector element by hand.
9448         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9449                                     SVOp->getOperand(Input),
9450                                     DAG.getIntPtrConstant(Idx)));
9451       }
9452
9453       // Construct the output using a BUILD_VECTOR.
9454       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9455     } else if (InputUsed[0] < 0) {
9456       // No input vectors were used! The result is undefined.
9457       Output[l] = DAG.getUNDEF(NVT);
9458     } else {
9459       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9460                                         (InputUsed[0] % 2) * NumLaneElems,
9461                                         DAG, dl);
9462       // If only one input was used, use an undefined vector for the other.
9463       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9464         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9465                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9466       // At least one input vector was used. Create a new shuffle vector.
9467       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9468     }
9469
9470     Mask.clear();
9471   }
9472
9473   // Concatenate the result back
9474   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9475 }
9476
9477 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9478 /// 4 elements, and match them with several different shuffle types.
9479 static SDValue
9480 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9481   SDValue V1 = SVOp->getOperand(0);
9482   SDValue V2 = SVOp->getOperand(1);
9483   SDLoc dl(SVOp);
9484   MVT VT = SVOp->getSimpleValueType(0);
9485
9486   assert(VT.is128BitVector() && "Unsupported vector size");
9487
9488   std::pair<int, int> Locs[4];
9489   int Mask1[] = { -1, -1, -1, -1 };
9490   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9491
9492   unsigned NumHi = 0;
9493   unsigned NumLo = 0;
9494   for (unsigned i = 0; i != 4; ++i) {
9495     int Idx = PermMask[i];
9496     if (Idx < 0) {
9497       Locs[i] = std::make_pair(-1, -1);
9498     } else {
9499       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9500       if (Idx < 4) {
9501         Locs[i] = std::make_pair(0, NumLo);
9502         Mask1[NumLo] = Idx;
9503         NumLo++;
9504       } else {
9505         Locs[i] = std::make_pair(1, NumHi);
9506         if (2+NumHi < 4)
9507           Mask1[2+NumHi] = Idx;
9508         NumHi++;
9509       }
9510     }
9511   }
9512
9513   if (NumLo <= 2 && NumHi <= 2) {
9514     // If no more than two elements come from either vector. This can be
9515     // implemented with two shuffles. First shuffle gather the elements.
9516     // The second shuffle, which takes the first shuffle as both of its
9517     // vector operands, put the elements into the right order.
9518     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9519
9520     int Mask2[] = { -1, -1, -1, -1 };
9521
9522     for (unsigned i = 0; i != 4; ++i)
9523       if (Locs[i].first != -1) {
9524         unsigned Idx = (i < 2) ? 0 : 4;
9525         Idx += Locs[i].first * 2 + Locs[i].second;
9526         Mask2[i] = Idx;
9527       }
9528
9529     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9530   }
9531
9532   if (NumLo == 3 || NumHi == 3) {
9533     // Otherwise, we must have three elements from one vector, call it X, and
9534     // one element from the other, call it Y.  First, use a shufps to build an
9535     // intermediate vector with the one element from Y and the element from X
9536     // that will be in the same half in the final destination (the indexes don't
9537     // matter). Then, use a shufps to build the final vector, taking the half
9538     // containing the element from Y from the intermediate, and the other half
9539     // from X.
9540     if (NumHi == 3) {
9541       // Normalize it so the 3 elements come from V1.
9542       CommuteVectorShuffleMask(PermMask, 4);
9543       std::swap(V1, V2);
9544     }
9545
9546     // Find the element from V2.
9547     unsigned HiIndex;
9548     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9549       int Val = PermMask[HiIndex];
9550       if (Val < 0)
9551         continue;
9552       if (Val >= 4)
9553         break;
9554     }
9555
9556     Mask1[0] = PermMask[HiIndex];
9557     Mask1[1] = -1;
9558     Mask1[2] = PermMask[HiIndex^1];
9559     Mask1[3] = -1;
9560     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9561
9562     if (HiIndex >= 2) {
9563       Mask1[0] = PermMask[0];
9564       Mask1[1] = PermMask[1];
9565       Mask1[2] = HiIndex & 1 ? 6 : 4;
9566       Mask1[3] = HiIndex & 1 ? 4 : 6;
9567       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9568     }
9569
9570     Mask1[0] = HiIndex & 1 ? 2 : 0;
9571     Mask1[1] = HiIndex & 1 ? 0 : 2;
9572     Mask1[2] = PermMask[2];
9573     Mask1[3] = PermMask[3];
9574     if (Mask1[2] >= 0)
9575       Mask1[2] += 4;
9576     if (Mask1[3] >= 0)
9577       Mask1[3] += 4;
9578     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9579   }
9580
9581   // Break it into (shuffle shuffle_hi, shuffle_lo).
9582   int LoMask[] = { -1, -1, -1, -1 };
9583   int HiMask[] = { -1, -1, -1, -1 };
9584
9585   int *MaskPtr = LoMask;
9586   unsigned MaskIdx = 0;
9587   unsigned LoIdx = 0;
9588   unsigned HiIdx = 2;
9589   for (unsigned i = 0; i != 4; ++i) {
9590     if (i == 2) {
9591       MaskPtr = HiMask;
9592       MaskIdx = 1;
9593       LoIdx = 0;
9594       HiIdx = 2;
9595     }
9596     int Idx = PermMask[i];
9597     if (Idx < 0) {
9598       Locs[i] = std::make_pair(-1, -1);
9599     } else if (Idx < 4) {
9600       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9601       MaskPtr[LoIdx] = Idx;
9602       LoIdx++;
9603     } else {
9604       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9605       MaskPtr[HiIdx] = Idx;
9606       HiIdx++;
9607     }
9608   }
9609
9610   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9611   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9612   int MaskOps[] = { -1, -1, -1, -1 };
9613   for (unsigned i = 0; i != 4; ++i)
9614     if (Locs[i].first != -1)
9615       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9616   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9617 }
9618
9619 static bool MayFoldVectorLoad(SDValue V) {
9620   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9621     V = V.getOperand(0);
9622
9623   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9624     V = V.getOperand(0);
9625   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9626       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9627     // BUILD_VECTOR (load), undef
9628     V = V.getOperand(0);
9629
9630   return MayFoldLoad(V);
9631 }
9632
9633 static
9634 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9635   MVT VT = Op.getSimpleValueType();
9636
9637   // Canonizalize to v2f64.
9638   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9639   return DAG.getNode(ISD::BITCAST, dl, VT,
9640                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9641                                           V1, DAG));
9642 }
9643
9644 static
9645 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9646                         bool HasSSE2) {
9647   SDValue V1 = Op.getOperand(0);
9648   SDValue V2 = Op.getOperand(1);
9649   MVT VT = Op.getSimpleValueType();
9650
9651   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9652
9653   if (HasSSE2 && VT == MVT::v2f64)
9654     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9655
9656   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9657   return DAG.getNode(ISD::BITCAST, dl, VT,
9658                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9659                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9660                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9661 }
9662
9663 static
9664 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9665   SDValue V1 = Op.getOperand(0);
9666   SDValue V2 = Op.getOperand(1);
9667   MVT VT = Op.getSimpleValueType();
9668
9669   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9670          "unsupported shuffle type");
9671
9672   if (V2.getOpcode() == ISD::UNDEF)
9673     V2 = V1;
9674
9675   // v4i32 or v4f32
9676   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9677 }
9678
9679 static
9680 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9681   SDValue V1 = Op.getOperand(0);
9682   SDValue V2 = Op.getOperand(1);
9683   MVT VT = Op.getSimpleValueType();
9684   unsigned NumElems = VT.getVectorNumElements();
9685
9686   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9687   // operand of these instructions is only memory, so check if there's a
9688   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9689   // same masks.
9690   bool CanFoldLoad = false;
9691
9692   // Trivial case, when V2 comes from a load.
9693   if (MayFoldVectorLoad(V2))
9694     CanFoldLoad = true;
9695
9696   // When V1 is a load, it can be folded later into a store in isel, example:
9697   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9698   //    turns into:
9699   //  (MOVLPSmr addr:$src1, VR128:$src2)
9700   // So, recognize this potential and also use MOVLPS or MOVLPD
9701   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9702     CanFoldLoad = true;
9703
9704   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9705   if (CanFoldLoad) {
9706     if (HasSSE2 && NumElems == 2)
9707       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9708
9709     if (NumElems == 4)
9710       // If we don't care about the second element, proceed to use movss.
9711       if (SVOp->getMaskElt(1) != -1)
9712         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9713   }
9714
9715   // movl and movlp will both match v2i64, but v2i64 is never matched by
9716   // movl earlier because we make it strict to avoid messing with the movlp load
9717   // folding logic (see the code above getMOVLP call). Match it here then,
9718   // this is horrible, but will stay like this until we move all shuffle
9719   // matching to x86 specific nodes. Note that for the 1st condition all
9720   // types are matched with movsd.
9721   if (HasSSE2) {
9722     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9723     // as to remove this logic from here, as much as possible
9724     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9725       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9726     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9727   }
9728
9729   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9730
9731   // Invert the operand order and use SHUFPS to match it.
9732   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9733                               getShuffleSHUFImmediate(SVOp), DAG);
9734 }
9735
9736 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9737                                          SelectionDAG &DAG) {
9738   SDLoc dl(Load);
9739   MVT VT = Load->getSimpleValueType(0);
9740   MVT EVT = VT.getVectorElementType();
9741   SDValue Addr = Load->getOperand(1);
9742   SDValue NewAddr = DAG.getNode(
9743       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9744       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9745
9746   SDValue NewLoad =
9747       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9748                   DAG.getMachineFunction().getMachineMemOperand(
9749                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9750   return NewLoad;
9751 }
9752
9753 // It is only safe to call this function if isINSERTPSMask is true for
9754 // this shufflevector mask.
9755 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9756                            SelectionDAG &DAG) {
9757   // Generate an insertps instruction when inserting an f32 from memory onto a
9758   // v4f32 or when copying a member from one v4f32 to another.
9759   // We also use it for transferring i32 from one register to another,
9760   // since it simply copies the same bits.
9761   // If we're transferring an i32 from memory to a specific element in a
9762   // register, we output a generic DAG that will match the PINSRD
9763   // instruction.
9764   MVT VT = SVOp->getSimpleValueType(0);
9765   MVT EVT = VT.getVectorElementType();
9766   SDValue V1 = SVOp->getOperand(0);
9767   SDValue V2 = SVOp->getOperand(1);
9768   auto Mask = SVOp->getMask();
9769   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9770          "unsupported vector type for insertps/pinsrd");
9771
9772   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9773   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9774   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9775
9776   SDValue From;
9777   SDValue To;
9778   unsigned DestIndex;
9779   if (FromV1 == 1) {
9780     From = V1;
9781     To = V2;
9782     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9783                 Mask.begin();
9784
9785     // If we have 1 element from each vector, we have to check if we're
9786     // changing V1's element's place. If so, we're done. Otherwise, we
9787     // should assume we're changing V2's element's place and behave
9788     // accordingly.
9789     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9790     assert(DestIndex <= INT32_MAX && "truncated destination index");
9791     if (FromV1 == FromV2 &&
9792         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9793       From = V2;
9794       To = V1;
9795       DestIndex =
9796           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9797     }
9798   } else {
9799     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9800            "More than one element from V1 and from V2, or no elements from one "
9801            "of the vectors. This case should not have returned true from "
9802            "isINSERTPSMask");
9803     From = V2;
9804     To = V1;
9805     DestIndex =
9806         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9807   }
9808
9809   // Get an index into the source vector in the range [0,4) (the mask is
9810   // in the range [0,8) because it can address V1 and V2)
9811   unsigned SrcIndex = Mask[DestIndex] % 4;
9812   if (MayFoldLoad(From)) {
9813     // Trivial case, when From comes from a load and is only used by the
9814     // shuffle. Make it use insertps from the vector that we need from that
9815     // load.
9816     SDValue NewLoad =
9817         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9818     if (!NewLoad.getNode())
9819       return SDValue();
9820
9821     if (EVT == MVT::f32) {
9822       // Create this as a scalar to vector to match the instruction pattern.
9823       SDValue LoadScalarToVector =
9824           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9825       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9826       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9827                          InsertpsMask);
9828     } else { // EVT == MVT::i32
9829       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9830       // instruction, to match the PINSRD instruction, which loads an i32 to a
9831       // certain vector element.
9832       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9833                          DAG.getConstant(DestIndex, MVT::i32));
9834     }
9835   }
9836
9837   // Vector-element-to-vector
9838   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9839   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9840 }
9841
9842 // Reduce a vector shuffle to zext.
9843 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9844                                     SelectionDAG &DAG) {
9845   // PMOVZX is only available from SSE41.
9846   if (!Subtarget->hasSSE41())
9847     return SDValue();
9848
9849   MVT VT = Op.getSimpleValueType();
9850
9851   // Only AVX2 support 256-bit vector integer extending.
9852   if (!Subtarget->hasInt256() && VT.is256BitVector())
9853     return SDValue();
9854
9855   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9856   SDLoc DL(Op);
9857   SDValue V1 = Op.getOperand(0);
9858   SDValue V2 = Op.getOperand(1);
9859   unsigned NumElems = VT.getVectorNumElements();
9860
9861   // Extending is an unary operation and the element type of the source vector
9862   // won't be equal to or larger than i64.
9863   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9864       VT.getVectorElementType() == MVT::i64)
9865     return SDValue();
9866
9867   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9868   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9869   while ((1U << Shift) < NumElems) {
9870     if (SVOp->getMaskElt(1U << Shift) == 1)
9871       break;
9872     Shift += 1;
9873     // The maximal ratio is 8, i.e. from i8 to i64.
9874     if (Shift > 3)
9875       return SDValue();
9876   }
9877
9878   // Check the shuffle mask.
9879   unsigned Mask = (1U << Shift) - 1;
9880   for (unsigned i = 0; i != NumElems; ++i) {
9881     int EltIdx = SVOp->getMaskElt(i);
9882     if ((i & Mask) != 0 && EltIdx != -1)
9883       return SDValue();
9884     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9885       return SDValue();
9886   }
9887
9888   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9889   MVT NeVT = MVT::getIntegerVT(NBits);
9890   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9891
9892   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9893     return SDValue();
9894
9895   // Simplify the operand as it's prepared to be fed into shuffle.
9896   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9897   if (V1.getOpcode() == ISD::BITCAST &&
9898       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9899       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9900       V1.getOperand(0).getOperand(0)
9901         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9902     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9903     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9904     ConstantSDNode *CIdx =
9905       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9906     // If it's foldable, i.e. normal load with single use, we will let code
9907     // selection to fold it. Otherwise, we will short the conversion sequence.
9908     if (CIdx && CIdx->getZExtValue() == 0 &&
9909         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9910       MVT FullVT = V.getSimpleValueType();
9911       MVT V1VT = V1.getSimpleValueType();
9912       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9913         // The "ext_vec_elt" node is wider than the result node.
9914         // In this case we should extract subvector from V.
9915         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9916         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9917         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9918                                         FullVT.getVectorNumElements()/Ratio);
9919         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9920                         DAG.getIntPtrConstant(0));
9921       }
9922       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9923     }
9924   }
9925
9926   return DAG.getNode(ISD::BITCAST, DL, VT,
9927                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9928 }
9929
9930 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9931                                       SelectionDAG &DAG) {
9932   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9933   MVT VT = Op.getSimpleValueType();
9934   SDLoc dl(Op);
9935   SDValue V1 = Op.getOperand(0);
9936   SDValue V2 = Op.getOperand(1);
9937
9938   if (isZeroShuffle(SVOp))
9939     return getZeroVector(VT, Subtarget, DAG, dl);
9940
9941   // Handle splat operations
9942   if (SVOp->isSplat()) {
9943     // Use vbroadcast whenever the splat comes from a foldable load
9944     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9945     if (Broadcast.getNode())
9946       return Broadcast;
9947   }
9948
9949   // Check integer expanding shuffles.
9950   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9951   if (NewOp.getNode())
9952     return NewOp;
9953
9954   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9955   // do it!
9956   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9957       VT == MVT::v32i8) {
9958     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9959     if (NewOp.getNode())
9960       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9961   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9962     // FIXME: Figure out a cleaner way to do this.
9963     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9964       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9965       if (NewOp.getNode()) {
9966         MVT NewVT = NewOp.getSimpleValueType();
9967         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9968                                NewVT, true, false))
9969           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9970                               dl);
9971       }
9972     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9973       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9974       if (NewOp.getNode()) {
9975         MVT NewVT = NewOp.getSimpleValueType();
9976         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9977           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9978                               dl);
9979       }
9980     }
9981   }
9982   return SDValue();
9983 }
9984
9985 SDValue
9986 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9987   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9988   SDValue V1 = Op.getOperand(0);
9989   SDValue V2 = Op.getOperand(1);
9990   MVT VT = Op.getSimpleValueType();
9991   SDLoc dl(Op);
9992   unsigned NumElems = VT.getVectorNumElements();
9993   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9994   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9995   bool V1IsSplat = false;
9996   bool V2IsSplat = false;
9997   bool HasSSE2 = Subtarget->hasSSE2();
9998   bool HasFp256    = Subtarget->hasFp256();
9999   bool HasInt256   = Subtarget->hasInt256();
10000   MachineFunction &MF = DAG.getMachineFunction();
10001   bool OptForSize = MF.getFunction()->getAttributes().
10002     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10003
10004   // Check if we should use the experimental vector shuffle lowering. If so,
10005   // delegate completely to that code path.
10006   if (ExperimentalVectorShuffleLowering)
10007     return lowerVectorShuffle(Op, Subtarget, DAG);
10008
10009   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10010
10011   if (V1IsUndef && V2IsUndef)
10012     return DAG.getUNDEF(VT);
10013
10014   // When we create a shuffle node we put the UNDEF node to second operand,
10015   // but in some cases the first operand may be transformed to UNDEF.
10016   // In this case we should just commute the node.
10017   if (V1IsUndef)
10018     return DAG.getCommutedVectorShuffle(*SVOp);
10019
10020   // Vector shuffle lowering takes 3 steps:
10021   //
10022   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10023   //    narrowing and commutation of operands should be handled.
10024   // 2) Matching of shuffles with known shuffle masks to x86 target specific
10025   //    shuffle nodes.
10026   // 3) Rewriting of unmatched masks into new generic shuffle operations,
10027   //    so the shuffle can be broken into other shuffles and the legalizer can
10028   //    try the lowering again.
10029   //
10030   // The general idea is that no vector_shuffle operation should be left to
10031   // be matched during isel, all of them must be converted to a target specific
10032   // node here.
10033
10034   // Normalize the input vectors. Here splats, zeroed vectors, profitable
10035   // narrowing and commutation of operands should be handled. The actual code
10036   // doesn't include all of those, work in progress...
10037   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10038   if (NewOp.getNode())
10039     return NewOp;
10040
10041   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10042
10043   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10044   // unpckh_undef). Only use pshufd if speed is more important than size.
10045   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10046     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10047   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10048     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10049
10050   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10051       V2IsUndef && MayFoldVectorLoad(V1))
10052     return getMOVDDup(Op, dl, V1, DAG);
10053
10054   if (isMOVHLPS_v_undef_Mask(M, VT))
10055     return getMOVHighToLow(Op, dl, DAG);
10056
10057   // Use to match splats
10058   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10059       (VT == MVT::v2f64 || VT == MVT::v2i64))
10060     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10061
10062   if (isPSHUFDMask(M, VT)) {
10063     // The actual implementation will match the mask in the if above and then
10064     // during isel it can match several different instructions, not only pshufd
10065     // as its name says, sad but true, emulate the behavior for now...
10066     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10067       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10068
10069     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10070
10071     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10072       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10073
10074     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10075       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10076                                   DAG);
10077
10078     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10079                                 TargetMask, DAG);
10080   }
10081
10082   if (isPALIGNRMask(M, VT, Subtarget))
10083     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10084                                 getShufflePALIGNRImmediate(SVOp),
10085                                 DAG);
10086
10087   if (isVALIGNMask(M, VT, Subtarget))
10088     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10089                                 getShuffleVALIGNImmediate(SVOp),
10090                                 DAG);
10091
10092   // Check if this can be converted into a logical shift.
10093   bool isLeft = false;
10094   unsigned ShAmt = 0;
10095   SDValue ShVal;
10096   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10097   if (isShift && ShVal.hasOneUse()) {
10098     // If the shifted value has multiple uses, it may be cheaper to use
10099     // v_set0 + movlhps or movhlps, etc.
10100     MVT EltVT = VT.getVectorElementType();
10101     ShAmt *= EltVT.getSizeInBits();
10102     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10103   }
10104
10105   if (isMOVLMask(M, VT)) {
10106     if (ISD::isBuildVectorAllZeros(V1.getNode()))
10107       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10108     if (!isMOVLPMask(M, VT)) {
10109       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10110         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10111
10112       if (VT == MVT::v4i32 || VT == MVT::v4f32)
10113         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10114     }
10115   }
10116
10117   // FIXME: fold these into legal mask.
10118   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10119     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10120
10121   if (isMOVHLPSMask(M, VT))
10122     return getMOVHighToLow(Op, dl, DAG);
10123
10124   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10125     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10126
10127   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10128     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10129
10130   if (isMOVLPMask(M, VT))
10131     return getMOVLP(Op, dl, DAG, HasSSE2);
10132
10133   if (ShouldXformToMOVHLPS(M, VT) ||
10134       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10135     return DAG.getCommutedVectorShuffle(*SVOp);
10136
10137   if (isShift) {
10138     // No better options. Use a vshldq / vsrldq.
10139     MVT EltVT = VT.getVectorElementType();
10140     ShAmt *= EltVT.getSizeInBits();
10141     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10142   }
10143
10144   bool Commuted = false;
10145   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
10146   // 1,1,1,1 -> v8i16 though.
10147   BitVector UndefElements;
10148   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10149     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10150       V1IsSplat = true;
10151   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10152     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10153       V2IsSplat = true;
10154
10155   // Canonicalize the splat or undef, if present, to be on the RHS.
10156   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10157     CommuteVectorShuffleMask(M, NumElems);
10158     std::swap(V1, V2);
10159     std::swap(V1IsSplat, V2IsSplat);
10160     Commuted = true;
10161   }
10162
10163   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10164     // Shuffling low element of v1 into undef, just return v1.
10165     if (V2IsUndef)
10166       return V1;
10167     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10168     // the instruction selector will not match, so get a canonical MOVL with
10169     // swapped operands to undo the commute.
10170     return getMOVL(DAG, dl, VT, V2, V1);
10171   }
10172
10173   if (isUNPCKLMask(M, VT, HasInt256))
10174     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10175
10176   if (isUNPCKHMask(M, VT, HasInt256))
10177     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10178
10179   if (V2IsSplat) {
10180     // Normalize mask so all entries that point to V2 points to its first
10181     // element then try to match unpck{h|l} again. If match, return a
10182     // new vector_shuffle with the corrected mask.p
10183     SmallVector<int, 8> NewMask(M.begin(), M.end());
10184     NormalizeMask(NewMask, NumElems);
10185     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10186       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10187     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10188       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10189   }
10190
10191   if (Commuted) {
10192     // Commute is back and try unpck* again.
10193     // FIXME: this seems wrong.
10194     CommuteVectorShuffleMask(M, NumElems);
10195     std::swap(V1, V2);
10196     std::swap(V1IsSplat, V2IsSplat);
10197
10198     if (isUNPCKLMask(M, VT, HasInt256))
10199       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10200
10201     if (isUNPCKHMask(M, VT, HasInt256))
10202       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10203   }
10204
10205   // Normalize the node to match x86 shuffle ops if needed
10206   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10207     return DAG.getCommutedVectorShuffle(*SVOp);
10208
10209   // The checks below are all present in isShuffleMaskLegal, but they are
10210   // inlined here right now to enable us to directly emit target specific
10211   // nodes, and remove one by one until they don't return Op anymore.
10212
10213   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10214       SVOp->getSplatIndex() == 0 && V2IsUndef) {
10215     if (VT == MVT::v2f64 || VT == MVT::v2i64)
10216       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10217   }
10218
10219   if (isPSHUFHWMask(M, VT, HasInt256))
10220     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10221                                 getShufflePSHUFHWImmediate(SVOp),
10222                                 DAG);
10223
10224   if (isPSHUFLWMask(M, VT, HasInt256))
10225     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10226                                 getShufflePSHUFLWImmediate(SVOp),
10227                                 DAG);
10228
10229   unsigned MaskValue;
10230   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10231                   &MaskValue))
10232     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10233
10234   if (isSHUFPMask(M, VT))
10235     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10236                                 getShuffleSHUFImmediate(SVOp), DAG);
10237
10238   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10239     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10240   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10241     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10242
10243   //===--------------------------------------------------------------------===//
10244   // Generate target specific nodes for 128 or 256-bit shuffles only
10245   // supported in the AVX instruction set.
10246   //
10247
10248   // Handle VMOVDDUPY permutations
10249   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10250     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10251
10252   // Handle VPERMILPS/D* permutations
10253   if (isVPERMILPMask(M, VT)) {
10254     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10255       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10256                                   getShuffleSHUFImmediate(SVOp), DAG);
10257     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10258                                 getShuffleSHUFImmediate(SVOp), DAG);
10259   }
10260
10261   unsigned Idx;
10262   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10263     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10264                               Idx*(NumElems/2), DAG, dl);
10265
10266   // Handle VPERM2F128/VPERM2I128 permutations
10267   if (isVPERM2X128Mask(M, VT, HasFp256))
10268     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10269                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10270
10271   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10272     return getINSERTPS(SVOp, dl, DAG);
10273
10274   unsigned Imm8;
10275   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10276     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10277
10278   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10279       VT.is512BitVector()) {
10280     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10281     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10282     SmallVector<SDValue, 16> permclMask;
10283     for (unsigned i = 0; i != NumElems; ++i) {
10284       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10285     }
10286
10287     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10288     if (V2IsUndef)
10289       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10290       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10291                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10292     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10293                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10294   }
10295
10296   //===--------------------------------------------------------------------===//
10297   // Since no target specific shuffle was selected for this generic one,
10298   // lower it into other known shuffles. FIXME: this isn't true yet, but
10299   // this is the plan.
10300   //
10301
10302   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10303   if (VT == MVT::v8i16) {
10304     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10305     if (NewOp.getNode())
10306       return NewOp;
10307   }
10308
10309   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10310     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10311     if (NewOp.getNode())
10312       return NewOp;
10313   }
10314
10315   if (VT == MVT::v16i8) {
10316     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10317     if (NewOp.getNode())
10318       return NewOp;
10319   }
10320
10321   if (VT == MVT::v32i8) {
10322     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10323     if (NewOp.getNode())
10324       return NewOp;
10325   }
10326
10327   // Handle all 128-bit wide vectors with 4 elements, and match them with
10328   // several different shuffle types.
10329   if (NumElems == 4 && VT.is128BitVector())
10330     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10331
10332   // Handle general 256-bit shuffles
10333   if (VT.is256BitVector())
10334     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10335
10336   return SDValue();
10337 }
10338
10339 // This function assumes its argument is a BUILD_VECTOR of constants or
10340 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10341 // true.
10342 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10343                                     unsigned &MaskValue) {
10344   MaskValue = 0;
10345   unsigned NumElems = BuildVector->getNumOperands();
10346   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10347   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10348   unsigned NumElemsInLane = NumElems / NumLanes;
10349
10350   // Blend for v16i16 should be symetric for the both lanes.
10351   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10352     SDValue EltCond = BuildVector->getOperand(i);
10353     SDValue SndLaneEltCond =
10354         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10355
10356     int Lane1Cond = -1, Lane2Cond = -1;
10357     if (isa<ConstantSDNode>(EltCond))
10358       Lane1Cond = !isZero(EltCond);
10359     if (isa<ConstantSDNode>(SndLaneEltCond))
10360       Lane2Cond = !isZero(SndLaneEltCond);
10361
10362     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10363       // Lane1Cond != 0, means we want the first argument.
10364       // Lane1Cond == 0, means we want the second argument.
10365       // The encoding of this argument is 0 for the first argument, 1
10366       // for the second. Therefore, invert the condition.
10367       MaskValue |= !Lane1Cond << i;
10368     else if (Lane1Cond < 0)
10369       MaskValue |= !Lane2Cond << i;
10370     else
10371       return false;
10372   }
10373   return true;
10374 }
10375
10376 // Try to lower a vselect node into a simple blend instruction.
10377 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10378                                    SelectionDAG &DAG) {
10379   SDValue Cond = Op.getOperand(0);
10380   SDValue LHS = Op.getOperand(1);
10381   SDValue RHS = Op.getOperand(2);
10382   SDLoc dl(Op);
10383   MVT VT = Op.getSimpleValueType();
10384   MVT EltVT = VT.getVectorElementType();
10385   unsigned NumElems = VT.getVectorNumElements();
10386
10387   // There is no blend with immediate in AVX-512.
10388   if (VT.is512BitVector())
10389     return SDValue();
10390
10391   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10392     return SDValue();
10393   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10394     return SDValue();
10395
10396   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10397     return SDValue();
10398
10399   // Check the mask for BLEND and build the value.
10400   unsigned MaskValue = 0;
10401   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10402     return SDValue();
10403
10404   // Convert i32 vectors to floating point if it is not AVX2.
10405   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10406   MVT BlendVT = VT;
10407   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10408     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10409                                NumElems);
10410     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10411     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10412   }
10413
10414   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10415                             DAG.getConstant(MaskValue, MVT::i32));
10416   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10417 }
10418
10419 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10420   // A vselect where all conditions and data are constants can be optimized into
10421   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10422   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10423       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10424       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10425     return SDValue();
10426   
10427   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10428   if (BlendOp.getNode())
10429     return BlendOp;
10430
10431   // Some types for vselect were previously set to Expand, not Legal or
10432   // Custom. Return an empty SDValue so we fall-through to Expand, after
10433   // the Custom lowering phase.
10434   MVT VT = Op.getSimpleValueType();
10435   switch (VT.SimpleTy) {
10436   default:
10437     break;
10438   case MVT::v8i16:
10439   case MVT::v16i16:
10440     return SDValue();
10441   }
10442
10443   // We couldn't create a "Blend with immediate" node.
10444   // This node should still be legal, but we'll have to emit a blendv*
10445   // instruction.
10446   return Op;
10447 }
10448
10449 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10450   MVT VT = Op.getSimpleValueType();
10451   SDLoc dl(Op);
10452
10453   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10454     return SDValue();
10455
10456   if (VT.getSizeInBits() == 8) {
10457     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10458                                   Op.getOperand(0), Op.getOperand(1));
10459     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10460                                   DAG.getValueType(VT));
10461     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10462   }
10463
10464   if (VT.getSizeInBits() == 16) {
10465     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10466     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10467     if (Idx == 0)
10468       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10469                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10470                                      DAG.getNode(ISD::BITCAST, dl,
10471                                                  MVT::v4i32,
10472                                                  Op.getOperand(0)),
10473                                      Op.getOperand(1)));
10474     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10475                                   Op.getOperand(0), Op.getOperand(1));
10476     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10477                                   DAG.getValueType(VT));
10478     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10479   }
10480
10481   if (VT == MVT::f32) {
10482     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10483     // the result back to FR32 register. It's only worth matching if the
10484     // result has a single use which is a store or a bitcast to i32.  And in
10485     // the case of a store, it's not worth it if the index is a constant 0,
10486     // because a MOVSSmr can be used instead, which is smaller and faster.
10487     if (!Op.hasOneUse())
10488       return SDValue();
10489     SDNode *User = *Op.getNode()->use_begin();
10490     if ((User->getOpcode() != ISD::STORE ||
10491          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10492           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10493         (User->getOpcode() != ISD::BITCAST ||
10494          User->getValueType(0) != MVT::i32))
10495       return SDValue();
10496     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10497                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10498                                               Op.getOperand(0)),
10499                                               Op.getOperand(1));
10500     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10501   }
10502
10503   if (VT == MVT::i32 || VT == MVT::i64) {
10504     // ExtractPS/pextrq works with constant index.
10505     if (isa<ConstantSDNode>(Op.getOperand(1)))
10506       return Op;
10507   }
10508   return SDValue();
10509 }
10510
10511 /// Extract one bit from mask vector, like v16i1 or v8i1.
10512 /// AVX-512 feature.
10513 SDValue
10514 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10515   SDValue Vec = Op.getOperand(0);
10516   SDLoc dl(Vec);
10517   MVT VecVT = Vec.getSimpleValueType();
10518   SDValue Idx = Op.getOperand(1);
10519   MVT EltVT = Op.getSimpleValueType();
10520
10521   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10522
10523   // variable index can't be handled in mask registers,
10524   // extend vector to VR512
10525   if (!isa<ConstantSDNode>(Idx)) {
10526     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10527     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10528     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10529                               ExtVT.getVectorElementType(), Ext, Idx);
10530     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10531   }
10532
10533   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10534   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10535   unsigned MaxSift = rc->getSize()*8 - 1;
10536   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10537                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10538   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10539                     DAG.getConstant(MaxSift, MVT::i8));
10540   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10541                        DAG.getIntPtrConstant(0));
10542 }
10543
10544 SDValue
10545 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10546                                            SelectionDAG &DAG) const {
10547   SDLoc dl(Op);
10548   SDValue Vec = Op.getOperand(0);
10549   MVT VecVT = Vec.getSimpleValueType();
10550   SDValue Idx = Op.getOperand(1);
10551
10552   if (Op.getSimpleValueType() == MVT::i1)
10553     return ExtractBitFromMaskVector(Op, DAG);
10554
10555   if (!isa<ConstantSDNode>(Idx)) {
10556     if (VecVT.is512BitVector() ||
10557         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10558          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10559
10560       MVT MaskEltVT =
10561         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10562       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10563                                     MaskEltVT.getSizeInBits());
10564
10565       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10566       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10567                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10568                                 Idx, DAG.getConstant(0, getPointerTy()));
10569       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10570       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10571                         Perm, DAG.getConstant(0, getPointerTy()));
10572     }
10573     return SDValue();
10574   }
10575
10576   // If this is a 256-bit vector result, first extract the 128-bit vector and
10577   // then extract the element from the 128-bit vector.
10578   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10579
10580     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10581     // Get the 128-bit vector.
10582     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10583     MVT EltVT = VecVT.getVectorElementType();
10584
10585     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10586
10587     //if (IdxVal >= NumElems/2)
10588     //  IdxVal -= NumElems/2;
10589     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10590     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10591                        DAG.getConstant(IdxVal, MVT::i32));
10592   }
10593
10594   assert(VecVT.is128BitVector() && "Unexpected vector length");
10595
10596   if (Subtarget->hasSSE41()) {
10597     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10598     if (Res.getNode())
10599       return Res;
10600   }
10601
10602   MVT VT = Op.getSimpleValueType();
10603   // TODO: handle v16i8.
10604   if (VT.getSizeInBits() == 16) {
10605     SDValue Vec = Op.getOperand(0);
10606     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10607     if (Idx == 0)
10608       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10609                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10610                                      DAG.getNode(ISD::BITCAST, dl,
10611                                                  MVT::v4i32, Vec),
10612                                      Op.getOperand(1)));
10613     // Transform it so it match pextrw which produces a 32-bit result.
10614     MVT EltVT = MVT::i32;
10615     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10616                                   Op.getOperand(0), Op.getOperand(1));
10617     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10618                                   DAG.getValueType(VT));
10619     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10620   }
10621
10622   if (VT.getSizeInBits() == 32) {
10623     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10624     if (Idx == 0)
10625       return Op;
10626
10627     // SHUFPS the element to the lowest double word, then movss.
10628     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10629     MVT VVT = Op.getOperand(0).getSimpleValueType();
10630     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10631                                        DAG.getUNDEF(VVT), Mask);
10632     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10633                        DAG.getIntPtrConstant(0));
10634   }
10635
10636   if (VT.getSizeInBits() == 64) {
10637     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10638     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10639     //        to match extract_elt for f64.
10640     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10641     if (Idx == 0)
10642       return Op;
10643
10644     // UNPCKHPD the element to the lowest double word, then movsd.
10645     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10646     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10647     int Mask[2] = { 1, -1 };
10648     MVT VVT = Op.getOperand(0).getSimpleValueType();
10649     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10650                                        DAG.getUNDEF(VVT), Mask);
10651     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10652                        DAG.getIntPtrConstant(0));
10653   }
10654
10655   return SDValue();
10656 }
10657
10658 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10659   MVT VT = Op.getSimpleValueType();
10660   MVT EltVT = VT.getVectorElementType();
10661   SDLoc dl(Op);
10662
10663   SDValue N0 = Op.getOperand(0);
10664   SDValue N1 = Op.getOperand(1);
10665   SDValue N2 = Op.getOperand(2);
10666
10667   if (!VT.is128BitVector())
10668     return SDValue();
10669
10670   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10671       isa<ConstantSDNode>(N2)) {
10672     unsigned Opc;
10673     if (VT == MVT::v8i16) {
10674       Opc = X86ISD::PINSRW;
10675     } else {
10676       assert(VT == MVT::v16i8);
10677       Opc = X86ISD::PINSRB;
10678     }
10679
10680     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10681     // argument.
10682     if (N1.getValueType() != MVT::i32)
10683       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10684     if (N2.getValueType() != MVT::i32)
10685       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10686     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10687   }
10688
10689   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10690     // Bits [7:6] of the constant are the source select.  This will always be
10691     //  zero here.  The DAG Combiner may combine an extract_elt index into these
10692     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
10693     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10694     // Bits [5:4] of the constant are the destination select.  This is the
10695     //  value of the incoming immediate.
10696     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10697     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10698     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10699     // Create this as a scalar to vector..
10700     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10701     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10702   }
10703
10704   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10705     // PINSR* works with constant index.
10706     return Op;
10707   }
10708   return SDValue();
10709 }
10710
10711 /// Insert one bit to mask vector, like v16i1 or v8i1.
10712 /// AVX-512 feature.
10713 SDValue 
10714 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10715   SDLoc dl(Op);
10716   SDValue Vec = Op.getOperand(0);
10717   SDValue Elt = Op.getOperand(1);
10718   SDValue Idx = Op.getOperand(2);
10719   MVT VecVT = Vec.getSimpleValueType();
10720
10721   if (!isa<ConstantSDNode>(Idx)) {
10722     // Non constant index. Extend source and destination,
10723     // insert element and then truncate the result.
10724     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10725     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10726     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10727       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10728       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10729     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10730   }
10731
10732   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10733   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10734   if (Vec.getOpcode() == ISD::UNDEF)
10735     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10736                        DAG.getConstant(IdxVal, MVT::i8));
10737   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10738   unsigned MaxSift = rc->getSize()*8 - 1;
10739   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10740                     DAG.getConstant(MaxSift, MVT::i8));
10741   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10742                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10743   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10744 }
10745 SDValue
10746 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10747   MVT VT = Op.getSimpleValueType();
10748   MVT EltVT = VT.getVectorElementType();
10749   
10750   if (EltVT == MVT::i1)
10751     return InsertBitToMaskVector(Op, DAG);
10752
10753   SDLoc dl(Op);
10754   SDValue N0 = Op.getOperand(0);
10755   SDValue N1 = Op.getOperand(1);
10756   SDValue N2 = Op.getOperand(2);
10757
10758   // If this is a 256-bit vector result, first extract the 128-bit vector,
10759   // insert the element into the extracted half and then place it back.
10760   if (VT.is256BitVector() || VT.is512BitVector()) {
10761     if (!isa<ConstantSDNode>(N2))
10762       return SDValue();
10763
10764     // Get the desired 128-bit vector half.
10765     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10766     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10767
10768     // Insert the element into the desired half.
10769     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10770     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10771
10772     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10773                     DAG.getConstant(IdxIn128, MVT::i32));
10774
10775     // Insert the changed part back to the 256-bit vector
10776     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10777   }
10778
10779   if (Subtarget->hasSSE41())
10780     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10781
10782   if (EltVT == MVT::i8)
10783     return SDValue();
10784
10785   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10786     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10787     // as its second argument.
10788     if (N1.getValueType() != MVT::i32)
10789       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10790     if (N2.getValueType() != MVT::i32)
10791       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10792     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10793   }
10794   return SDValue();
10795 }
10796
10797 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10798   SDLoc dl(Op);
10799   MVT OpVT = Op.getSimpleValueType();
10800
10801   // If this is a 256-bit vector result, first insert into a 128-bit
10802   // vector and then insert into the 256-bit vector.
10803   if (!OpVT.is128BitVector()) {
10804     // Insert into a 128-bit vector.
10805     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10806     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10807                                  OpVT.getVectorNumElements() / SizeFactor);
10808
10809     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10810
10811     // Insert the 128-bit vector.
10812     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10813   }
10814
10815   if (OpVT == MVT::v1i64 &&
10816       Op.getOperand(0).getValueType() == MVT::i64)
10817     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10818
10819   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10820   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10821   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10822                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10823 }
10824
10825 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10826 // a simple subregister reference or explicit instructions to grab
10827 // upper bits of a vector.
10828 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10829                                       SelectionDAG &DAG) {
10830   SDLoc dl(Op);
10831   SDValue In =  Op.getOperand(0);
10832   SDValue Idx = Op.getOperand(1);
10833   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10834   MVT ResVT   = Op.getSimpleValueType();
10835   MVT InVT    = In.getSimpleValueType();
10836
10837   if (Subtarget->hasFp256()) {
10838     if (ResVT.is128BitVector() &&
10839         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10840         isa<ConstantSDNode>(Idx)) {
10841       return Extract128BitVector(In, IdxVal, DAG, dl);
10842     }
10843     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10844         isa<ConstantSDNode>(Idx)) {
10845       return Extract256BitVector(In, IdxVal, DAG, dl);
10846     }
10847   }
10848   return SDValue();
10849 }
10850
10851 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10852 // simple superregister reference or explicit instructions to insert
10853 // the upper bits of a vector.
10854 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10855                                      SelectionDAG &DAG) {
10856   if (Subtarget->hasFp256()) {
10857     SDLoc dl(Op.getNode());
10858     SDValue Vec = Op.getNode()->getOperand(0);
10859     SDValue SubVec = Op.getNode()->getOperand(1);
10860     SDValue Idx = Op.getNode()->getOperand(2);
10861
10862     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10863          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10864         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10865         isa<ConstantSDNode>(Idx)) {
10866       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10867       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10868     }
10869
10870     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10871         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10872         isa<ConstantSDNode>(Idx)) {
10873       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10874       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10875     }
10876   }
10877   return SDValue();
10878 }
10879
10880 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10881 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10882 // one of the above mentioned nodes. It has to be wrapped because otherwise
10883 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10884 // be used to form addressing mode. These wrapped nodes will be selected
10885 // into MOV32ri.
10886 SDValue
10887 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10888   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10889
10890   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10891   // global base reg.
10892   unsigned char OpFlag = 0;
10893   unsigned WrapperKind = X86ISD::Wrapper;
10894   CodeModel::Model M = DAG.getTarget().getCodeModel();
10895
10896   if (Subtarget->isPICStyleRIPRel() &&
10897       (M == CodeModel::Small || M == CodeModel::Kernel))
10898     WrapperKind = X86ISD::WrapperRIP;
10899   else if (Subtarget->isPICStyleGOT())
10900     OpFlag = X86II::MO_GOTOFF;
10901   else if (Subtarget->isPICStyleStubPIC())
10902     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10903
10904   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10905                                              CP->getAlignment(),
10906                                              CP->getOffset(), OpFlag);
10907   SDLoc DL(CP);
10908   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10909   // With PIC, the address is actually $g + Offset.
10910   if (OpFlag) {
10911     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10912                          DAG.getNode(X86ISD::GlobalBaseReg,
10913                                      SDLoc(), getPointerTy()),
10914                          Result);
10915   }
10916
10917   return Result;
10918 }
10919
10920 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10921   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10922
10923   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10924   // global base reg.
10925   unsigned char OpFlag = 0;
10926   unsigned WrapperKind = X86ISD::Wrapper;
10927   CodeModel::Model M = DAG.getTarget().getCodeModel();
10928
10929   if (Subtarget->isPICStyleRIPRel() &&
10930       (M == CodeModel::Small || M == CodeModel::Kernel))
10931     WrapperKind = X86ISD::WrapperRIP;
10932   else if (Subtarget->isPICStyleGOT())
10933     OpFlag = X86II::MO_GOTOFF;
10934   else if (Subtarget->isPICStyleStubPIC())
10935     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10936
10937   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10938                                           OpFlag);
10939   SDLoc DL(JT);
10940   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10941
10942   // With PIC, the address is actually $g + Offset.
10943   if (OpFlag)
10944     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10945                          DAG.getNode(X86ISD::GlobalBaseReg,
10946                                      SDLoc(), getPointerTy()),
10947                          Result);
10948
10949   return Result;
10950 }
10951
10952 SDValue
10953 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10954   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10955
10956   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10957   // global base reg.
10958   unsigned char OpFlag = 0;
10959   unsigned WrapperKind = X86ISD::Wrapper;
10960   CodeModel::Model M = DAG.getTarget().getCodeModel();
10961
10962   if (Subtarget->isPICStyleRIPRel() &&
10963       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10964     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10965       OpFlag = X86II::MO_GOTPCREL;
10966     WrapperKind = X86ISD::WrapperRIP;
10967   } else if (Subtarget->isPICStyleGOT()) {
10968     OpFlag = X86II::MO_GOT;
10969   } else if (Subtarget->isPICStyleStubPIC()) {
10970     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10971   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10972     OpFlag = X86II::MO_DARWIN_NONLAZY;
10973   }
10974
10975   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10976
10977   SDLoc DL(Op);
10978   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10979
10980   // With PIC, the address is actually $g + Offset.
10981   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10982       !Subtarget->is64Bit()) {
10983     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10984                          DAG.getNode(X86ISD::GlobalBaseReg,
10985                                      SDLoc(), getPointerTy()),
10986                          Result);
10987   }
10988
10989   // For symbols that require a load from a stub to get the address, emit the
10990   // load.
10991   if (isGlobalStubReference(OpFlag))
10992     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10993                          MachinePointerInfo::getGOT(), false, false, false, 0);
10994
10995   return Result;
10996 }
10997
10998 SDValue
10999 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11000   // Create the TargetBlockAddressAddress node.
11001   unsigned char OpFlags =
11002     Subtarget->ClassifyBlockAddressReference();
11003   CodeModel::Model M = DAG.getTarget().getCodeModel();
11004   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11005   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11006   SDLoc dl(Op);
11007   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11008                                              OpFlags);
11009
11010   if (Subtarget->isPICStyleRIPRel() &&
11011       (M == CodeModel::Small || M == CodeModel::Kernel))
11012     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11013   else
11014     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11015
11016   // With PIC, the address is actually $g + Offset.
11017   if (isGlobalRelativeToPICBase(OpFlags)) {
11018     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11019                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11020                          Result);
11021   }
11022
11023   return Result;
11024 }
11025
11026 SDValue
11027 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11028                                       int64_t Offset, SelectionDAG &DAG) const {
11029   // Create the TargetGlobalAddress node, folding in the constant
11030   // offset if it is legal.
11031   unsigned char OpFlags =
11032       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11033   CodeModel::Model M = DAG.getTarget().getCodeModel();
11034   SDValue Result;
11035   if (OpFlags == X86II::MO_NO_FLAG &&
11036       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11037     // A direct static reference to a global.
11038     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11039     Offset = 0;
11040   } else {
11041     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11042   }
11043
11044   if (Subtarget->isPICStyleRIPRel() &&
11045       (M == CodeModel::Small || M == CodeModel::Kernel))
11046     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11047   else
11048     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11049
11050   // With PIC, the address is actually $g + Offset.
11051   if (isGlobalRelativeToPICBase(OpFlags)) {
11052     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11053                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11054                          Result);
11055   }
11056
11057   // For globals that require a load from a stub to get the address, emit the
11058   // load.
11059   if (isGlobalStubReference(OpFlags))
11060     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11061                          MachinePointerInfo::getGOT(), false, false, false, 0);
11062
11063   // If there was a non-zero offset that we didn't fold, create an explicit
11064   // addition for it.
11065   if (Offset != 0)
11066     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11067                          DAG.getConstant(Offset, getPointerTy()));
11068
11069   return Result;
11070 }
11071
11072 SDValue
11073 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11074   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11075   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11076   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11077 }
11078
11079 static SDValue
11080 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11081            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11082            unsigned char OperandFlags, bool LocalDynamic = false) {
11083   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11084   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11085   SDLoc dl(GA);
11086   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11087                                            GA->getValueType(0),
11088                                            GA->getOffset(),
11089                                            OperandFlags);
11090
11091   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11092                                            : X86ISD::TLSADDR;
11093
11094   if (InFlag) {
11095     SDValue Ops[] = { Chain,  TGA, *InFlag };
11096     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11097   } else {
11098     SDValue Ops[]  = { Chain, TGA };
11099     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11100   }
11101
11102   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11103   MFI->setAdjustsStack(true);
11104
11105   SDValue Flag = Chain.getValue(1);
11106   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11107 }
11108
11109 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11110 static SDValue
11111 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11112                                 const EVT PtrVT) {
11113   SDValue InFlag;
11114   SDLoc dl(GA);  // ? function entry point might be better
11115   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11116                                    DAG.getNode(X86ISD::GlobalBaseReg,
11117                                                SDLoc(), PtrVT), InFlag);
11118   InFlag = Chain.getValue(1);
11119
11120   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11121 }
11122
11123 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11124 static SDValue
11125 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11126                                 const EVT PtrVT) {
11127   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11128                     X86::RAX, X86II::MO_TLSGD);
11129 }
11130
11131 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11132                                            SelectionDAG &DAG,
11133                                            const EVT PtrVT,
11134                                            bool is64Bit) {
11135   SDLoc dl(GA);
11136
11137   // Get the start address of the TLS block for this module.
11138   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11139       .getInfo<X86MachineFunctionInfo>();
11140   MFI->incNumLocalDynamicTLSAccesses();
11141
11142   SDValue Base;
11143   if (is64Bit) {
11144     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11145                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11146   } else {
11147     SDValue InFlag;
11148     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11149         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11150     InFlag = Chain.getValue(1);
11151     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11152                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11153   }
11154
11155   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11156   // of Base.
11157
11158   // Build x@dtpoff.
11159   unsigned char OperandFlags = X86II::MO_DTPOFF;
11160   unsigned WrapperKind = X86ISD::Wrapper;
11161   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11162                                            GA->getValueType(0),
11163                                            GA->getOffset(), OperandFlags);
11164   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11165
11166   // Add x@dtpoff with the base.
11167   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11168 }
11169
11170 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11171 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11172                                    const EVT PtrVT, TLSModel::Model model,
11173                                    bool is64Bit, bool isPIC) {
11174   SDLoc dl(GA);
11175
11176   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11177   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11178                                                          is64Bit ? 257 : 256));
11179
11180   SDValue ThreadPointer =
11181       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11182                   MachinePointerInfo(Ptr), false, false, false, 0);
11183
11184   unsigned char OperandFlags = 0;
11185   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11186   // initialexec.
11187   unsigned WrapperKind = X86ISD::Wrapper;
11188   if (model == TLSModel::LocalExec) {
11189     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11190   } else if (model == TLSModel::InitialExec) {
11191     if (is64Bit) {
11192       OperandFlags = X86II::MO_GOTTPOFF;
11193       WrapperKind = X86ISD::WrapperRIP;
11194     } else {
11195       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11196     }
11197   } else {
11198     llvm_unreachable("Unexpected model");
11199   }
11200
11201   // emit "addl x@ntpoff,%eax" (local exec)
11202   // or "addl x@indntpoff,%eax" (initial exec)
11203   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11204   SDValue TGA =
11205       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11206                                  GA->getOffset(), OperandFlags);
11207   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11208
11209   if (model == TLSModel::InitialExec) {
11210     if (isPIC && !is64Bit) {
11211       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11212                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11213                            Offset);
11214     }
11215
11216     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11217                          MachinePointerInfo::getGOT(), false, false, false, 0);
11218   }
11219
11220   // The address of the thread local variable is the add of the thread
11221   // pointer with the offset of the variable.
11222   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11223 }
11224
11225 SDValue
11226 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11227
11228   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11229   const GlobalValue *GV = GA->getGlobal();
11230
11231   if (Subtarget->isTargetELF()) {
11232     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11233
11234     switch (model) {
11235       case TLSModel::GeneralDynamic:
11236         if (Subtarget->is64Bit())
11237           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11238         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11239       case TLSModel::LocalDynamic:
11240         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11241                                            Subtarget->is64Bit());
11242       case TLSModel::InitialExec:
11243       case TLSModel::LocalExec:
11244         return LowerToTLSExecModel(
11245             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11246             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11247     }
11248     llvm_unreachable("Unknown TLS model.");
11249   }
11250
11251   if (Subtarget->isTargetDarwin()) {
11252     // Darwin only has one model of TLS.  Lower to that.
11253     unsigned char OpFlag = 0;
11254     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11255                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11256
11257     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11258     // global base reg.
11259     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11260                  !Subtarget->is64Bit();
11261     if (PIC32)
11262       OpFlag = X86II::MO_TLVP_PIC_BASE;
11263     else
11264       OpFlag = X86II::MO_TLVP;
11265     SDLoc DL(Op);
11266     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11267                                                 GA->getValueType(0),
11268                                                 GA->getOffset(), OpFlag);
11269     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11270
11271     // With PIC32, the address is actually $g + Offset.
11272     if (PIC32)
11273       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11274                            DAG.getNode(X86ISD::GlobalBaseReg,
11275                                        SDLoc(), getPointerTy()),
11276                            Offset);
11277
11278     // Lowering the machine isd will make sure everything is in the right
11279     // location.
11280     SDValue Chain = DAG.getEntryNode();
11281     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11282     SDValue Args[] = { Chain, Offset };
11283     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11284
11285     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11286     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11287     MFI->setAdjustsStack(true);
11288
11289     // And our return value (tls address) is in the standard call return value
11290     // location.
11291     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11292     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11293                               Chain.getValue(1));
11294   }
11295
11296   if (Subtarget->isTargetKnownWindowsMSVC() ||
11297       Subtarget->isTargetWindowsGNU()) {
11298     // Just use the implicit TLS architecture
11299     // Need to generate someting similar to:
11300     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11301     //                                  ; from TEB
11302     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11303     //   mov     rcx, qword [rdx+rcx*8]
11304     //   mov     eax, .tls$:tlsvar
11305     //   [rax+rcx] contains the address
11306     // Windows 64bit: gs:0x58
11307     // Windows 32bit: fs:__tls_array
11308
11309     SDLoc dl(GA);
11310     SDValue Chain = DAG.getEntryNode();
11311
11312     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11313     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11314     // use its literal value of 0x2C.
11315     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11316                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11317                                                              256)
11318                                         : Type::getInt32PtrTy(*DAG.getContext(),
11319                                                               257));
11320
11321     SDValue TlsArray =
11322         Subtarget->is64Bit()
11323             ? DAG.getIntPtrConstant(0x58)
11324             : (Subtarget->isTargetWindowsGNU()
11325                    ? DAG.getIntPtrConstant(0x2C)
11326                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11327
11328     SDValue ThreadPointer =
11329         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11330                     MachinePointerInfo(Ptr), false, false, false, 0);
11331
11332     // Load the _tls_index variable
11333     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11334     if (Subtarget->is64Bit())
11335       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11336                            IDX, MachinePointerInfo(), MVT::i32,
11337                            false, false, false, 0);
11338     else
11339       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11340                         false, false, false, 0);
11341
11342     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11343                                     getPointerTy());
11344     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11345
11346     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11347     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11348                       false, false, false, 0);
11349
11350     // Get the offset of start of .tls section
11351     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11352                                              GA->getValueType(0),
11353                                              GA->getOffset(), X86II::MO_SECREL);
11354     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11355
11356     // The address of the thread local variable is the add of the thread
11357     // pointer with the offset of the variable.
11358     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11359   }
11360
11361   llvm_unreachable("TLS not implemented for this target.");
11362 }
11363
11364 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11365 /// and take a 2 x i32 value to shift plus a shift amount.
11366 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11367   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11368   MVT VT = Op.getSimpleValueType();
11369   unsigned VTBits = VT.getSizeInBits();
11370   SDLoc dl(Op);
11371   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11372   SDValue ShOpLo = Op.getOperand(0);
11373   SDValue ShOpHi = Op.getOperand(1);
11374   SDValue ShAmt  = Op.getOperand(2);
11375   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11376   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11377   // during isel.
11378   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11379                                   DAG.getConstant(VTBits - 1, MVT::i8));
11380   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11381                                      DAG.getConstant(VTBits - 1, MVT::i8))
11382                        : DAG.getConstant(0, VT);
11383
11384   SDValue Tmp2, Tmp3;
11385   if (Op.getOpcode() == ISD::SHL_PARTS) {
11386     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11387     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11388   } else {
11389     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11390     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11391   }
11392
11393   // If the shift amount is larger or equal than the width of a part we can't
11394   // rely on the results of shld/shrd. Insert a test and select the appropriate
11395   // values for large shift amounts.
11396   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11397                                 DAG.getConstant(VTBits, MVT::i8));
11398   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11399                              AndNode, DAG.getConstant(0, MVT::i8));
11400
11401   SDValue Hi, Lo;
11402   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11403   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11404   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11405
11406   if (Op.getOpcode() == ISD::SHL_PARTS) {
11407     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11408     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11409   } else {
11410     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11411     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11412   }
11413
11414   SDValue Ops[2] = { Lo, Hi };
11415   return DAG.getMergeValues(Ops, dl);
11416 }
11417
11418 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11419                                            SelectionDAG &DAG) const {
11420   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11421
11422   if (SrcVT.isVector())
11423     return SDValue();
11424
11425   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11426          "Unknown SINT_TO_FP to lower!");
11427
11428   // These are really Legal; return the operand so the caller accepts it as
11429   // Legal.
11430   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11431     return Op;
11432   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11433       Subtarget->is64Bit()) {
11434     return Op;
11435   }
11436
11437   SDLoc dl(Op);
11438   unsigned Size = SrcVT.getSizeInBits()/8;
11439   MachineFunction &MF = DAG.getMachineFunction();
11440   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11441   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11442   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11443                                StackSlot,
11444                                MachinePointerInfo::getFixedStack(SSFI),
11445                                false, false, 0);
11446   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11447 }
11448
11449 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11450                                      SDValue StackSlot,
11451                                      SelectionDAG &DAG) const {
11452   // Build the FILD
11453   SDLoc DL(Op);
11454   SDVTList Tys;
11455   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11456   if (useSSE)
11457     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11458   else
11459     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11460
11461   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11462
11463   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11464   MachineMemOperand *MMO;
11465   if (FI) {
11466     int SSFI = FI->getIndex();
11467     MMO =
11468       DAG.getMachineFunction()
11469       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11470                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11471   } else {
11472     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11473     StackSlot = StackSlot.getOperand(1);
11474   }
11475   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11476   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11477                                            X86ISD::FILD, DL,
11478                                            Tys, Ops, SrcVT, MMO);
11479
11480   if (useSSE) {
11481     Chain = Result.getValue(1);
11482     SDValue InFlag = Result.getValue(2);
11483
11484     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11485     // shouldn't be necessary except that RFP cannot be live across
11486     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11487     MachineFunction &MF = DAG.getMachineFunction();
11488     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11489     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11490     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11491     Tys = DAG.getVTList(MVT::Other);
11492     SDValue Ops[] = {
11493       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11494     };
11495     MachineMemOperand *MMO =
11496       DAG.getMachineFunction()
11497       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11498                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11499
11500     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11501                                     Ops, Op.getValueType(), MMO);
11502     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11503                          MachinePointerInfo::getFixedStack(SSFI),
11504                          false, false, false, 0);
11505   }
11506
11507   return Result;
11508 }
11509
11510 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11511 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11512                                                SelectionDAG &DAG) const {
11513   // This algorithm is not obvious. Here it is what we're trying to output:
11514   /*
11515      movq       %rax,  %xmm0
11516      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11517      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11518      #ifdef __SSE3__
11519        haddpd   %xmm0, %xmm0
11520      #else
11521        pshufd   $0x4e, %xmm0, %xmm1
11522        addpd    %xmm1, %xmm0
11523      #endif
11524   */
11525
11526   SDLoc dl(Op);
11527   LLVMContext *Context = DAG.getContext();
11528
11529   // Build some magic constants.
11530   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11531   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11532   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11533
11534   SmallVector<Constant*,2> CV1;
11535   CV1.push_back(
11536     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11537                                       APInt(64, 0x4330000000000000ULL))));
11538   CV1.push_back(
11539     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11540                                       APInt(64, 0x4530000000000000ULL))));
11541   Constant *C1 = ConstantVector::get(CV1);
11542   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11543
11544   // Load the 64-bit value into an XMM register.
11545   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11546                             Op.getOperand(0));
11547   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11548                               MachinePointerInfo::getConstantPool(),
11549                               false, false, false, 16);
11550   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11551                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11552                               CLod0);
11553
11554   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11555                               MachinePointerInfo::getConstantPool(),
11556                               false, false, false, 16);
11557   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11558   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11559   SDValue Result;
11560
11561   if (Subtarget->hasSSE3()) {
11562     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11563     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11564   } else {
11565     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11566     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11567                                            S2F, 0x4E, DAG);
11568     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11569                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11570                          Sub);
11571   }
11572
11573   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11574                      DAG.getIntPtrConstant(0));
11575 }
11576
11577 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11578 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11579                                                SelectionDAG &DAG) const {
11580   SDLoc dl(Op);
11581   // FP constant to bias correct the final result.
11582   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11583                                    MVT::f64);
11584
11585   // Load the 32-bit value into an XMM register.
11586   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11587                              Op.getOperand(0));
11588
11589   // Zero out the upper parts of the register.
11590   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11591
11592   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11593                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11594                      DAG.getIntPtrConstant(0));
11595
11596   // Or the load with the bias.
11597   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11598                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11599                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11600                                                    MVT::v2f64, Load)),
11601                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11602                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11603                                                    MVT::v2f64, Bias)));
11604   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11605                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11606                    DAG.getIntPtrConstant(0));
11607
11608   // Subtract the bias.
11609   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11610
11611   // Handle final rounding.
11612   EVT DestVT = Op.getValueType();
11613
11614   if (DestVT.bitsLT(MVT::f64))
11615     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11616                        DAG.getIntPtrConstant(0));
11617   if (DestVT.bitsGT(MVT::f64))
11618     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11619
11620   // Handle final rounding.
11621   return Sub;
11622 }
11623
11624 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11625                                                SelectionDAG &DAG) const {
11626   SDValue N0 = Op.getOperand(0);
11627   MVT SVT = N0.getSimpleValueType();
11628   SDLoc dl(Op);
11629
11630   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11631           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11632          "Custom UINT_TO_FP is not supported!");
11633
11634   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11635   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11636                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11637 }
11638
11639 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11640                                            SelectionDAG &DAG) const {
11641   SDValue N0 = Op.getOperand(0);
11642   SDLoc dl(Op);
11643
11644   if (Op.getValueType().isVector())
11645     return lowerUINT_TO_FP_vec(Op, DAG);
11646
11647   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11648   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11649   // the optimization here.
11650   if (DAG.SignBitIsZero(N0))
11651     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11652
11653   MVT SrcVT = N0.getSimpleValueType();
11654   MVT DstVT = Op.getSimpleValueType();
11655   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11656     return LowerUINT_TO_FP_i64(Op, DAG);
11657   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11658     return LowerUINT_TO_FP_i32(Op, DAG);
11659   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11660     return SDValue();
11661
11662   // Make a 64-bit buffer, and use it to build an FILD.
11663   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11664   if (SrcVT == MVT::i32) {
11665     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11666     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11667                                      getPointerTy(), StackSlot, WordOff);
11668     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11669                                   StackSlot, MachinePointerInfo(),
11670                                   false, false, 0);
11671     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11672                                   OffsetSlot, MachinePointerInfo(),
11673                                   false, false, 0);
11674     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11675     return Fild;
11676   }
11677
11678   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11679   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11680                                StackSlot, MachinePointerInfo(),
11681                                false, false, 0);
11682   // For i64 source, we need to add the appropriate power of 2 if the input
11683   // was negative.  This is the same as the optimization in
11684   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11685   // we must be careful to do the computation in x87 extended precision, not
11686   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11687   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11688   MachineMemOperand *MMO =
11689     DAG.getMachineFunction()
11690     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11691                           MachineMemOperand::MOLoad, 8, 8);
11692
11693   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11694   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11695   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11696                                          MVT::i64, MMO);
11697
11698   APInt FF(32, 0x5F800000ULL);
11699
11700   // Check whether the sign bit is set.
11701   SDValue SignSet = DAG.getSetCC(dl,
11702                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11703                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11704                                  ISD::SETLT);
11705
11706   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11707   SDValue FudgePtr = DAG.getConstantPool(
11708                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11709                                          getPointerTy());
11710
11711   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11712   SDValue Zero = DAG.getIntPtrConstant(0);
11713   SDValue Four = DAG.getIntPtrConstant(4);
11714   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11715                                Zero, Four);
11716   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11717
11718   // Load the value out, extending it from f32 to f80.
11719   // FIXME: Avoid the extend by constructing the right constant pool?
11720   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11721                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11722                                  MVT::f32, false, false, false, 4);
11723   // Extend everything to 80 bits to force it to be done on x87.
11724   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11725   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11726 }
11727
11728 std::pair<SDValue,SDValue>
11729 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11730                                     bool IsSigned, bool IsReplace) const {
11731   SDLoc DL(Op);
11732
11733   EVT DstTy = Op.getValueType();
11734
11735   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11736     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11737     DstTy = MVT::i64;
11738   }
11739
11740   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11741          DstTy.getSimpleVT() >= MVT::i16 &&
11742          "Unknown FP_TO_INT to lower!");
11743
11744   // These are really Legal.
11745   if (DstTy == MVT::i32 &&
11746       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11747     return std::make_pair(SDValue(), SDValue());
11748   if (Subtarget->is64Bit() &&
11749       DstTy == MVT::i64 &&
11750       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11751     return std::make_pair(SDValue(), SDValue());
11752
11753   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11754   // stack slot, or into the FTOL runtime function.
11755   MachineFunction &MF = DAG.getMachineFunction();
11756   unsigned MemSize = DstTy.getSizeInBits()/8;
11757   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11758   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11759
11760   unsigned Opc;
11761   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11762     Opc = X86ISD::WIN_FTOL;
11763   else
11764     switch (DstTy.getSimpleVT().SimpleTy) {
11765     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11766     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11767     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11768     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11769     }
11770
11771   SDValue Chain = DAG.getEntryNode();
11772   SDValue Value = Op.getOperand(0);
11773   EVT TheVT = Op.getOperand(0).getValueType();
11774   // FIXME This causes a redundant load/store if the SSE-class value is already
11775   // in memory, such as if it is on the callstack.
11776   if (isScalarFPTypeInSSEReg(TheVT)) {
11777     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11778     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11779                          MachinePointerInfo::getFixedStack(SSFI),
11780                          false, false, 0);
11781     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11782     SDValue Ops[] = {
11783       Chain, StackSlot, DAG.getValueType(TheVT)
11784     };
11785
11786     MachineMemOperand *MMO =
11787       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11788                               MachineMemOperand::MOLoad, MemSize, MemSize);
11789     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11790     Chain = Value.getValue(1);
11791     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11792     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11793   }
11794
11795   MachineMemOperand *MMO =
11796     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11797                             MachineMemOperand::MOStore, MemSize, MemSize);
11798
11799   if (Opc != X86ISD::WIN_FTOL) {
11800     // Build the FP_TO_INT*_IN_MEM
11801     SDValue Ops[] = { Chain, Value, StackSlot };
11802     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11803                                            Ops, DstTy, MMO);
11804     return std::make_pair(FIST, StackSlot);
11805   } else {
11806     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11807       DAG.getVTList(MVT::Other, MVT::Glue),
11808       Chain, Value);
11809     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11810       MVT::i32, ftol.getValue(1));
11811     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11812       MVT::i32, eax.getValue(2));
11813     SDValue Ops[] = { eax, edx };
11814     SDValue pair = IsReplace
11815       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11816       : DAG.getMergeValues(Ops, DL);
11817     return std::make_pair(pair, SDValue());
11818   }
11819 }
11820
11821 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11822                               const X86Subtarget *Subtarget) {
11823   MVT VT = Op->getSimpleValueType(0);
11824   SDValue In = Op->getOperand(0);
11825   MVT InVT = In.getSimpleValueType();
11826   SDLoc dl(Op);
11827
11828   // Optimize vectors in AVX mode:
11829   //
11830   //   v8i16 -> v8i32
11831   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11832   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11833   //   Concat upper and lower parts.
11834   //
11835   //   v4i32 -> v4i64
11836   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11837   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11838   //   Concat upper and lower parts.
11839   //
11840
11841   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11842       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11843       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11844     return SDValue();
11845
11846   if (Subtarget->hasInt256())
11847     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11848
11849   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11850   SDValue Undef = DAG.getUNDEF(InVT);
11851   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11852   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11853   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11854
11855   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11856                              VT.getVectorNumElements()/2);
11857
11858   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11859   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11860
11861   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11862 }
11863
11864 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11865                                         SelectionDAG &DAG) {
11866   MVT VT = Op->getSimpleValueType(0);
11867   SDValue In = Op->getOperand(0);
11868   MVT InVT = In.getSimpleValueType();
11869   SDLoc DL(Op);
11870   unsigned int NumElts = VT.getVectorNumElements();
11871   if (NumElts != 8 && NumElts != 16)
11872     return SDValue();
11873
11874   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11875     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11876
11877   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11879   // Now we have only mask extension
11880   assert(InVT.getVectorElementType() == MVT::i1);
11881   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11882   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11883   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11884   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11885   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11886                            MachinePointerInfo::getConstantPool(),
11887                            false, false, false, Alignment);
11888
11889   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11890   if (VT.is512BitVector())
11891     return Brcst;
11892   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11893 }
11894
11895 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11896                                SelectionDAG &DAG) {
11897   if (Subtarget->hasFp256()) {
11898     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11899     if (Res.getNode())
11900       return Res;
11901   }
11902
11903   return SDValue();
11904 }
11905
11906 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11907                                 SelectionDAG &DAG) {
11908   SDLoc DL(Op);
11909   MVT VT = Op.getSimpleValueType();
11910   SDValue In = Op.getOperand(0);
11911   MVT SVT = In.getSimpleValueType();
11912
11913   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11914     return LowerZERO_EXTEND_AVX512(Op, DAG);
11915
11916   if (Subtarget->hasFp256()) {
11917     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11918     if (Res.getNode())
11919       return Res;
11920   }
11921
11922   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11923          VT.getVectorNumElements() != SVT.getVectorNumElements());
11924   return SDValue();
11925 }
11926
11927 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11928   SDLoc DL(Op);
11929   MVT VT = Op.getSimpleValueType();
11930   SDValue In = Op.getOperand(0);
11931   MVT InVT = In.getSimpleValueType();
11932
11933   if (VT == MVT::i1) {
11934     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11935            "Invalid scalar TRUNCATE operation");
11936     if (InVT.getSizeInBits() >= 32)
11937       return SDValue();
11938     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11939     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11940   }
11941   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11942          "Invalid TRUNCATE operation");
11943
11944   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11945     if (VT.getVectorElementType().getSizeInBits() >=8)
11946       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11947
11948     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11949     unsigned NumElts = InVT.getVectorNumElements();
11950     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11951     if (InVT.getSizeInBits() < 512) {
11952       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11953       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11954       InVT = ExtVT;
11955     }
11956     
11957     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11958     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11959     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11960     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11961     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11962                            MachinePointerInfo::getConstantPool(),
11963                            false, false, false, Alignment);
11964     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11965     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11966     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11967   }
11968
11969   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11970     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11971     if (Subtarget->hasInt256()) {
11972       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11973       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11974       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11975                                 ShufMask);
11976       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11977                          DAG.getIntPtrConstant(0));
11978     }
11979
11980     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11981                                DAG.getIntPtrConstant(0));
11982     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11983                                DAG.getIntPtrConstant(2));
11984     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11985     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11986     static const int ShufMask[] = {0, 2, 4, 6};
11987     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11988   }
11989
11990   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11991     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11992     if (Subtarget->hasInt256()) {
11993       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11994
11995       SmallVector<SDValue,32> pshufbMask;
11996       for (unsigned i = 0; i < 2; ++i) {
11997         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11998         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11999         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12000         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12001         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12002         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12003         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12004         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12005         for (unsigned j = 0; j < 8; ++j)
12006           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12007       }
12008       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12009       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12010       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12011
12012       static const int ShufMask[] = {0,  2,  -1,  -1};
12013       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12014                                 &ShufMask[0]);
12015       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12016                        DAG.getIntPtrConstant(0));
12017       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12018     }
12019
12020     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12021                                DAG.getIntPtrConstant(0));
12022
12023     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12024                                DAG.getIntPtrConstant(4));
12025
12026     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12027     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12028
12029     // The PSHUFB mask:
12030     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12031                                    -1, -1, -1, -1, -1, -1, -1, -1};
12032
12033     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12034     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12035     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12036
12037     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12038     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12039
12040     // The MOVLHPS Mask:
12041     static const int ShufMask2[] = {0, 1, 4, 5};
12042     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12043     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12044   }
12045
12046   // Handle truncation of V256 to V128 using shuffles.
12047   if (!VT.is128BitVector() || !InVT.is256BitVector())
12048     return SDValue();
12049
12050   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12051
12052   unsigned NumElems = VT.getVectorNumElements();
12053   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12054
12055   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12056   // Prepare truncation shuffle mask
12057   for (unsigned i = 0; i != NumElems; ++i)
12058     MaskVec[i] = i * 2;
12059   SDValue V = DAG.getVectorShuffle(NVT, DL,
12060                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12061                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12062   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12063                      DAG.getIntPtrConstant(0));
12064 }
12065
12066 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12067                                            SelectionDAG &DAG) const {
12068   assert(!Op.getSimpleValueType().isVector());
12069
12070   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12071     /*IsSigned=*/ true, /*IsReplace=*/ false);
12072   SDValue FIST = Vals.first, StackSlot = Vals.second;
12073   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12074   if (!FIST.getNode()) return Op;
12075
12076   if (StackSlot.getNode())
12077     // Load the result.
12078     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12079                        FIST, StackSlot, MachinePointerInfo(),
12080                        false, false, false, 0);
12081
12082   // The node is the result.
12083   return FIST;
12084 }
12085
12086 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12087                                            SelectionDAG &DAG) const {
12088   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12089     /*IsSigned=*/ false, /*IsReplace=*/ false);
12090   SDValue FIST = Vals.first, StackSlot = Vals.second;
12091   assert(FIST.getNode() && "Unexpected failure");
12092
12093   if (StackSlot.getNode())
12094     // Load the result.
12095     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12096                        FIST, StackSlot, MachinePointerInfo(),
12097                        false, false, false, 0);
12098
12099   // The node is the result.
12100   return FIST;
12101 }
12102
12103 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12104   SDLoc DL(Op);
12105   MVT VT = Op.getSimpleValueType();
12106   SDValue In = Op.getOperand(0);
12107   MVT SVT = In.getSimpleValueType();
12108
12109   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12110
12111   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12112                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12113                                  In, DAG.getUNDEF(SVT)));
12114 }
12115
12116 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
12117   LLVMContext *Context = DAG.getContext();
12118   SDLoc dl(Op);
12119   MVT VT = Op.getSimpleValueType();
12120   MVT EltVT = VT;
12121   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12122   if (VT.isVector()) {
12123     EltVT = VT.getVectorElementType();
12124     NumElts = VT.getVectorNumElements();
12125   }
12126   Constant *C;
12127   if (EltVT == MVT::f64)
12128     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12129                                           APInt(64, ~(1ULL << 63))));
12130   else
12131     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12132                                           APInt(32, ~(1U << 31))));
12133   C = ConstantVector::getSplat(NumElts, C);
12134   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12135   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12136   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12137   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12138                              MachinePointerInfo::getConstantPool(),
12139                              false, false, false, Alignment);
12140   if (VT.isVector()) {
12141     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12142     return DAG.getNode(ISD::BITCAST, dl, VT,
12143                        DAG.getNode(ISD::AND, dl, ANDVT,
12144                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
12145                                                Op.getOperand(0)),
12146                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
12147   }
12148   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
12149 }
12150
12151 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
12152   LLVMContext *Context = DAG.getContext();
12153   SDLoc dl(Op);
12154   MVT VT = Op.getSimpleValueType();
12155   MVT EltVT = VT;
12156   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12157   if (VT.isVector()) {
12158     EltVT = VT.getVectorElementType();
12159     NumElts = VT.getVectorNumElements();
12160   }
12161   Constant *C;
12162   if (EltVT == MVT::f64)
12163     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12164                                           APInt(64, 1ULL << 63)));
12165   else
12166     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12167                                           APInt(32, 1U << 31)));
12168   C = ConstantVector::getSplat(NumElts, C);
12169   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12170   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12171   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12172   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12173                              MachinePointerInfo::getConstantPool(),
12174                              false, false, false, Alignment);
12175   if (VT.isVector()) {
12176     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
12177     return DAG.getNode(ISD::BITCAST, dl, VT,
12178                        DAG.getNode(ISD::XOR, dl, XORVT,
12179                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
12180                                                Op.getOperand(0)),
12181                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
12182   }
12183
12184   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
12185 }
12186
12187 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12188   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12189   LLVMContext *Context = DAG.getContext();
12190   SDValue Op0 = Op.getOperand(0);
12191   SDValue Op1 = Op.getOperand(1);
12192   SDLoc dl(Op);
12193   MVT VT = Op.getSimpleValueType();
12194   MVT SrcVT = Op1.getSimpleValueType();
12195
12196   // If second operand is smaller, extend it first.
12197   if (SrcVT.bitsLT(VT)) {
12198     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12199     SrcVT = VT;
12200   }
12201   // And if it is bigger, shrink it first.
12202   if (SrcVT.bitsGT(VT)) {
12203     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12204     SrcVT = VT;
12205   }
12206
12207   // At this point the operands and the result should have the same
12208   // type, and that won't be f80 since that is not custom lowered.
12209
12210   // First get the sign bit of second operand.
12211   SmallVector<Constant*,4> CV;
12212   if (SrcVT == MVT::f64) {
12213     const fltSemantics &Sem = APFloat::IEEEdouble;
12214     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12215     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12216   } else {
12217     const fltSemantics &Sem = APFloat::IEEEsingle;
12218     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12219     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12220     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12221     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12222   }
12223   Constant *C = ConstantVector::get(CV);
12224   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12225   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12226                               MachinePointerInfo::getConstantPool(),
12227                               false, false, false, 16);
12228   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12229
12230   // Shift sign bit right or left if the two operands have different types.
12231   if (SrcVT.bitsGT(VT)) {
12232     // Op0 is MVT::f32, Op1 is MVT::f64.
12233     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12234     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12235                           DAG.getConstant(32, MVT::i32));
12236     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12237     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12238                           DAG.getIntPtrConstant(0));
12239   }
12240
12241   // Clear first operand sign bit.
12242   CV.clear();
12243   if (VT == MVT::f64) {
12244     const fltSemantics &Sem = APFloat::IEEEdouble;
12245     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12246                                                    APInt(64, ~(1ULL << 63)))));
12247     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12248   } else {
12249     const fltSemantics &Sem = APFloat::IEEEsingle;
12250     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12251                                                    APInt(32, ~(1U << 31)))));
12252     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12253     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12254     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12255   }
12256   C = ConstantVector::get(CV);
12257   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12258   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12259                               MachinePointerInfo::getConstantPool(),
12260                               false, false, false, 16);
12261   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12262
12263   // Or the value with the sign bit.
12264   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12265 }
12266
12267 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12268   SDValue N0 = Op.getOperand(0);
12269   SDLoc dl(Op);
12270   MVT VT = Op.getSimpleValueType();
12271
12272   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12273   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12274                                   DAG.getConstant(1, VT));
12275   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12276 }
12277
12278 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12279 //
12280 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12281                                       SelectionDAG &DAG) {
12282   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12283
12284   if (!Subtarget->hasSSE41())
12285     return SDValue();
12286
12287   if (!Op->hasOneUse())
12288     return SDValue();
12289
12290   SDNode *N = Op.getNode();
12291   SDLoc DL(N);
12292
12293   SmallVector<SDValue, 8> Opnds;
12294   DenseMap<SDValue, unsigned> VecInMap;
12295   SmallVector<SDValue, 8> VecIns;
12296   EVT VT = MVT::Other;
12297
12298   // Recognize a special case where a vector is casted into wide integer to
12299   // test all 0s.
12300   Opnds.push_back(N->getOperand(0));
12301   Opnds.push_back(N->getOperand(1));
12302
12303   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12304     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12305     // BFS traverse all OR'd operands.
12306     if (I->getOpcode() == ISD::OR) {
12307       Opnds.push_back(I->getOperand(0));
12308       Opnds.push_back(I->getOperand(1));
12309       // Re-evaluate the number of nodes to be traversed.
12310       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12311       continue;
12312     }
12313
12314     // Quit if a non-EXTRACT_VECTOR_ELT
12315     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12316       return SDValue();
12317
12318     // Quit if without a constant index.
12319     SDValue Idx = I->getOperand(1);
12320     if (!isa<ConstantSDNode>(Idx))
12321       return SDValue();
12322
12323     SDValue ExtractedFromVec = I->getOperand(0);
12324     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12325     if (M == VecInMap.end()) {
12326       VT = ExtractedFromVec.getValueType();
12327       // Quit if not 128/256-bit vector.
12328       if (!VT.is128BitVector() && !VT.is256BitVector())
12329         return SDValue();
12330       // Quit if not the same type.
12331       if (VecInMap.begin() != VecInMap.end() &&
12332           VT != VecInMap.begin()->first.getValueType())
12333         return SDValue();
12334       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12335       VecIns.push_back(ExtractedFromVec);
12336     }
12337     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12338   }
12339
12340   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12341          "Not extracted from 128-/256-bit vector.");
12342
12343   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12344
12345   for (DenseMap<SDValue, unsigned>::const_iterator
12346         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12347     // Quit if not all elements are used.
12348     if (I->second != FullMask)
12349       return SDValue();
12350   }
12351
12352   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12353
12354   // Cast all vectors into TestVT for PTEST.
12355   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12356     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12357
12358   // If more than one full vectors are evaluated, OR them first before PTEST.
12359   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12360     // Each iteration will OR 2 nodes and append the result until there is only
12361     // 1 node left, i.e. the final OR'd value of all vectors.
12362     SDValue LHS = VecIns[Slot];
12363     SDValue RHS = VecIns[Slot + 1];
12364     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12365   }
12366
12367   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12368                      VecIns.back(), VecIns.back());
12369 }
12370
12371 /// \brief return true if \c Op has a use that doesn't just read flags.
12372 static bool hasNonFlagsUse(SDValue Op) {
12373   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12374        ++UI) {
12375     SDNode *User = *UI;
12376     unsigned UOpNo = UI.getOperandNo();
12377     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12378       // Look pass truncate.
12379       UOpNo = User->use_begin().getOperandNo();
12380       User = *User->use_begin();
12381     }
12382
12383     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12384         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12385       return true;
12386   }
12387   return false;
12388 }
12389
12390 /// Emit nodes that will be selected as "test Op0,Op0", or something
12391 /// equivalent.
12392 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12393                                     SelectionDAG &DAG) const {
12394   if (Op.getValueType() == MVT::i1)
12395     // KORTEST instruction should be selected
12396     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12397                        DAG.getConstant(0, Op.getValueType()));
12398
12399   // CF and OF aren't always set the way we want. Determine which
12400   // of these we need.
12401   bool NeedCF = false;
12402   bool NeedOF = false;
12403   switch (X86CC) {
12404   default: break;
12405   case X86::COND_A: case X86::COND_AE:
12406   case X86::COND_B: case X86::COND_BE:
12407     NeedCF = true;
12408     break;
12409   case X86::COND_G: case X86::COND_GE:
12410   case X86::COND_L: case X86::COND_LE:
12411   case X86::COND_O: case X86::COND_NO: {
12412     // Check if we really need to set the
12413     // Overflow flag. If NoSignedWrap is present
12414     // that is not actually needed.
12415     switch (Op->getOpcode()) {
12416     case ISD::ADD:
12417     case ISD::SUB:
12418     case ISD::MUL:
12419     case ISD::SHL: {
12420       const BinaryWithFlagsSDNode *BinNode =
12421           cast<BinaryWithFlagsSDNode>(Op.getNode());
12422       if (BinNode->hasNoSignedWrap())
12423         break;
12424     }
12425     default:
12426       NeedOF = true;
12427       break;
12428     }
12429     break;
12430   }
12431   }
12432   // See if we can use the EFLAGS value from the operand instead of
12433   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12434   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12435   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12436     // Emit a CMP with 0, which is the TEST pattern.
12437     //if (Op.getValueType() == MVT::i1)
12438     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12439     //                     DAG.getConstant(0, MVT::i1));
12440     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12441                        DAG.getConstant(0, Op.getValueType()));
12442   }
12443   unsigned Opcode = 0;
12444   unsigned NumOperands = 0;
12445
12446   // Truncate operations may prevent the merge of the SETCC instruction
12447   // and the arithmetic instruction before it. Attempt to truncate the operands
12448   // of the arithmetic instruction and use a reduced bit-width instruction.
12449   bool NeedTruncation = false;
12450   SDValue ArithOp = Op;
12451   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12452     SDValue Arith = Op->getOperand(0);
12453     // Both the trunc and the arithmetic op need to have one user each.
12454     if (Arith->hasOneUse())
12455       switch (Arith.getOpcode()) {
12456         default: break;
12457         case ISD::ADD:
12458         case ISD::SUB:
12459         case ISD::AND:
12460         case ISD::OR:
12461         case ISD::XOR: {
12462           NeedTruncation = true;
12463           ArithOp = Arith;
12464         }
12465       }
12466   }
12467
12468   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12469   // which may be the result of a CAST.  We use the variable 'Op', which is the
12470   // non-casted variable when we check for possible users.
12471   switch (ArithOp.getOpcode()) {
12472   case ISD::ADD:
12473     // Due to an isel shortcoming, be conservative if this add is likely to be
12474     // selected as part of a load-modify-store instruction. When the root node
12475     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12476     // uses of other nodes in the match, such as the ADD in this case. This
12477     // leads to the ADD being left around and reselected, with the result being
12478     // two adds in the output.  Alas, even if none our users are stores, that
12479     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12480     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12481     // climbing the DAG back to the root, and it doesn't seem to be worth the
12482     // effort.
12483     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12484          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12485       if (UI->getOpcode() != ISD::CopyToReg &&
12486           UI->getOpcode() != ISD::SETCC &&
12487           UI->getOpcode() != ISD::STORE)
12488         goto default_case;
12489
12490     if (ConstantSDNode *C =
12491         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12492       // An add of one will be selected as an INC.
12493       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12494         Opcode = X86ISD::INC;
12495         NumOperands = 1;
12496         break;
12497       }
12498
12499       // An add of negative one (subtract of one) will be selected as a DEC.
12500       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12501         Opcode = X86ISD::DEC;
12502         NumOperands = 1;
12503         break;
12504       }
12505     }
12506
12507     // Otherwise use a regular EFLAGS-setting add.
12508     Opcode = X86ISD::ADD;
12509     NumOperands = 2;
12510     break;
12511   case ISD::SHL:
12512   case ISD::SRL:
12513     // If we have a constant logical shift that's only used in a comparison
12514     // against zero turn it into an equivalent AND. This allows turning it into
12515     // a TEST instruction later.
12516     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12517         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12518       EVT VT = Op.getValueType();
12519       unsigned BitWidth = VT.getSizeInBits();
12520       unsigned ShAmt = Op->getConstantOperandVal(1);
12521       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12522         break;
12523       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12524                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12525                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12526       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12527         break;
12528       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12529                                 DAG.getConstant(Mask, VT));
12530       DAG.ReplaceAllUsesWith(Op, New);
12531       Op = New;
12532     }
12533     break;
12534
12535   case ISD::AND:
12536     // If the primary and result isn't used, don't bother using X86ISD::AND,
12537     // because a TEST instruction will be better.
12538     if (!hasNonFlagsUse(Op))
12539       break;
12540     // FALL THROUGH
12541   case ISD::SUB:
12542   case ISD::OR:
12543   case ISD::XOR:
12544     // Due to the ISEL shortcoming noted above, be conservative if this op is
12545     // likely to be selected as part of a load-modify-store instruction.
12546     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12547            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12548       if (UI->getOpcode() == ISD::STORE)
12549         goto default_case;
12550
12551     // Otherwise use a regular EFLAGS-setting instruction.
12552     switch (ArithOp.getOpcode()) {
12553     default: llvm_unreachable("unexpected operator!");
12554     case ISD::SUB: Opcode = X86ISD::SUB; break;
12555     case ISD::XOR: Opcode = X86ISD::XOR; break;
12556     case ISD::AND: Opcode = X86ISD::AND; break;
12557     case ISD::OR: {
12558       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12559         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12560         if (EFLAGS.getNode())
12561           return EFLAGS;
12562       }
12563       Opcode = X86ISD::OR;
12564       break;
12565     }
12566     }
12567
12568     NumOperands = 2;
12569     break;
12570   case X86ISD::ADD:
12571   case X86ISD::SUB:
12572   case X86ISD::INC:
12573   case X86ISD::DEC:
12574   case X86ISD::OR:
12575   case X86ISD::XOR:
12576   case X86ISD::AND:
12577     return SDValue(Op.getNode(), 1);
12578   default:
12579   default_case:
12580     break;
12581   }
12582
12583   // If we found that truncation is beneficial, perform the truncation and
12584   // update 'Op'.
12585   if (NeedTruncation) {
12586     EVT VT = Op.getValueType();
12587     SDValue WideVal = Op->getOperand(0);
12588     EVT WideVT = WideVal.getValueType();
12589     unsigned ConvertedOp = 0;
12590     // Use a target machine opcode to prevent further DAGCombine
12591     // optimizations that may separate the arithmetic operations
12592     // from the setcc node.
12593     switch (WideVal.getOpcode()) {
12594       default: break;
12595       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12596       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12597       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12598       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12599       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12600     }
12601
12602     if (ConvertedOp) {
12603       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12604       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12605         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12606         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12607         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12608       }
12609     }
12610   }
12611
12612   if (Opcode == 0)
12613     // Emit a CMP with 0, which is the TEST pattern.
12614     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12615                        DAG.getConstant(0, Op.getValueType()));
12616
12617   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12618   SmallVector<SDValue, 4> Ops;
12619   for (unsigned i = 0; i != NumOperands; ++i)
12620     Ops.push_back(Op.getOperand(i));
12621
12622   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12623   DAG.ReplaceAllUsesWith(Op, New);
12624   return SDValue(New.getNode(), 1);
12625 }
12626
12627 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12628 /// equivalent.
12629 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12630                                    SDLoc dl, SelectionDAG &DAG) const {
12631   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12632     if (C->getAPIntValue() == 0)
12633       return EmitTest(Op0, X86CC, dl, DAG);
12634
12635      if (Op0.getValueType() == MVT::i1)
12636        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12637   }
12638  
12639   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12640        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12641     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12642     // This avoids subregister aliasing issues. Keep the smaller reference 
12643     // if we're optimizing for size, however, as that'll allow better folding 
12644     // of memory operations.
12645     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12646         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12647              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12648         !Subtarget->isAtom()) {
12649       unsigned ExtendOp =
12650           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12651       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12652       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12653     }
12654     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12655     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12656     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12657                               Op0, Op1);
12658     return SDValue(Sub.getNode(), 1);
12659   }
12660   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12661 }
12662
12663 /// Convert a comparison if required by the subtarget.
12664 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12665                                                  SelectionDAG &DAG) const {
12666   // If the subtarget does not support the FUCOMI instruction, floating-point
12667   // comparisons have to be converted.
12668   if (Subtarget->hasCMov() ||
12669       Cmp.getOpcode() != X86ISD::CMP ||
12670       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12671       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12672     return Cmp;
12673
12674   // The instruction selector will select an FUCOM instruction instead of
12675   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12676   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12677   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12678   SDLoc dl(Cmp);
12679   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12680   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12681   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12682                             DAG.getConstant(8, MVT::i8));
12683   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12684   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12685 }
12686
12687 static bool isAllOnes(SDValue V) {
12688   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12689   return C && C->isAllOnesValue();
12690 }
12691
12692 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12693 /// if it's possible.
12694 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12695                                      SDLoc dl, SelectionDAG &DAG) const {
12696   SDValue Op0 = And.getOperand(0);
12697   SDValue Op1 = And.getOperand(1);
12698   if (Op0.getOpcode() == ISD::TRUNCATE)
12699     Op0 = Op0.getOperand(0);
12700   if (Op1.getOpcode() == ISD::TRUNCATE)
12701     Op1 = Op1.getOperand(0);
12702
12703   SDValue LHS, RHS;
12704   if (Op1.getOpcode() == ISD::SHL)
12705     std::swap(Op0, Op1);
12706   if (Op0.getOpcode() == ISD::SHL) {
12707     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12708       if (And00C->getZExtValue() == 1) {
12709         // If we looked past a truncate, check that it's only truncating away
12710         // known zeros.
12711         unsigned BitWidth = Op0.getValueSizeInBits();
12712         unsigned AndBitWidth = And.getValueSizeInBits();
12713         if (BitWidth > AndBitWidth) {
12714           APInt Zeros, Ones;
12715           DAG.computeKnownBits(Op0, Zeros, Ones);
12716           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12717             return SDValue();
12718         }
12719         LHS = Op1;
12720         RHS = Op0.getOperand(1);
12721       }
12722   } else if (Op1.getOpcode() == ISD::Constant) {
12723     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12724     uint64_t AndRHSVal = AndRHS->getZExtValue();
12725     SDValue AndLHS = Op0;
12726
12727     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12728       LHS = AndLHS.getOperand(0);
12729       RHS = AndLHS.getOperand(1);
12730     }
12731
12732     // Use BT if the immediate can't be encoded in a TEST instruction.
12733     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12734       LHS = AndLHS;
12735       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12736     }
12737   }
12738
12739   if (LHS.getNode()) {
12740     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12741     // instruction.  Since the shift amount is in-range-or-undefined, we know
12742     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12743     // the encoding for the i16 version is larger than the i32 version.
12744     // Also promote i16 to i32 for performance / code size reason.
12745     if (LHS.getValueType() == MVT::i8 ||
12746         LHS.getValueType() == MVT::i16)
12747       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12748
12749     // If the operand types disagree, extend the shift amount to match.  Since
12750     // BT ignores high bits (like shifts) we can use anyextend.
12751     if (LHS.getValueType() != RHS.getValueType())
12752       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12753
12754     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12755     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12756     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12757                        DAG.getConstant(Cond, MVT::i8), BT);
12758   }
12759
12760   return SDValue();
12761 }
12762
12763 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12764 /// mask CMPs.
12765 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12766                               SDValue &Op1) {
12767   unsigned SSECC;
12768   bool Swap = false;
12769
12770   // SSE Condition code mapping:
12771   //  0 - EQ
12772   //  1 - LT
12773   //  2 - LE
12774   //  3 - UNORD
12775   //  4 - NEQ
12776   //  5 - NLT
12777   //  6 - NLE
12778   //  7 - ORD
12779   switch (SetCCOpcode) {
12780   default: llvm_unreachable("Unexpected SETCC condition");
12781   case ISD::SETOEQ:
12782   case ISD::SETEQ:  SSECC = 0; break;
12783   case ISD::SETOGT:
12784   case ISD::SETGT:  Swap = true; // Fallthrough
12785   case ISD::SETLT:
12786   case ISD::SETOLT: SSECC = 1; break;
12787   case ISD::SETOGE:
12788   case ISD::SETGE:  Swap = true; // Fallthrough
12789   case ISD::SETLE:
12790   case ISD::SETOLE: SSECC = 2; break;
12791   case ISD::SETUO:  SSECC = 3; break;
12792   case ISD::SETUNE:
12793   case ISD::SETNE:  SSECC = 4; break;
12794   case ISD::SETULE: Swap = true; // Fallthrough
12795   case ISD::SETUGE: SSECC = 5; break;
12796   case ISD::SETULT: Swap = true; // Fallthrough
12797   case ISD::SETUGT: SSECC = 6; break;
12798   case ISD::SETO:   SSECC = 7; break;
12799   case ISD::SETUEQ:
12800   case ISD::SETONE: SSECC = 8; break;
12801   }
12802   if (Swap)
12803     std::swap(Op0, Op1);
12804
12805   return SSECC;
12806 }
12807
12808 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12809 // ones, and then concatenate the result back.
12810 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12811   MVT VT = Op.getSimpleValueType();
12812
12813   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12814          "Unsupported value type for operation");
12815
12816   unsigned NumElems = VT.getVectorNumElements();
12817   SDLoc dl(Op);
12818   SDValue CC = Op.getOperand(2);
12819
12820   // Extract the LHS vectors
12821   SDValue LHS = Op.getOperand(0);
12822   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12823   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12824
12825   // Extract the RHS vectors
12826   SDValue RHS = Op.getOperand(1);
12827   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12828   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12829
12830   // Issue the operation on the smaller types and concatenate the result back
12831   MVT EltVT = VT.getVectorElementType();
12832   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12833   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12834                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12835                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12836 }
12837
12838 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12839                                      const X86Subtarget *Subtarget) {
12840   SDValue Op0 = Op.getOperand(0);
12841   SDValue Op1 = Op.getOperand(1);
12842   SDValue CC = Op.getOperand(2);
12843   MVT VT = Op.getSimpleValueType();
12844   SDLoc dl(Op);
12845
12846   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12847          Op.getValueType().getScalarType() == MVT::i1 &&
12848          "Cannot set masked compare for this operation");
12849
12850   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12851   unsigned  Opc = 0;
12852   bool Unsigned = false;
12853   bool Swap = false;
12854   unsigned SSECC;
12855   switch (SetCCOpcode) {
12856   default: llvm_unreachable("Unexpected SETCC condition");
12857   case ISD::SETNE:  SSECC = 4; break;
12858   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12859   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12860   case ISD::SETLT:  Swap = true; //fall-through
12861   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12862   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12863   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12864   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12865   case ISD::SETULE: Unsigned = true; //fall-through
12866   case ISD::SETLE:  SSECC = 2; break;
12867   }
12868
12869   if (Swap)
12870     std::swap(Op0, Op1);
12871   if (Opc)
12872     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12873   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12874   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12875                      DAG.getConstant(SSECC, MVT::i8));
12876 }
12877
12878 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12879 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12880 /// return an empty value.
12881 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12882 {
12883   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12884   if (!BV)
12885     return SDValue();
12886
12887   MVT VT = Op1.getSimpleValueType();
12888   MVT EVT = VT.getVectorElementType();
12889   unsigned n = VT.getVectorNumElements();
12890   SmallVector<SDValue, 8> ULTOp1;
12891
12892   for (unsigned i = 0; i < n; ++i) {
12893     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12894     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12895       return SDValue();
12896
12897     // Avoid underflow.
12898     APInt Val = Elt->getAPIntValue();
12899     if (Val == 0)
12900       return SDValue();
12901
12902     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12903   }
12904
12905   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12906 }
12907
12908 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12909                            SelectionDAG &DAG) {
12910   SDValue Op0 = Op.getOperand(0);
12911   SDValue Op1 = Op.getOperand(1);
12912   SDValue CC = Op.getOperand(2);
12913   MVT VT = Op.getSimpleValueType();
12914   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12915   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12916   SDLoc dl(Op);
12917
12918   if (isFP) {
12919 #ifndef NDEBUG
12920     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12921     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12922 #endif
12923
12924     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12925     unsigned Opc = X86ISD::CMPP;
12926     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12927       assert(VT.getVectorNumElements() <= 16);
12928       Opc = X86ISD::CMPM;
12929     }
12930     // In the two special cases we can't handle, emit two comparisons.
12931     if (SSECC == 8) {
12932       unsigned CC0, CC1;
12933       unsigned CombineOpc;
12934       if (SetCCOpcode == ISD::SETUEQ) {
12935         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12936       } else {
12937         assert(SetCCOpcode == ISD::SETONE);
12938         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12939       }
12940
12941       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12942                                  DAG.getConstant(CC0, MVT::i8));
12943       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12944                                  DAG.getConstant(CC1, MVT::i8));
12945       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12946     }
12947     // Handle all other FP comparisons here.
12948     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12949                        DAG.getConstant(SSECC, MVT::i8));
12950   }
12951
12952   // Break 256-bit integer vector compare into smaller ones.
12953   if (VT.is256BitVector() && !Subtarget->hasInt256())
12954     return Lower256IntVSETCC(Op, DAG);
12955
12956   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12957   EVT OpVT = Op1.getValueType();
12958   if (Subtarget->hasAVX512()) {
12959     if (Op1.getValueType().is512BitVector() ||
12960         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12961       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12962
12963     // In AVX-512 architecture setcc returns mask with i1 elements,
12964     // But there is no compare instruction for i8 and i16 elements.
12965     // We are not talking about 512-bit operands in this case, these
12966     // types are illegal.
12967     if (MaskResult &&
12968         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12969          OpVT.getVectorElementType().getSizeInBits() >= 8))
12970       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12971                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12972   }
12973
12974   // We are handling one of the integer comparisons here.  Since SSE only has
12975   // GT and EQ comparisons for integer, swapping operands and multiple
12976   // operations may be required for some comparisons.
12977   unsigned Opc;
12978   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12979   bool Subus = false;
12980
12981   switch (SetCCOpcode) {
12982   default: llvm_unreachable("Unexpected SETCC condition");
12983   case ISD::SETNE:  Invert = true;
12984   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12985   case ISD::SETLT:  Swap = true;
12986   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12987   case ISD::SETGE:  Swap = true;
12988   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12989                     Invert = true; break;
12990   case ISD::SETULT: Swap = true;
12991   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12992                     FlipSigns = true; break;
12993   case ISD::SETUGE: Swap = true;
12994   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12995                     FlipSigns = true; Invert = true; break;
12996   }
12997
12998   // Special case: Use min/max operations for SETULE/SETUGE
12999   MVT VET = VT.getVectorElementType();
13000   bool hasMinMax =
13001        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13002     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13003
13004   if (hasMinMax) {
13005     switch (SetCCOpcode) {
13006     default: break;
13007     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13008     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13009     }
13010
13011     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13012   }
13013
13014   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13015   if (!MinMax && hasSubus) {
13016     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13017     // Op0 u<= Op1:
13018     //   t = psubus Op0, Op1
13019     //   pcmpeq t, <0..0>
13020     switch (SetCCOpcode) {
13021     default: break;
13022     case ISD::SETULT: {
13023       // If the comparison is against a constant we can turn this into a
13024       // setule.  With psubus, setule does not require a swap.  This is
13025       // beneficial because the constant in the register is no longer
13026       // destructed as the destination so it can be hoisted out of a loop.
13027       // Only do this pre-AVX since vpcmp* is no longer destructive.
13028       if (Subtarget->hasAVX())
13029         break;
13030       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13031       if (ULEOp1.getNode()) {
13032         Op1 = ULEOp1;
13033         Subus = true; Invert = false; Swap = false;
13034       }
13035       break;
13036     }
13037     // Psubus is better than flip-sign because it requires no inversion.
13038     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13039     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13040     }
13041
13042     if (Subus) {
13043       Opc = X86ISD::SUBUS;
13044       FlipSigns = false;
13045     }
13046   }
13047
13048   if (Swap)
13049     std::swap(Op0, Op1);
13050
13051   // Check that the operation in question is available (most are plain SSE2,
13052   // but PCMPGTQ and PCMPEQQ have different requirements).
13053   if (VT == MVT::v2i64) {
13054     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13055       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13056
13057       // First cast everything to the right type.
13058       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13059       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13060
13061       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13062       // bits of the inputs before performing those operations. The lower
13063       // compare is always unsigned.
13064       SDValue SB;
13065       if (FlipSigns) {
13066         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13067       } else {
13068         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13069         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13070         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13071                          Sign, Zero, Sign, Zero);
13072       }
13073       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13074       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13075
13076       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13077       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13078       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13079
13080       // Create masks for only the low parts/high parts of the 64 bit integers.
13081       static const int MaskHi[] = { 1, 1, 3, 3 };
13082       static const int MaskLo[] = { 0, 0, 2, 2 };
13083       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13084       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13085       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13086
13087       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13088       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13089
13090       if (Invert)
13091         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13092
13093       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13094     }
13095
13096     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13097       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13098       // pcmpeqd + pshufd + pand.
13099       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13100
13101       // First cast everything to the right type.
13102       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13103       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13104
13105       // Do the compare.
13106       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13107
13108       // Make sure the lower and upper halves are both all-ones.
13109       static const int Mask[] = { 1, 0, 3, 2 };
13110       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13111       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13112
13113       if (Invert)
13114         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13115
13116       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13117     }
13118   }
13119
13120   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13121   // bits of the inputs before performing those operations.
13122   if (FlipSigns) {
13123     EVT EltVT = VT.getVectorElementType();
13124     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13125     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13126     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13127   }
13128
13129   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13130
13131   // If the logical-not of the result is required, perform that now.
13132   if (Invert)
13133     Result = DAG.getNOT(dl, Result, VT);
13134
13135   if (MinMax)
13136     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13137
13138   if (Subus)
13139     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13140                          getZeroVector(VT, Subtarget, DAG, dl));
13141
13142   return Result;
13143 }
13144
13145 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13146
13147   MVT VT = Op.getSimpleValueType();
13148
13149   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13150
13151   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13152          && "SetCC type must be 8-bit or 1-bit integer");
13153   SDValue Op0 = Op.getOperand(0);
13154   SDValue Op1 = Op.getOperand(1);
13155   SDLoc dl(Op);
13156   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13157
13158   // Optimize to BT if possible.
13159   // Lower (X & (1 << N)) == 0 to BT(X, N).
13160   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13161   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13162   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13163       Op1.getOpcode() == ISD::Constant &&
13164       cast<ConstantSDNode>(Op1)->isNullValue() &&
13165       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13166     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13167     if (NewSetCC.getNode())
13168       return NewSetCC;
13169   }
13170
13171   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13172   // these.
13173   if (Op1.getOpcode() == ISD::Constant &&
13174       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13175        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13176       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13177
13178     // If the input is a setcc, then reuse the input setcc or use a new one with
13179     // the inverted condition.
13180     if (Op0.getOpcode() == X86ISD::SETCC) {
13181       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13182       bool Invert = (CC == ISD::SETNE) ^
13183         cast<ConstantSDNode>(Op1)->isNullValue();
13184       if (!Invert)
13185         return Op0;
13186
13187       CCode = X86::GetOppositeBranchCondition(CCode);
13188       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13189                                   DAG.getConstant(CCode, MVT::i8),
13190                                   Op0.getOperand(1));
13191       if (VT == MVT::i1)
13192         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13193       return SetCC;
13194     }
13195   }
13196   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13197       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13198       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13199
13200     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13201     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13202   }
13203
13204   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13205   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13206   if (X86CC == X86::COND_INVALID)
13207     return SDValue();
13208
13209   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13210   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13211   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13212                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13213   if (VT == MVT::i1)
13214     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13215   return SetCC;
13216 }
13217
13218 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13219 static bool isX86LogicalCmp(SDValue Op) {
13220   unsigned Opc = Op.getNode()->getOpcode();
13221   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13222       Opc == X86ISD::SAHF)
13223     return true;
13224   if (Op.getResNo() == 1 &&
13225       (Opc == X86ISD::ADD ||
13226        Opc == X86ISD::SUB ||
13227        Opc == X86ISD::ADC ||
13228        Opc == X86ISD::SBB ||
13229        Opc == X86ISD::SMUL ||
13230        Opc == X86ISD::UMUL ||
13231        Opc == X86ISD::INC ||
13232        Opc == X86ISD::DEC ||
13233        Opc == X86ISD::OR ||
13234        Opc == X86ISD::XOR ||
13235        Opc == X86ISD::AND))
13236     return true;
13237
13238   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13239     return true;
13240
13241   return false;
13242 }
13243
13244 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13245   if (V.getOpcode() != ISD::TRUNCATE)
13246     return false;
13247
13248   SDValue VOp0 = V.getOperand(0);
13249   unsigned InBits = VOp0.getValueSizeInBits();
13250   unsigned Bits = V.getValueSizeInBits();
13251   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13252 }
13253
13254 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13255   bool addTest = true;
13256   SDValue Cond  = Op.getOperand(0);
13257   SDValue Op1 = Op.getOperand(1);
13258   SDValue Op2 = Op.getOperand(2);
13259   SDLoc DL(Op);
13260   EVT VT = Op1.getValueType();
13261   SDValue CC;
13262
13263   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13264   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13265   // sequence later on.
13266   if (Cond.getOpcode() == ISD::SETCC &&
13267       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13268        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13269       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13270     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13271     int SSECC = translateX86FSETCC(
13272         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13273
13274     if (SSECC != 8) {
13275       if (Subtarget->hasAVX512()) {
13276         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13277                                   DAG.getConstant(SSECC, MVT::i8));
13278         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13279       }
13280       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13281                                 DAG.getConstant(SSECC, MVT::i8));
13282       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13283       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13284       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13285     }
13286   }
13287
13288   if (Cond.getOpcode() == ISD::SETCC) {
13289     SDValue NewCond = LowerSETCC(Cond, DAG);
13290     if (NewCond.getNode())
13291       Cond = NewCond;
13292   }
13293
13294   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13295   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13296   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13297   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13298   if (Cond.getOpcode() == X86ISD::SETCC &&
13299       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13300       isZero(Cond.getOperand(1).getOperand(1))) {
13301     SDValue Cmp = Cond.getOperand(1);
13302
13303     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13304
13305     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13306         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13307       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13308
13309       SDValue CmpOp0 = Cmp.getOperand(0);
13310       // Apply further optimizations for special cases
13311       // (select (x != 0), -1, 0) -> neg & sbb
13312       // (select (x == 0), 0, -1) -> neg & sbb
13313       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13314         if (YC->isNullValue() &&
13315             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13316           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13317           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13318                                     DAG.getConstant(0, CmpOp0.getValueType()),
13319                                     CmpOp0);
13320           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13321                                     DAG.getConstant(X86::COND_B, MVT::i8),
13322                                     SDValue(Neg.getNode(), 1));
13323           return Res;
13324         }
13325
13326       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13327                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13328       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13329
13330       SDValue Res =   // Res = 0 or -1.
13331         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13332                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13333
13334       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13335         Res = DAG.getNOT(DL, Res, Res.getValueType());
13336
13337       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13338       if (!N2C || !N2C->isNullValue())
13339         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13340       return Res;
13341     }
13342   }
13343
13344   // Look past (and (setcc_carry (cmp ...)), 1).
13345   if (Cond.getOpcode() == ISD::AND &&
13346       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13347     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13348     if (C && C->getAPIntValue() == 1)
13349       Cond = Cond.getOperand(0);
13350   }
13351
13352   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13353   // setting operand in place of the X86ISD::SETCC.
13354   unsigned CondOpcode = Cond.getOpcode();
13355   if (CondOpcode == X86ISD::SETCC ||
13356       CondOpcode == X86ISD::SETCC_CARRY) {
13357     CC = Cond.getOperand(0);
13358
13359     SDValue Cmp = Cond.getOperand(1);
13360     unsigned Opc = Cmp.getOpcode();
13361     MVT VT = Op.getSimpleValueType();
13362
13363     bool IllegalFPCMov = false;
13364     if (VT.isFloatingPoint() && !VT.isVector() &&
13365         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13366       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13367
13368     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13369         Opc == X86ISD::BT) { // FIXME
13370       Cond = Cmp;
13371       addTest = false;
13372     }
13373   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13374              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13375              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13376               Cond.getOperand(0).getValueType() != MVT::i8)) {
13377     SDValue LHS = Cond.getOperand(0);
13378     SDValue RHS = Cond.getOperand(1);
13379     unsigned X86Opcode;
13380     unsigned X86Cond;
13381     SDVTList VTs;
13382     switch (CondOpcode) {
13383     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13384     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13385     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13386     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13387     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13388     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13389     default: llvm_unreachable("unexpected overflowing operator");
13390     }
13391     if (CondOpcode == ISD::UMULO)
13392       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13393                           MVT::i32);
13394     else
13395       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13396
13397     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13398
13399     if (CondOpcode == ISD::UMULO)
13400       Cond = X86Op.getValue(2);
13401     else
13402       Cond = X86Op.getValue(1);
13403
13404     CC = DAG.getConstant(X86Cond, MVT::i8);
13405     addTest = false;
13406   }
13407
13408   if (addTest) {
13409     // Look pass the truncate if the high bits are known zero.
13410     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13411         Cond = Cond.getOperand(0);
13412
13413     // We know the result of AND is compared against zero. Try to match
13414     // it to BT.
13415     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13416       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13417       if (NewSetCC.getNode()) {
13418         CC = NewSetCC.getOperand(0);
13419         Cond = NewSetCC.getOperand(1);
13420         addTest = false;
13421       }
13422     }
13423   }
13424
13425   if (addTest) {
13426     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13427     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13428   }
13429
13430   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13431   // a <  b ?  0 : -1 -> RES = setcc_carry
13432   // a >= b ? -1 :  0 -> RES = setcc_carry
13433   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13434   if (Cond.getOpcode() == X86ISD::SUB) {
13435     Cond = ConvertCmpIfNecessary(Cond, DAG);
13436     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13437
13438     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13439         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13440       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13441                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13442       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13443         return DAG.getNOT(DL, Res, Res.getValueType());
13444       return Res;
13445     }
13446   }
13447
13448   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13449   // widen the cmov and push the truncate through. This avoids introducing a new
13450   // branch during isel and doesn't add any extensions.
13451   if (Op.getValueType() == MVT::i8 &&
13452       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13453     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13454     if (T1.getValueType() == T2.getValueType() &&
13455         // Blacklist CopyFromReg to avoid partial register stalls.
13456         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13457       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13458       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13459       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13460     }
13461   }
13462
13463   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13464   // condition is true.
13465   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13466   SDValue Ops[] = { Op2, Op1, CC, Cond };
13467   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13468 }
13469
13470 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13471   MVT VT = Op->getSimpleValueType(0);
13472   SDValue In = Op->getOperand(0);
13473   MVT InVT = In.getSimpleValueType();
13474   SDLoc dl(Op);
13475
13476   unsigned int NumElts = VT.getVectorNumElements();
13477   if (NumElts != 8 && NumElts != 16)
13478     return SDValue();
13479
13480   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13481     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13482
13483   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13484   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13485
13486   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13487   Constant *C = ConstantInt::get(*DAG.getContext(),
13488     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13489
13490   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13491   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13492   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13493                           MachinePointerInfo::getConstantPool(),
13494                           false, false, false, Alignment);
13495   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13496   if (VT.is512BitVector())
13497     return Brcst;
13498   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13499 }
13500
13501 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13502                                 SelectionDAG &DAG) {
13503   MVT VT = Op->getSimpleValueType(0);
13504   SDValue In = Op->getOperand(0);
13505   MVT InVT = In.getSimpleValueType();
13506   SDLoc dl(Op);
13507
13508   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13509     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13510
13511   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13512       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13513       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13514     return SDValue();
13515
13516   if (Subtarget->hasInt256())
13517     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13518
13519   // Optimize vectors in AVX mode
13520   // Sign extend  v8i16 to v8i32 and
13521   //              v4i32 to v4i64
13522   //
13523   // Divide input vector into two parts
13524   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13525   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13526   // concat the vectors to original VT
13527
13528   unsigned NumElems = InVT.getVectorNumElements();
13529   SDValue Undef = DAG.getUNDEF(InVT);
13530
13531   SmallVector<int,8> ShufMask1(NumElems, -1);
13532   for (unsigned i = 0; i != NumElems/2; ++i)
13533     ShufMask1[i] = i;
13534
13535   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13536
13537   SmallVector<int,8> ShufMask2(NumElems, -1);
13538   for (unsigned i = 0; i != NumElems/2; ++i)
13539     ShufMask2[i] = i + NumElems/2;
13540
13541   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13542
13543   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13544                                 VT.getVectorNumElements()/2);
13545
13546   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13547   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13548
13549   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13550 }
13551
13552 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13553 // may emit an illegal shuffle but the expansion is still better than scalar
13554 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13555 // we'll emit a shuffle and a arithmetic shift.
13556 // TODO: It is possible to support ZExt by zeroing the undef values during
13557 // the shuffle phase or after the shuffle.
13558 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13559                                  SelectionDAG &DAG) {
13560   MVT RegVT = Op.getSimpleValueType();
13561   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13562   assert(RegVT.isInteger() &&
13563          "We only custom lower integer vector sext loads.");
13564
13565   // Nothing useful we can do without SSE2 shuffles.
13566   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13567
13568   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13569   SDLoc dl(Ld);
13570   EVT MemVT = Ld->getMemoryVT();
13571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13572   unsigned RegSz = RegVT.getSizeInBits();
13573
13574   ISD::LoadExtType Ext = Ld->getExtensionType();
13575
13576   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13577          && "Only anyext and sext are currently implemented.");
13578   assert(MemVT != RegVT && "Cannot extend to the same type");
13579   assert(MemVT.isVector() && "Must load a vector from memory");
13580
13581   unsigned NumElems = RegVT.getVectorNumElements();
13582   unsigned MemSz = MemVT.getSizeInBits();
13583   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13584
13585   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13586     // The only way in which we have a legal 256-bit vector result but not the
13587     // integer 256-bit operations needed to directly lower a sextload is if we
13588     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13589     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13590     // correctly legalized. We do this late to allow the canonical form of
13591     // sextload to persist throughout the rest of the DAG combiner -- it wants
13592     // to fold together any extensions it can, and so will fuse a sign_extend
13593     // of an sextload into a sextload targeting a wider value.
13594     SDValue Load;
13595     if (MemSz == 128) {
13596       // Just switch this to a normal load.
13597       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13598                                        "it must be a legal 128-bit vector "
13599                                        "type!");
13600       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13601                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13602                   Ld->isInvariant(), Ld->getAlignment());
13603     } else {
13604       assert(MemSz < 128 &&
13605              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13606       // Do an sext load to a 128-bit vector type. We want to use the same
13607       // number of elements, but elements half as wide. This will end up being
13608       // recursively lowered by this routine, but will succeed as we definitely
13609       // have all the necessary features if we're using AVX1.
13610       EVT HalfEltVT =
13611           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13612       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13613       Load =
13614           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13615                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13616                          Ld->isNonTemporal(), Ld->isInvariant(),
13617                          Ld->getAlignment());
13618     }
13619
13620     // Replace chain users with the new chain.
13621     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13622     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13623
13624     // Finally, do a normal sign-extend to the desired register.
13625     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13626   }
13627
13628   // All sizes must be a power of two.
13629   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13630          "Non-power-of-two elements are not custom lowered!");
13631
13632   // Attempt to load the original value using scalar loads.
13633   // Find the largest scalar type that divides the total loaded size.
13634   MVT SclrLoadTy = MVT::i8;
13635   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13636        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13637     MVT Tp = (MVT::SimpleValueType)tp;
13638     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13639       SclrLoadTy = Tp;
13640     }
13641   }
13642
13643   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13644   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13645       (64 <= MemSz))
13646     SclrLoadTy = MVT::f64;
13647
13648   // Calculate the number of scalar loads that we need to perform
13649   // in order to load our vector from memory.
13650   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13651
13652   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13653          "Can only lower sext loads with a single scalar load!");
13654
13655   unsigned loadRegZize = RegSz;
13656   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13657     loadRegZize /= 2;
13658
13659   // Represent our vector as a sequence of elements which are the
13660   // largest scalar that we can load.
13661   EVT LoadUnitVecVT = EVT::getVectorVT(
13662       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13663
13664   // Represent the data using the same element type that is stored in
13665   // memory. In practice, we ''widen'' MemVT.
13666   EVT WideVecVT =
13667       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13668                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13669
13670   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13671          "Invalid vector type");
13672
13673   // We can't shuffle using an illegal type.
13674   assert(TLI.isTypeLegal(WideVecVT) &&
13675          "We only lower types that form legal widened vector types");
13676
13677   SmallVector<SDValue, 8> Chains;
13678   SDValue Ptr = Ld->getBasePtr();
13679   SDValue Increment =
13680       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13681   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13682
13683   for (unsigned i = 0; i < NumLoads; ++i) {
13684     // Perform a single load.
13685     SDValue ScalarLoad =
13686         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13687                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13688                     Ld->getAlignment());
13689     Chains.push_back(ScalarLoad.getValue(1));
13690     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13691     // another round of DAGCombining.
13692     if (i == 0)
13693       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13694     else
13695       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13696                         ScalarLoad, DAG.getIntPtrConstant(i));
13697
13698     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13699   }
13700
13701   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13702
13703   // Bitcast the loaded value to a vector of the original element type, in
13704   // the size of the target vector type.
13705   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13706   unsigned SizeRatio = RegSz / MemSz;
13707
13708   if (Ext == ISD::SEXTLOAD) {
13709     // If we have SSE4.1, we can directly emit a VSEXT node.
13710     if (Subtarget->hasSSE41()) {
13711       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13712       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13713       return Sext;
13714     }
13715
13716     // Otherwise we'll shuffle the small elements in the high bits of the
13717     // larger type and perform an arithmetic shift. If the shift is not legal
13718     // it's better to scalarize.
13719     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13720            "We can't implement a sext load without an arithmetic right shift!");
13721
13722     // Redistribute the loaded elements into the different locations.
13723     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13724     for (unsigned i = 0; i != NumElems; ++i)
13725       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13726
13727     SDValue Shuff = DAG.getVectorShuffle(
13728         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13729
13730     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13731
13732     // Build the arithmetic shift.
13733     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13734                    MemVT.getVectorElementType().getSizeInBits();
13735     Shuff =
13736         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13737
13738     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13739     return Shuff;
13740   }
13741
13742   // Redistribute the loaded elements into the different locations.
13743   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13744   for (unsigned i = 0; i != NumElems; ++i)
13745     ShuffleVec[i * SizeRatio] = i;
13746
13747   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13748                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13749
13750   // Bitcast to the requested type.
13751   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13752   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13753   return Shuff;
13754 }
13755
13756 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13757 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13758 // from the AND / OR.
13759 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13760   Opc = Op.getOpcode();
13761   if (Opc != ISD::OR && Opc != ISD::AND)
13762     return false;
13763   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13764           Op.getOperand(0).hasOneUse() &&
13765           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13766           Op.getOperand(1).hasOneUse());
13767 }
13768
13769 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13770 // 1 and that the SETCC node has a single use.
13771 static bool isXor1OfSetCC(SDValue Op) {
13772   if (Op.getOpcode() != ISD::XOR)
13773     return false;
13774   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13775   if (N1C && N1C->getAPIntValue() == 1) {
13776     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13777       Op.getOperand(0).hasOneUse();
13778   }
13779   return false;
13780 }
13781
13782 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13783   bool addTest = true;
13784   SDValue Chain = Op.getOperand(0);
13785   SDValue Cond  = Op.getOperand(1);
13786   SDValue Dest  = Op.getOperand(2);
13787   SDLoc dl(Op);
13788   SDValue CC;
13789   bool Inverted = false;
13790
13791   if (Cond.getOpcode() == ISD::SETCC) {
13792     // Check for setcc([su]{add,sub,mul}o == 0).
13793     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13794         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13795         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13796         Cond.getOperand(0).getResNo() == 1 &&
13797         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13798          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13799          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13800          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13801          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13802          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13803       Inverted = true;
13804       Cond = Cond.getOperand(0);
13805     } else {
13806       SDValue NewCond = LowerSETCC(Cond, DAG);
13807       if (NewCond.getNode())
13808         Cond = NewCond;
13809     }
13810   }
13811 #if 0
13812   // FIXME: LowerXALUO doesn't handle these!!
13813   else if (Cond.getOpcode() == X86ISD::ADD  ||
13814            Cond.getOpcode() == X86ISD::SUB  ||
13815            Cond.getOpcode() == X86ISD::SMUL ||
13816            Cond.getOpcode() == X86ISD::UMUL)
13817     Cond = LowerXALUO(Cond, DAG);
13818 #endif
13819
13820   // Look pass (and (setcc_carry (cmp ...)), 1).
13821   if (Cond.getOpcode() == ISD::AND &&
13822       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13823     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13824     if (C && C->getAPIntValue() == 1)
13825       Cond = Cond.getOperand(0);
13826   }
13827
13828   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13829   // setting operand in place of the X86ISD::SETCC.
13830   unsigned CondOpcode = Cond.getOpcode();
13831   if (CondOpcode == X86ISD::SETCC ||
13832       CondOpcode == X86ISD::SETCC_CARRY) {
13833     CC = Cond.getOperand(0);
13834
13835     SDValue Cmp = Cond.getOperand(1);
13836     unsigned Opc = Cmp.getOpcode();
13837     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13838     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13839       Cond = Cmp;
13840       addTest = false;
13841     } else {
13842       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13843       default: break;
13844       case X86::COND_O:
13845       case X86::COND_B:
13846         // These can only come from an arithmetic instruction with overflow,
13847         // e.g. SADDO, UADDO.
13848         Cond = Cond.getNode()->getOperand(1);
13849         addTest = false;
13850         break;
13851       }
13852     }
13853   }
13854   CondOpcode = Cond.getOpcode();
13855   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13856       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13857       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13858        Cond.getOperand(0).getValueType() != MVT::i8)) {
13859     SDValue LHS = Cond.getOperand(0);
13860     SDValue RHS = Cond.getOperand(1);
13861     unsigned X86Opcode;
13862     unsigned X86Cond;
13863     SDVTList VTs;
13864     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13865     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13866     // X86ISD::INC).
13867     switch (CondOpcode) {
13868     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13869     case ISD::SADDO:
13870       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13871         if (C->isOne()) {
13872           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13873           break;
13874         }
13875       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13876     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13877     case ISD::SSUBO:
13878       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13879         if (C->isOne()) {
13880           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13881           break;
13882         }
13883       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13884     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13885     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13886     default: llvm_unreachable("unexpected overflowing operator");
13887     }
13888     if (Inverted)
13889       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13890     if (CondOpcode == ISD::UMULO)
13891       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13892                           MVT::i32);
13893     else
13894       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13895
13896     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13897
13898     if (CondOpcode == ISD::UMULO)
13899       Cond = X86Op.getValue(2);
13900     else
13901       Cond = X86Op.getValue(1);
13902
13903     CC = DAG.getConstant(X86Cond, MVT::i8);
13904     addTest = false;
13905   } else {
13906     unsigned CondOpc;
13907     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13908       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13909       if (CondOpc == ISD::OR) {
13910         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13911         // two branches instead of an explicit OR instruction with a
13912         // separate test.
13913         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13914             isX86LogicalCmp(Cmp)) {
13915           CC = Cond.getOperand(0).getOperand(0);
13916           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13917                               Chain, Dest, CC, Cmp);
13918           CC = Cond.getOperand(1).getOperand(0);
13919           Cond = Cmp;
13920           addTest = false;
13921         }
13922       } else { // ISD::AND
13923         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13924         // two branches instead of an explicit AND instruction with a
13925         // separate test. However, we only do this if this block doesn't
13926         // have a fall-through edge, because this requires an explicit
13927         // jmp when the condition is false.
13928         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13929             isX86LogicalCmp(Cmp) &&
13930             Op.getNode()->hasOneUse()) {
13931           X86::CondCode CCode =
13932             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13933           CCode = X86::GetOppositeBranchCondition(CCode);
13934           CC = DAG.getConstant(CCode, MVT::i8);
13935           SDNode *User = *Op.getNode()->use_begin();
13936           // Look for an unconditional branch following this conditional branch.
13937           // We need this because we need to reverse the successors in order
13938           // to implement FCMP_OEQ.
13939           if (User->getOpcode() == ISD::BR) {
13940             SDValue FalseBB = User->getOperand(1);
13941             SDNode *NewBR =
13942               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13943             assert(NewBR == User);
13944             (void)NewBR;
13945             Dest = FalseBB;
13946
13947             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13948                                 Chain, Dest, CC, Cmp);
13949             X86::CondCode CCode =
13950               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13951             CCode = X86::GetOppositeBranchCondition(CCode);
13952             CC = DAG.getConstant(CCode, MVT::i8);
13953             Cond = Cmp;
13954             addTest = false;
13955           }
13956         }
13957       }
13958     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13959       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13960       // It should be transformed during dag combiner except when the condition
13961       // is set by a arithmetics with overflow node.
13962       X86::CondCode CCode =
13963         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13964       CCode = X86::GetOppositeBranchCondition(CCode);
13965       CC = DAG.getConstant(CCode, MVT::i8);
13966       Cond = Cond.getOperand(0).getOperand(1);
13967       addTest = false;
13968     } else if (Cond.getOpcode() == ISD::SETCC &&
13969                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13970       // For FCMP_OEQ, we can emit
13971       // two branches instead of an explicit AND instruction with a
13972       // separate test. However, we only do this if this block doesn't
13973       // have a fall-through edge, because this requires an explicit
13974       // jmp when the condition is false.
13975       if (Op.getNode()->hasOneUse()) {
13976         SDNode *User = *Op.getNode()->use_begin();
13977         // Look for an unconditional branch following this conditional branch.
13978         // We need this because we need to reverse the successors in order
13979         // to implement FCMP_OEQ.
13980         if (User->getOpcode() == ISD::BR) {
13981           SDValue FalseBB = User->getOperand(1);
13982           SDNode *NewBR =
13983             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13984           assert(NewBR == User);
13985           (void)NewBR;
13986           Dest = FalseBB;
13987
13988           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13989                                     Cond.getOperand(0), Cond.getOperand(1));
13990           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13991           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13992           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13993                               Chain, Dest, CC, Cmp);
13994           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13995           Cond = Cmp;
13996           addTest = false;
13997         }
13998       }
13999     } else if (Cond.getOpcode() == ISD::SETCC &&
14000                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14001       // For FCMP_UNE, we can emit
14002       // two branches instead of an explicit AND instruction with a
14003       // separate test. However, we only do this if this block doesn't
14004       // have a fall-through edge, because this requires an explicit
14005       // jmp when the condition is false.
14006       if (Op.getNode()->hasOneUse()) {
14007         SDNode *User = *Op.getNode()->use_begin();
14008         // Look for an unconditional branch following this conditional branch.
14009         // We need this because we need to reverse the successors in order
14010         // to implement FCMP_UNE.
14011         if (User->getOpcode() == ISD::BR) {
14012           SDValue FalseBB = User->getOperand(1);
14013           SDNode *NewBR =
14014             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14015           assert(NewBR == User);
14016           (void)NewBR;
14017
14018           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14019                                     Cond.getOperand(0), Cond.getOperand(1));
14020           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14021           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14022           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14023                               Chain, Dest, CC, Cmp);
14024           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14025           Cond = Cmp;
14026           addTest = false;
14027           Dest = FalseBB;
14028         }
14029       }
14030     }
14031   }
14032
14033   if (addTest) {
14034     // Look pass the truncate if the high bits are known zero.
14035     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14036         Cond = Cond.getOperand(0);
14037
14038     // We know the result of AND is compared against zero. Try to match
14039     // it to BT.
14040     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14041       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14042       if (NewSetCC.getNode()) {
14043         CC = NewSetCC.getOperand(0);
14044         Cond = NewSetCC.getOperand(1);
14045         addTest = false;
14046       }
14047     }
14048   }
14049
14050   if (addTest) {
14051     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14052     CC = DAG.getConstant(X86Cond, MVT::i8);
14053     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14054   }
14055   Cond = ConvertCmpIfNecessary(Cond, DAG);
14056   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14057                      Chain, Dest, CC, Cond);
14058 }
14059
14060 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14061 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14062 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14063 // that the guard pages used by the OS virtual memory manager are allocated in
14064 // correct sequence.
14065 SDValue
14066 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14067                                            SelectionDAG &DAG) const {
14068   MachineFunction &MF = DAG.getMachineFunction();
14069   bool SplitStack = MF.shouldSplitStack();
14070   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14071                SplitStack;
14072   SDLoc dl(Op);
14073
14074   if (!Lower) {
14075     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14076     SDNode* Node = Op.getNode();
14077
14078     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14079     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14080         " not tell us which reg is the stack pointer!");
14081     EVT VT = Node->getValueType(0);
14082     SDValue Tmp1 = SDValue(Node, 0);
14083     SDValue Tmp2 = SDValue(Node, 1);
14084     SDValue Tmp3 = Node->getOperand(2);
14085     SDValue Chain = Tmp1.getOperand(0);
14086
14087     // Chain the dynamic stack allocation so that it doesn't modify the stack
14088     // pointer when other instructions are using the stack.
14089     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14090         SDLoc(Node));
14091
14092     SDValue Size = Tmp2.getOperand(1);
14093     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14094     Chain = SP.getValue(1);
14095     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14096     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14097     unsigned StackAlign = TFI.getStackAlignment();
14098     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14099     if (Align > StackAlign)
14100       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14101           DAG.getConstant(-(uint64_t)Align, VT));
14102     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14103
14104     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14105         DAG.getIntPtrConstant(0, true), SDValue(),
14106         SDLoc(Node));
14107
14108     SDValue Ops[2] = { Tmp1, Tmp2 };
14109     return DAG.getMergeValues(Ops, dl);
14110   }
14111
14112   // Get the inputs.
14113   SDValue Chain = Op.getOperand(0);
14114   SDValue Size  = Op.getOperand(1);
14115   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14116   EVT VT = Op.getNode()->getValueType(0);
14117
14118   bool Is64Bit = Subtarget->is64Bit();
14119   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14120
14121   if (SplitStack) {
14122     MachineRegisterInfo &MRI = MF.getRegInfo();
14123
14124     if (Is64Bit) {
14125       // The 64 bit implementation of segmented stacks needs to clobber both r10
14126       // r11. This makes it impossible to use it along with nested parameters.
14127       const Function *F = MF.getFunction();
14128
14129       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14130            I != E; ++I)
14131         if (I->hasNestAttr())
14132           report_fatal_error("Cannot use segmented stacks with functions that "
14133                              "have nested arguments.");
14134     }
14135
14136     const TargetRegisterClass *AddrRegClass =
14137       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14138     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14139     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14140     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14141                                 DAG.getRegister(Vreg, SPTy));
14142     SDValue Ops1[2] = { Value, Chain };
14143     return DAG.getMergeValues(Ops1, dl);
14144   } else {
14145     SDValue Flag;
14146     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14147
14148     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14149     Flag = Chain.getValue(1);
14150     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14151
14152     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14153
14154     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14155         DAG.getSubtarget().getRegisterInfo());
14156     unsigned SPReg = RegInfo->getStackRegister();
14157     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14158     Chain = SP.getValue(1);
14159
14160     if (Align) {
14161       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14162                        DAG.getConstant(-(uint64_t)Align, VT));
14163       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14164     }
14165
14166     SDValue Ops1[2] = { SP, Chain };
14167     return DAG.getMergeValues(Ops1, dl);
14168   }
14169 }
14170
14171 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14172   MachineFunction &MF = DAG.getMachineFunction();
14173   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14174
14175   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14176   SDLoc DL(Op);
14177
14178   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14179     // vastart just stores the address of the VarArgsFrameIndex slot into the
14180     // memory location argument.
14181     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14182                                    getPointerTy());
14183     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14184                         MachinePointerInfo(SV), false, false, 0);
14185   }
14186
14187   // __va_list_tag:
14188   //   gp_offset         (0 - 6 * 8)
14189   //   fp_offset         (48 - 48 + 8 * 16)
14190   //   overflow_arg_area (point to parameters coming in memory).
14191   //   reg_save_area
14192   SmallVector<SDValue, 8> MemOps;
14193   SDValue FIN = Op.getOperand(1);
14194   // Store gp_offset
14195   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14196                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14197                                                MVT::i32),
14198                                FIN, MachinePointerInfo(SV), false, false, 0);
14199   MemOps.push_back(Store);
14200
14201   // Store fp_offset
14202   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14203                     FIN, DAG.getIntPtrConstant(4));
14204   Store = DAG.getStore(Op.getOperand(0), DL,
14205                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14206                                        MVT::i32),
14207                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14208   MemOps.push_back(Store);
14209
14210   // Store ptr to overflow_arg_area
14211   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14212                     FIN, DAG.getIntPtrConstant(4));
14213   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14214                                     getPointerTy());
14215   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14216                        MachinePointerInfo(SV, 8),
14217                        false, false, 0);
14218   MemOps.push_back(Store);
14219
14220   // Store ptr to reg_save_area.
14221   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14222                     FIN, DAG.getIntPtrConstant(8));
14223   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14224                                     getPointerTy());
14225   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14226                        MachinePointerInfo(SV, 16), false, false, 0);
14227   MemOps.push_back(Store);
14228   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14229 }
14230
14231 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14232   assert(Subtarget->is64Bit() &&
14233          "LowerVAARG only handles 64-bit va_arg!");
14234   assert((Subtarget->isTargetLinux() ||
14235           Subtarget->isTargetDarwin()) &&
14236           "Unhandled target in LowerVAARG");
14237   assert(Op.getNode()->getNumOperands() == 4);
14238   SDValue Chain = Op.getOperand(0);
14239   SDValue SrcPtr = Op.getOperand(1);
14240   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14241   unsigned Align = Op.getConstantOperandVal(3);
14242   SDLoc dl(Op);
14243
14244   EVT ArgVT = Op.getNode()->getValueType(0);
14245   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14246   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14247   uint8_t ArgMode;
14248
14249   // Decide which area this value should be read from.
14250   // TODO: Implement the AMD64 ABI in its entirety. This simple
14251   // selection mechanism works only for the basic types.
14252   if (ArgVT == MVT::f80) {
14253     llvm_unreachable("va_arg for f80 not yet implemented");
14254   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14255     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14256   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14257     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14258   } else {
14259     llvm_unreachable("Unhandled argument type in LowerVAARG");
14260   }
14261
14262   if (ArgMode == 2) {
14263     // Sanity Check: Make sure using fp_offset makes sense.
14264     assert(!DAG.getTarget().Options.UseSoftFloat &&
14265            !(DAG.getMachineFunction()
14266                 .getFunction()->getAttributes()
14267                 .hasAttribute(AttributeSet::FunctionIndex,
14268                               Attribute::NoImplicitFloat)) &&
14269            Subtarget->hasSSE1());
14270   }
14271
14272   // Insert VAARG_64 node into the DAG
14273   // VAARG_64 returns two values: Variable Argument Address, Chain
14274   SmallVector<SDValue, 11> InstOps;
14275   InstOps.push_back(Chain);
14276   InstOps.push_back(SrcPtr);
14277   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14278   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14279   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14280   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14281   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14282                                           VTs, InstOps, MVT::i64,
14283                                           MachinePointerInfo(SV),
14284                                           /*Align=*/0,
14285                                           /*Volatile=*/false,
14286                                           /*ReadMem=*/true,
14287                                           /*WriteMem=*/true);
14288   Chain = VAARG.getValue(1);
14289
14290   // Load the next argument and return it
14291   return DAG.getLoad(ArgVT, dl,
14292                      Chain,
14293                      VAARG,
14294                      MachinePointerInfo(),
14295                      false, false, false, 0);
14296 }
14297
14298 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14299                            SelectionDAG &DAG) {
14300   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14301   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14302   SDValue Chain = Op.getOperand(0);
14303   SDValue DstPtr = Op.getOperand(1);
14304   SDValue SrcPtr = Op.getOperand(2);
14305   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14306   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14307   SDLoc DL(Op);
14308
14309   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14310                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14311                        false,
14312                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14313 }
14314
14315 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14316 // amount is a constant. Takes immediate version of shift as input.
14317 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14318                                           SDValue SrcOp, uint64_t ShiftAmt,
14319                                           SelectionDAG &DAG) {
14320   MVT ElementType = VT.getVectorElementType();
14321
14322   // Fold this packed shift into its first operand if ShiftAmt is 0.
14323   if (ShiftAmt == 0)
14324     return SrcOp;
14325
14326   // Check for ShiftAmt >= element width
14327   if (ShiftAmt >= ElementType.getSizeInBits()) {
14328     if (Opc == X86ISD::VSRAI)
14329       ShiftAmt = ElementType.getSizeInBits() - 1;
14330     else
14331       return DAG.getConstant(0, VT);
14332   }
14333
14334   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14335          && "Unknown target vector shift-by-constant node");
14336
14337   // Fold this packed vector shift into a build vector if SrcOp is a
14338   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14339   if (VT == SrcOp.getSimpleValueType() &&
14340       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14341     SmallVector<SDValue, 8> Elts;
14342     unsigned NumElts = SrcOp->getNumOperands();
14343     ConstantSDNode *ND;
14344
14345     switch(Opc) {
14346     default: llvm_unreachable(nullptr);
14347     case X86ISD::VSHLI:
14348       for (unsigned i=0; i!=NumElts; ++i) {
14349         SDValue CurrentOp = SrcOp->getOperand(i);
14350         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14351           Elts.push_back(CurrentOp);
14352           continue;
14353         }
14354         ND = cast<ConstantSDNode>(CurrentOp);
14355         const APInt &C = ND->getAPIntValue();
14356         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14357       }
14358       break;
14359     case X86ISD::VSRLI:
14360       for (unsigned i=0; i!=NumElts; ++i) {
14361         SDValue CurrentOp = SrcOp->getOperand(i);
14362         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14363           Elts.push_back(CurrentOp);
14364           continue;
14365         }
14366         ND = cast<ConstantSDNode>(CurrentOp);
14367         const APInt &C = ND->getAPIntValue();
14368         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14369       }
14370       break;
14371     case X86ISD::VSRAI:
14372       for (unsigned i=0; i!=NumElts; ++i) {
14373         SDValue CurrentOp = SrcOp->getOperand(i);
14374         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14375           Elts.push_back(CurrentOp);
14376           continue;
14377         }
14378         ND = cast<ConstantSDNode>(CurrentOp);
14379         const APInt &C = ND->getAPIntValue();
14380         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14381       }
14382       break;
14383     }
14384
14385     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14386   }
14387
14388   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14389 }
14390
14391 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14392 // may or may not be a constant. Takes immediate version of shift as input.
14393 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14394                                    SDValue SrcOp, SDValue ShAmt,
14395                                    SelectionDAG &DAG) {
14396   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14397
14398   // Catch shift-by-constant.
14399   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14400     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14401                                       CShAmt->getZExtValue(), DAG);
14402
14403   // Change opcode to non-immediate version
14404   switch (Opc) {
14405     default: llvm_unreachable("Unknown target vector shift node");
14406     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14407     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14408     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14409   }
14410
14411   // Need to build a vector containing shift amount
14412   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14413   SDValue ShOps[4];
14414   ShOps[0] = ShAmt;
14415   ShOps[1] = DAG.getConstant(0, MVT::i32);
14416   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14417   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14418
14419   // The return type has to be a 128-bit type with the same element
14420   // type as the input type.
14421   MVT EltVT = VT.getVectorElementType();
14422   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14423
14424   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14425   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14426 }
14427
14428 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14429 /// necessary casting for \p Mask when lowering masking intrinsics.
14430 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14431                                     SDValue PreservedSrc, SelectionDAG &DAG) {
14432     EVT VT = Op.getValueType();
14433     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14434                                   MVT::i1, VT.getVectorNumElements());
14435     SDLoc dl(Op);
14436
14437     assert(MaskVT.isSimple() && "invalid mask type");
14438     return DAG.getNode(ISD::VSELECT, dl, VT,
14439                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14440                        Op, PreservedSrc);
14441 }
14442
14443 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14444     switch (IntNo) {
14445     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14446     case Intrinsic::x86_fma_vfmadd_ps:
14447     case Intrinsic::x86_fma_vfmadd_pd:
14448     case Intrinsic::x86_fma_vfmadd_ps_256:
14449     case Intrinsic::x86_fma_vfmadd_pd_256:
14450     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14451     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14452       return X86ISD::FMADD;
14453     case Intrinsic::x86_fma_vfmsub_ps:
14454     case Intrinsic::x86_fma_vfmsub_pd:
14455     case Intrinsic::x86_fma_vfmsub_ps_256:
14456     case Intrinsic::x86_fma_vfmsub_pd_256:
14457     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14458     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14459       return X86ISD::FMSUB;
14460     case Intrinsic::x86_fma_vfnmadd_ps:
14461     case Intrinsic::x86_fma_vfnmadd_pd:
14462     case Intrinsic::x86_fma_vfnmadd_ps_256:
14463     case Intrinsic::x86_fma_vfnmadd_pd_256:
14464     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14465     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14466       return X86ISD::FNMADD;
14467     case Intrinsic::x86_fma_vfnmsub_ps:
14468     case Intrinsic::x86_fma_vfnmsub_pd:
14469     case Intrinsic::x86_fma_vfnmsub_ps_256:
14470     case Intrinsic::x86_fma_vfnmsub_pd_256:
14471     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14472     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14473       return X86ISD::FNMSUB;
14474     case Intrinsic::x86_fma_vfmaddsub_ps:
14475     case Intrinsic::x86_fma_vfmaddsub_pd:
14476     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14477     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14478     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14479     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14480       return X86ISD::FMADDSUB;
14481     case Intrinsic::x86_fma_vfmsubadd_ps:
14482     case Intrinsic::x86_fma_vfmsubadd_pd:
14483     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14484     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14485     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14486     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14487       return X86ISD::FMSUBADD;
14488     }
14489 }
14490
14491 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14492   SDLoc dl(Op);
14493   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14494
14495   const IntrinsicData* IntrData = GetIntrinsicWithoutChain(IntNo);
14496   if (IntrData) {
14497     switch(IntrData->Type) {
14498     case INTR_TYPE_1OP:
14499       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14500     case INTR_TYPE_2OP:
14501       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14502         Op.getOperand(2));
14503     case INTR_TYPE_3OP:
14504       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14505         Op.getOperand(2), Op.getOperand(3));
14506     case COMI: { // Comparison intrinsics
14507       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14508       SDValue LHS = Op.getOperand(1);
14509       SDValue RHS = Op.getOperand(2);
14510       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14511       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14512       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14513       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14514                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14515       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14516     }
14517     case VSHIFT:
14518       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14519                                  Op.getOperand(1), Op.getOperand(2), DAG);
14520     default:
14521       break;
14522     }
14523   }
14524
14525   switch (IntNo) {
14526   default: return SDValue();    // Don't custom lower most intrinsics.
14527
14528   // Arithmetic intrinsics.
14529   case Intrinsic::x86_sse2_pmulu_dq:
14530   case Intrinsic::x86_avx2_pmulu_dq:
14531     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14532                        Op.getOperand(1), Op.getOperand(2));
14533
14534   case Intrinsic::x86_sse41_pmuldq:
14535   case Intrinsic::x86_avx2_pmul_dq:
14536     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14537                        Op.getOperand(1), Op.getOperand(2));
14538
14539   case Intrinsic::x86_sse2_pmulhu_w:
14540   case Intrinsic::x86_avx2_pmulhu_w:
14541     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14542                        Op.getOperand(1), Op.getOperand(2));
14543
14544   case Intrinsic::x86_sse2_pmulh_w:
14545   case Intrinsic::x86_avx2_pmulh_w:
14546     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14547                        Op.getOperand(1), Op.getOperand(2));
14548
14549   // SSE/SSE2/AVX floating point max/min intrinsics.
14550   case Intrinsic::x86_sse_max_ps:
14551   case Intrinsic::x86_sse2_max_pd:
14552   case Intrinsic::x86_avx_max_ps_256:
14553   case Intrinsic::x86_avx_max_pd_256:
14554   case Intrinsic::x86_sse_min_ps:
14555   case Intrinsic::x86_sse2_min_pd:
14556   case Intrinsic::x86_avx_min_ps_256:
14557   case Intrinsic::x86_avx_min_pd_256: {
14558     unsigned Opcode;
14559     switch (IntNo) {
14560     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14561     case Intrinsic::x86_sse_max_ps:
14562     case Intrinsic::x86_sse2_max_pd:
14563     case Intrinsic::x86_avx_max_ps_256:
14564     case Intrinsic::x86_avx_max_pd_256:
14565       Opcode = X86ISD::FMAX;
14566       break;
14567     case Intrinsic::x86_sse_min_ps:
14568     case Intrinsic::x86_sse2_min_pd:
14569     case Intrinsic::x86_avx_min_ps_256:
14570     case Intrinsic::x86_avx_min_pd_256:
14571       Opcode = X86ISD::FMIN;
14572       break;
14573     }
14574     return DAG.getNode(Opcode, dl, Op.getValueType(),
14575                        Op.getOperand(1), Op.getOperand(2));
14576   }
14577
14578   // AVX2 variable shift intrinsics
14579   case Intrinsic::x86_avx2_psllv_d:
14580   case Intrinsic::x86_avx2_psllv_q:
14581   case Intrinsic::x86_avx2_psllv_d_256:
14582   case Intrinsic::x86_avx2_psllv_q_256:
14583   case Intrinsic::x86_avx2_psrlv_d:
14584   case Intrinsic::x86_avx2_psrlv_q:
14585   case Intrinsic::x86_avx2_psrlv_d_256:
14586   case Intrinsic::x86_avx2_psrlv_q_256:
14587   case Intrinsic::x86_avx2_psrav_d:
14588   case Intrinsic::x86_avx2_psrav_d_256: {
14589     unsigned Opcode;
14590     switch (IntNo) {
14591     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14592     case Intrinsic::x86_avx2_psllv_d:
14593     case Intrinsic::x86_avx2_psllv_q:
14594     case Intrinsic::x86_avx2_psllv_d_256:
14595     case Intrinsic::x86_avx2_psllv_q_256:
14596       Opcode = ISD::SHL;
14597       break;
14598     case Intrinsic::x86_avx2_psrlv_d:
14599     case Intrinsic::x86_avx2_psrlv_q:
14600     case Intrinsic::x86_avx2_psrlv_d_256:
14601     case Intrinsic::x86_avx2_psrlv_q_256:
14602       Opcode = ISD::SRL;
14603       break;
14604     case Intrinsic::x86_avx2_psrav_d:
14605     case Intrinsic::x86_avx2_psrav_d_256:
14606       Opcode = ISD::SRA;
14607       break;
14608     }
14609     return DAG.getNode(Opcode, dl, Op.getValueType(),
14610                        Op.getOperand(1), Op.getOperand(2));
14611   }
14612
14613   case Intrinsic::x86_sse2_packssdw_128:
14614   case Intrinsic::x86_sse2_packsswb_128:
14615   case Intrinsic::x86_avx2_packssdw:
14616   case Intrinsic::x86_avx2_packsswb:
14617     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14618                        Op.getOperand(1), Op.getOperand(2));
14619
14620   case Intrinsic::x86_sse2_packuswb_128:
14621   case Intrinsic::x86_sse41_packusdw:
14622   case Intrinsic::x86_avx2_packuswb:
14623   case Intrinsic::x86_avx2_packusdw:
14624     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14625                        Op.getOperand(1), Op.getOperand(2));
14626
14627   case Intrinsic::x86_ssse3_pshuf_b_128:
14628   case Intrinsic::x86_avx2_pshuf_b:
14629     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14630                        Op.getOperand(1), Op.getOperand(2));
14631
14632   case Intrinsic::x86_sse2_pshuf_d:
14633     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14634                        Op.getOperand(1), Op.getOperand(2));
14635
14636   case Intrinsic::x86_sse2_pshufl_w:
14637     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14638                        Op.getOperand(1), Op.getOperand(2));
14639
14640   case Intrinsic::x86_sse2_pshufh_w:
14641     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14642                        Op.getOperand(1), Op.getOperand(2));
14643
14644   case Intrinsic::x86_ssse3_psign_b_128:
14645   case Intrinsic::x86_ssse3_psign_w_128:
14646   case Intrinsic::x86_ssse3_psign_d_128:
14647   case Intrinsic::x86_avx2_psign_b:
14648   case Intrinsic::x86_avx2_psign_w:
14649   case Intrinsic::x86_avx2_psign_d:
14650     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14651                        Op.getOperand(1), Op.getOperand(2));
14652
14653   case Intrinsic::x86_avx2_permd:
14654   case Intrinsic::x86_avx2_permps:
14655     // Operands intentionally swapped. Mask is last operand to intrinsic,
14656     // but second operand for node/instruction.
14657     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14658                        Op.getOperand(2), Op.getOperand(1));
14659
14660   case Intrinsic::x86_avx512_mask_valign_q_512:
14661   case Intrinsic::x86_avx512_mask_valign_d_512:
14662     // Vector source operands are swapped.
14663     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14664                                             Op.getValueType(), Op.getOperand(2),
14665                                             Op.getOperand(1),
14666                                             Op.getOperand(3)),
14667                                 Op.getOperand(5), Op.getOperand(4), DAG);
14668
14669   // ptest and testp intrinsics. The intrinsic these come from are designed to
14670   // return an integer value, not just an instruction so lower it to the ptest
14671   // or testp pattern and a setcc for the result.
14672   case Intrinsic::x86_sse41_ptestz:
14673   case Intrinsic::x86_sse41_ptestc:
14674   case Intrinsic::x86_sse41_ptestnzc:
14675   case Intrinsic::x86_avx_ptestz_256:
14676   case Intrinsic::x86_avx_ptestc_256:
14677   case Intrinsic::x86_avx_ptestnzc_256:
14678   case Intrinsic::x86_avx_vtestz_ps:
14679   case Intrinsic::x86_avx_vtestc_ps:
14680   case Intrinsic::x86_avx_vtestnzc_ps:
14681   case Intrinsic::x86_avx_vtestz_pd:
14682   case Intrinsic::x86_avx_vtestc_pd:
14683   case Intrinsic::x86_avx_vtestnzc_pd:
14684   case Intrinsic::x86_avx_vtestz_ps_256:
14685   case Intrinsic::x86_avx_vtestc_ps_256:
14686   case Intrinsic::x86_avx_vtestnzc_ps_256:
14687   case Intrinsic::x86_avx_vtestz_pd_256:
14688   case Intrinsic::x86_avx_vtestc_pd_256:
14689   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14690     bool IsTestPacked = false;
14691     unsigned X86CC;
14692     switch (IntNo) {
14693     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14694     case Intrinsic::x86_avx_vtestz_ps:
14695     case Intrinsic::x86_avx_vtestz_pd:
14696     case Intrinsic::x86_avx_vtestz_ps_256:
14697     case Intrinsic::x86_avx_vtestz_pd_256:
14698       IsTestPacked = true; // Fallthrough
14699     case Intrinsic::x86_sse41_ptestz:
14700     case Intrinsic::x86_avx_ptestz_256:
14701       // ZF = 1
14702       X86CC = X86::COND_E;
14703       break;
14704     case Intrinsic::x86_avx_vtestc_ps:
14705     case Intrinsic::x86_avx_vtestc_pd:
14706     case Intrinsic::x86_avx_vtestc_ps_256:
14707     case Intrinsic::x86_avx_vtestc_pd_256:
14708       IsTestPacked = true; // Fallthrough
14709     case Intrinsic::x86_sse41_ptestc:
14710     case Intrinsic::x86_avx_ptestc_256:
14711       // CF = 1
14712       X86CC = X86::COND_B;
14713       break;
14714     case Intrinsic::x86_avx_vtestnzc_ps:
14715     case Intrinsic::x86_avx_vtestnzc_pd:
14716     case Intrinsic::x86_avx_vtestnzc_ps_256:
14717     case Intrinsic::x86_avx_vtestnzc_pd_256:
14718       IsTestPacked = true; // Fallthrough
14719     case Intrinsic::x86_sse41_ptestnzc:
14720     case Intrinsic::x86_avx_ptestnzc_256:
14721       // ZF and CF = 0
14722       X86CC = X86::COND_A;
14723       break;
14724     }
14725
14726     SDValue LHS = Op.getOperand(1);
14727     SDValue RHS = Op.getOperand(2);
14728     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14729     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14730     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14731     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14732     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14733   }
14734   case Intrinsic::x86_avx512_kortestz_w:
14735   case Intrinsic::x86_avx512_kortestc_w: {
14736     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14737     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14738     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14739     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14740     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14741     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14742     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14743   }
14744
14745   case Intrinsic::x86_sse42_pcmpistria128:
14746   case Intrinsic::x86_sse42_pcmpestria128:
14747   case Intrinsic::x86_sse42_pcmpistric128:
14748   case Intrinsic::x86_sse42_pcmpestric128:
14749   case Intrinsic::x86_sse42_pcmpistrio128:
14750   case Intrinsic::x86_sse42_pcmpestrio128:
14751   case Intrinsic::x86_sse42_pcmpistris128:
14752   case Intrinsic::x86_sse42_pcmpestris128:
14753   case Intrinsic::x86_sse42_pcmpistriz128:
14754   case Intrinsic::x86_sse42_pcmpestriz128: {
14755     unsigned Opcode;
14756     unsigned X86CC;
14757     switch (IntNo) {
14758     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14759     case Intrinsic::x86_sse42_pcmpistria128:
14760       Opcode = X86ISD::PCMPISTRI;
14761       X86CC = X86::COND_A;
14762       break;
14763     case Intrinsic::x86_sse42_pcmpestria128:
14764       Opcode = X86ISD::PCMPESTRI;
14765       X86CC = X86::COND_A;
14766       break;
14767     case Intrinsic::x86_sse42_pcmpistric128:
14768       Opcode = X86ISD::PCMPISTRI;
14769       X86CC = X86::COND_B;
14770       break;
14771     case Intrinsic::x86_sse42_pcmpestric128:
14772       Opcode = X86ISD::PCMPESTRI;
14773       X86CC = X86::COND_B;
14774       break;
14775     case Intrinsic::x86_sse42_pcmpistrio128:
14776       Opcode = X86ISD::PCMPISTRI;
14777       X86CC = X86::COND_O;
14778       break;
14779     case Intrinsic::x86_sse42_pcmpestrio128:
14780       Opcode = X86ISD::PCMPESTRI;
14781       X86CC = X86::COND_O;
14782       break;
14783     case Intrinsic::x86_sse42_pcmpistris128:
14784       Opcode = X86ISD::PCMPISTRI;
14785       X86CC = X86::COND_S;
14786       break;
14787     case Intrinsic::x86_sse42_pcmpestris128:
14788       Opcode = X86ISD::PCMPESTRI;
14789       X86CC = X86::COND_S;
14790       break;
14791     case Intrinsic::x86_sse42_pcmpistriz128:
14792       Opcode = X86ISD::PCMPISTRI;
14793       X86CC = X86::COND_E;
14794       break;
14795     case Intrinsic::x86_sse42_pcmpestriz128:
14796       Opcode = X86ISD::PCMPESTRI;
14797       X86CC = X86::COND_E;
14798       break;
14799     }
14800     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14801     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14802     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14803     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14804                                 DAG.getConstant(X86CC, MVT::i8),
14805                                 SDValue(PCMP.getNode(), 1));
14806     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14807   }
14808
14809   case Intrinsic::x86_sse42_pcmpistri128:
14810   case Intrinsic::x86_sse42_pcmpestri128: {
14811     unsigned Opcode;
14812     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14813       Opcode = X86ISD::PCMPISTRI;
14814     else
14815       Opcode = X86ISD::PCMPESTRI;
14816
14817     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14818     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14819     return DAG.getNode(Opcode, dl, VTs, NewOps);
14820   }
14821
14822   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14823   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14824   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14825   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14826   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14827   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14828   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14829   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14830   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14831   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14832   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14833   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
14834     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
14835     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
14836       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
14837                                               dl, Op.getValueType(),
14838                                               Op.getOperand(1),
14839                                               Op.getOperand(2),
14840                                               Op.getOperand(3)),
14841                                   Op.getOperand(4), Op.getOperand(1), DAG);
14842     else
14843       return SDValue();
14844   }
14845
14846   case Intrinsic::x86_fma_vfmadd_ps:
14847   case Intrinsic::x86_fma_vfmadd_pd:
14848   case Intrinsic::x86_fma_vfmsub_ps:
14849   case Intrinsic::x86_fma_vfmsub_pd:
14850   case Intrinsic::x86_fma_vfnmadd_ps:
14851   case Intrinsic::x86_fma_vfnmadd_pd:
14852   case Intrinsic::x86_fma_vfnmsub_ps:
14853   case Intrinsic::x86_fma_vfnmsub_pd:
14854   case Intrinsic::x86_fma_vfmaddsub_ps:
14855   case Intrinsic::x86_fma_vfmaddsub_pd:
14856   case Intrinsic::x86_fma_vfmsubadd_ps:
14857   case Intrinsic::x86_fma_vfmsubadd_pd:
14858   case Intrinsic::x86_fma_vfmadd_ps_256:
14859   case Intrinsic::x86_fma_vfmadd_pd_256:
14860   case Intrinsic::x86_fma_vfmsub_ps_256:
14861   case Intrinsic::x86_fma_vfmsub_pd_256:
14862   case Intrinsic::x86_fma_vfnmadd_ps_256:
14863   case Intrinsic::x86_fma_vfnmadd_pd_256:
14864   case Intrinsic::x86_fma_vfnmsub_ps_256:
14865   case Intrinsic::x86_fma_vfnmsub_pd_256:
14866   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14867   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14868   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14869   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14870     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
14871                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14872   }
14873 }
14874
14875 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14876                               SDValue Src, SDValue Mask, SDValue Base,
14877                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14878                               const X86Subtarget * Subtarget) {
14879   SDLoc dl(Op);
14880   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14881   assert(C && "Invalid scale type");
14882   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14883   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14884                              Index.getSimpleValueType().getVectorNumElements());
14885   SDValue MaskInReg;
14886   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14887   if (MaskC)
14888     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14889   else
14890     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14891   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14892   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14893   SDValue Segment = DAG.getRegister(0, MVT::i32);
14894   if (Src.getOpcode() == ISD::UNDEF)
14895     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14896   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14897   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14898   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14899   return DAG.getMergeValues(RetOps, dl);
14900 }
14901
14902 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14903                                SDValue Src, SDValue Mask, SDValue Base,
14904                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14905   SDLoc dl(Op);
14906   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14907   assert(C && "Invalid scale type");
14908   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14909   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14910   SDValue Segment = DAG.getRegister(0, MVT::i32);
14911   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14912                              Index.getSimpleValueType().getVectorNumElements());
14913   SDValue MaskInReg;
14914   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14915   if (MaskC)
14916     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14917   else
14918     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14919   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14920   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14921   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14922   return SDValue(Res, 1);
14923 }
14924
14925 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14926                                SDValue Mask, SDValue Base, SDValue Index,
14927                                SDValue ScaleOp, SDValue Chain) {
14928   SDLoc dl(Op);
14929   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14930   assert(C && "Invalid scale type");
14931   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14932   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14933   SDValue Segment = DAG.getRegister(0, MVT::i32);
14934   EVT MaskVT =
14935     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14936   SDValue MaskInReg;
14937   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14938   if (MaskC)
14939     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14940   else
14941     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14942   //SDVTList VTs = DAG.getVTList(MVT::Other);
14943   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14944   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14945   return SDValue(Res, 0);
14946 }
14947
14948 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14949 // read performance monitor counters (x86_rdpmc).
14950 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14951                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14952                               SmallVectorImpl<SDValue> &Results) {
14953   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14954   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14955   SDValue LO, HI;
14956
14957   // The ECX register is used to select the index of the performance counter
14958   // to read.
14959   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14960                                    N->getOperand(2));
14961   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14962
14963   // Reads the content of a 64-bit performance counter and returns it in the
14964   // registers EDX:EAX.
14965   if (Subtarget->is64Bit()) {
14966     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14967     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14968                             LO.getValue(2));
14969   } else {
14970     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14971     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14972                             LO.getValue(2));
14973   }
14974   Chain = HI.getValue(1);
14975
14976   if (Subtarget->is64Bit()) {
14977     // The EAX register is loaded with the low-order 32 bits. The EDX register
14978     // is loaded with the supported high-order bits of the counter.
14979     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14980                               DAG.getConstant(32, MVT::i8));
14981     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14982     Results.push_back(Chain);
14983     return;
14984   }
14985
14986   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14987   SDValue Ops[] = { LO, HI };
14988   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14989   Results.push_back(Pair);
14990   Results.push_back(Chain);
14991 }
14992
14993 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14994 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14995 // also used to custom lower READCYCLECOUNTER nodes.
14996 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14997                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14998                               SmallVectorImpl<SDValue> &Results) {
14999   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15000   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15001   SDValue LO, HI;
15002
15003   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15004   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15005   // and the EAX register is loaded with the low-order 32 bits.
15006   if (Subtarget->is64Bit()) {
15007     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15008     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15009                             LO.getValue(2));
15010   } else {
15011     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15012     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15013                             LO.getValue(2));
15014   }
15015   SDValue Chain = HI.getValue(1);
15016
15017   if (Opcode == X86ISD::RDTSCP_DAG) {
15018     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15019
15020     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15021     // the ECX register. Add 'ecx' explicitly to the chain.
15022     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15023                                      HI.getValue(2));
15024     // Explicitly store the content of ECX at the location passed in input
15025     // to the 'rdtscp' intrinsic.
15026     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15027                          MachinePointerInfo(), false, false, 0);
15028   }
15029
15030   if (Subtarget->is64Bit()) {
15031     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15032     // the EAX register is loaded with the low-order 32 bits.
15033     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15034                               DAG.getConstant(32, MVT::i8));
15035     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15036     Results.push_back(Chain);
15037     return;
15038   }
15039
15040   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15041   SDValue Ops[] = { LO, HI };
15042   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15043   Results.push_back(Pair);
15044   Results.push_back(Chain);
15045 }
15046
15047 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15048                                      SelectionDAG &DAG) {
15049   SmallVector<SDValue, 2> Results;
15050   SDLoc DL(Op);
15051   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15052                           Results);
15053   return DAG.getMergeValues(Results, DL);
15054 }
15055
15056
15057 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15058                                       SelectionDAG &DAG) {
15059   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15060
15061   const IntrinsicData* IntrData = GetIntrinsicWithChain(IntNo);
15062   if (!IntrData)
15063     return SDValue();
15064
15065   SDLoc dl(Op);
15066   switch(IntrData->Type) {
15067   default:
15068     llvm_unreachable("Unknown Intrinsic Type");
15069     break;    
15070   case RDSEED:
15071   case RDRAND: {
15072     // Emit the node with the right value type.
15073     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15074     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15075
15076     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15077     // Otherwise return the value from Rand, which is always 0, casted to i32.
15078     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15079                       DAG.getConstant(1, Op->getValueType(1)),
15080                       DAG.getConstant(X86::COND_B, MVT::i32),
15081                       SDValue(Result.getNode(), 1) };
15082     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15083                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15084                                   Ops);
15085
15086     // Return { result, isValid, chain }.
15087     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15088                        SDValue(Result.getNode(), 2));
15089   }
15090   case GATHER: {
15091   //gather(v1, mask, index, base, scale);
15092     SDValue Chain = Op.getOperand(0);
15093     SDValue Src   = Op.getOperand(2);
15094     SDValue Base  = Op.getOperand(3);
15095     SDValue Index = Op.getOperand(4);
15096     SDValue Mask  = Op.getOperand(5);
15097     SDValue Scale = Op.getOperand(6);
15098     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15099                           Subtarget);
15100   }
15101   case SCATTER: {
15102   //scatter(base, mask, index, v1, scale);
15103     SDValue Chain = Op.getOperand(0);
15104     SDValue Base  = Op.getOperand(2);
15105     SDValue Mask  = Op.getOperand(3);
15106     SDValue Index = Op.getOperand(4);
15107     SDValue Src   = Op.getOperand(5);
15108     SDValue Scale = Op.getOperand(6);
15109     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15110   }
15111   case PREFETCH: {
15112     SDValue Hint = Op.getOperand(6);
15113     unsigned HintVal;
15114     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15115         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15116       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15117     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15118     SDValue Chain = Op.getOperand(0);
15119     SDValue Mask  = Op.getOperand(2);
15120     SDValue Index = Op.getOperand(3);
15121     SDValue Base  = Op.getOperand(4);
15122     SDValue Scale = Op.getOperand(5);
15123     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15124   }
15125   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15126   case RDTSC: {
15127     SmallVector<SDValue, 2> Results;
15128     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15129     return DAG.getMergeValues(Results, dl);
15130   }
15131   // Read Performance Monitoring Counters.
15132   case RDPMC: {
15133     SmallVector<SDValue, 2> Results;
15134     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15135     return DAG.getMergeValues(Results, dl);
15136   }
15137   // XTEST intrinsics.
15138   case XTEST: {
15139     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15140     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15141     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15142                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15143                                 InTrans);
15144     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15145     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15146                        Ret, SDValue(InTrans.getNode(), 1));
15147   }
15148   // ADC/ADCX/SBB
15149   case ADX: {
15150     SmallVector<SDValue, 2> Results;
15151     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15152     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15153     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15154                                 DAG.getConstant(-1, MVT::i8));
15155     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15156                               Op.getOperand(4), GenCF.getValue(1));
15157     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15158                                  Op.getOperand(5), MachinePointerInfo(),
15159                                  false, false, 0);
15160     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15161                                 DAG.getConstant(X86::COND_B, MVT::i8),
15162                                 Res.getValue(1));
15163     Results.push_back(SetCC);
15164     Results.push_back(Store);
15165     return DAG.getMergeValues(Results, dl);
15166   }
15167   }
15168 }
15169
15170 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15171                                            SelectionDAG &DAG) const {
15172   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15173   MFI->setReturnAddressIsTaken(true);
15174
15175   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15176     return SDValue();
15177
15178   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15179   SDLoc dl(Op);
15180   EVT PtrVT = getPointerTy();
15181
15182   if (Depth > 0) {
15183     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15184     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15185         DAG.getSubtarget().getRegisterInfo());
15186     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15187     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15188                        DAG.getNode(ISD::ADD, dl, PtrVT,
15189                                    FrameAddr, Offset),
15190                        MachinePointerInfo(), false, false, false, 0);
15191   }
15192
15193   // Just load the return address.
15194   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15195   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15196                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15197 }
15198
15199 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15200   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15201   MFI->setFrameAddressIsTaken(true);
15202
15203   EVT VT = Op.getValueType();
15204   SDLoc dl(Op);  // FIXME probably not meaningful
15205   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15206   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15207       DAG.getSubtarget().getRegisterInfo());
15208   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15209   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15210           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15211          "Invalid Frame Register!");
15212   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15213   while (Depth--)
15214     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15215                             MachinePointerInfo(),
15216                             false, false, false, 0);
15217   return FrameAddr;
15218 }
15219
15220 // FIXME? Maybe this could be a TableGen attribute on some registers and
15221 // this table could be generated automatically from RegInfo.
15222 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15223                                               EVT VT) const {
15224   unsigned Reg = StringSwitch<unsigned>(RegName)
15225                        .Case("esp", X86::ESP)
15226                        .Case("rsp", X86::RSP)
15227                        .Default(0);
15228   if (Reg)
15229     return Reg;
15230   report_fatal_error("Invalid register name global variable");
15231 }
15232
15233 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15234                                                      SelectionDAG &DAG) const {
15235   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15236       DAG.getSubtarget().getRegisterInfo());
15237   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15238 }
15239
15240 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15241   SDValue Chain     = Op.getOperand(0);
15242   SDValue Offset    = Op.getOperand(1);
15243   SDValue Handler   = Op.getOperand(2);
15244   SDLoc dl      (Op);
15245
15246   EVT PtrVT = getPointerTy();
15247   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15248       DAG.getSubtarget().getRegisterInfo());
15249   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15250   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15251           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15252          "Invalid Frame Register!");
15253   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15254   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15255
15256   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15257                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15258   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15259   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15260                        false, false, 0);
15261   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15262
15263   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15264                      DAG.getRegister(StoreAddrReg, PtrVT));
15265 }
15266
15267 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15268                                                SelectionDAG &DAG) const {
15269   SDLoc DL(Op);
15270   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15271                      DAG.getVTList(MVT::i32, MVT::Other),
15272                      Op.getOperand(0), Op.getOperand(1));
15273 }
15274
15275 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15276                                                 SelectionDAG &DAG) const {
15277   SDLoc DL(Op);
15278   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15279                      Op.getOperand(0), Op.getOperand(1));
15280 }
15281
15282 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15283   return Op.getOperand(0);
15284 }
15285
15286 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15287                                                 SelectionDAG &DAG) const {
15288   SDValue Root = Op.getOperand(0);
15289   SDValue Trmp = Op.getOperand(1); // trampoline
15290   SDValue FPtr = Op.getOperand(2); // nested function
15291   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15292   SDLoc dl (Op);
15293
15294   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15295   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15296
15297   if (Subtarget->is64Bit()) {
15298     SDValue OutChains[6];
15299
15300     // Large code-model.
15301     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15302     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15303
15304     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15305     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15306
15307     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15308
15309     // Load the pointer to the nested function into R11.
15310     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15311     SDValue Addr = Trmp;
15312     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15313                                 Addr, MachinePointerInfo(TrmpAddr),
15314                                 false, false, 0);
15315
15316     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15317                        DAG.getConstant(2, MVT::i64));
15318     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15319                                 MachinePointerInfo(TrmpAddr, 2),
15320                                 false, false, 2);
15321
15322     // Load the 'nest' parameter value into R10.
15323     // R10 is specified in X86CallingConv.td
15324     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15325     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15326                        DAG.getConstant(10, MVT::i64));
15327     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15328                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15329                                 false, false, 0);
15330
15331     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15332                        DAG.getConstant(12, MVT::i64));
15333     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15334                                 MachinePointerInfo(TrmpAddr, 12),
15335                                 false, false, 2);
15336
15337     // Jump to the nested function.
15338     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15339     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15340                        DAG.getConstant(20, MVT::i64));
15341     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15342                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15343                                 false, false, 0);
15344
15345     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15346     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15347                        DAG.getConstant(22, MVT::i64));
15348     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15349                                 MachinePointerInfo(TrmpAddr, 22),
15350                                 false, false, 0);
15351
15352     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15353   } else {
15354     const Function *Func =
15355       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15356     CallingConv::ID CC = Func->getCallingConv();
15357     unsigned NestReg;
15358
15359     switch (CC) {
15360     default:
15361       llvm_unreachable("Unsupported calling convention");
15362     case CallingConv::C:
15363     case CallingConv::X86_StdCall: {
15364       // Pass 'nest' parameter in ECX.
15365       // Must be kept in sync with X86CallingConv.td
15366       NestReg = X86::ECX;
15367
15368       // Check that ECX wasn't needed by an 'inreg' parameter.
15369       FunctionType *FTy = Func->getFunctionType();
15370       const AttributeSet &Attrs = Func->getAttributes();
15371
15372       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15373         unsigned InRegCount = 0;
15374         unsigned Idx = 1;
15375
15376         for (FunctionType::param_iterator I = FTy->param_begin(),
15377              E = FTy->param_end(); I != E; ++I, ++Idx)
15378           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15379             // FIXME: should only count parameters that are lowered to integers.
15380             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15381
15382         if (InRegCount > 2) {
15383           report_fatal_error("Nest register in use - reduce number of inreg"
15384                              " parameters!");
15385         }
15386       }
15387       break;
15388     }
15389     case CallingConv::X86_FastCall:
15390     case CallingConv::X86_ThisCall:
15391     case CallingConv::Fast:
15392       // Pass 'nest' parameter in EAX.
15393       // Must be kept in sync with X86CallingConv.td
15394       NestReg = X86::EAX;
15395       break;
15396     }
15397
15398     SDValue OutChains[4];
15399     SDValue Addr, Disp;
15400
15401     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15402                        DAG.getConstant(10, MVT::i32));
15403     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15404
15405     // This is storing the opcode for MOV32ri.
15406     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15407     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15408     OutChains[0] = DAG.getStore(Root, dl,
15409                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15410                                 Trmp, MachinePointerInfo(TrmpAddr),
15411                                 false, false, 0);
15412
15413     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15414                        DAG.getConstant(1, MVT::i32));
15415     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15416                                 MachinePointerInfo(TrmpAddr, 1),
15417                                 false, false, 1);
15418
15419     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15420     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15421                        DAG.getConstant(5, MVT::i32));
15422     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15423                                 MachinePointerInfo(TrmpAddr, 5),
15424                                 false, false, 1);
15425
15426     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15427                        DAG.getConstant(6, MVT::i32));
15428     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15429                                 MachinePointerInfo(TrmpAddr, 6),
15430                                 false, false, 1);
15431
15432     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15433   }
15434 }
15435
15436 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15437                                             SelectionDAG &DAG) const {
15438   /*
15439    The rounding mode is in bits 11:10 of FPSR, and has the following
15440    settings:
15441      00 Round to nearest
15442      01 Round to -inf
15443      10 Round to +inf
15444      11 Round to 0
15445
15446   FLT_ROUNDS, on the other hand, expects the following:
15447     -1 Undefined
15448      0 Round to 0
15449      1 Round to nearest
15450      2 Round to +inf
15451      3 Round to -inf
15452
15453   To perform the conversion, we do:
15454     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15455   */
15456
15457   MachineFunction &MF = DAG.getMachineFunction();
15458   const TargetMachine &TM = MF.getTarget();
15459   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15460   unsigned StackAlignment = TFI.getStackAlignment();
15461   MVT VT = Op.getSimpleValueType();
15462   SDLoc DL(Op);
15463
15464   // Save FP Control Word to stack slot
15465   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15466   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15467
15468   MachineMemOperand *MMO =
15469    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15470                            MachineMemOperand::MOStore, 2, 2);
15471
15472   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15473   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15474                                           DAG.getVTList(MVT::Other),
15475                                           Ops, MVT::i16, MMO);
15476
15477   // Load FP Control Word from stack slot
15478   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15479                             MachinePointerInfo(), false, false, false, 0);
15480
15481   // Transform as necessary
15482   SDValue CWD1 =
15483     DAG.getNode(ISD::SRL, DL, MVT::i16,
15484                 DAG.getNode(ISD::AND, DL, MVT::i16,
15485                             CWD, DAG.getConstant(0x800, MVT::i16)),
15486                 DAG.getConstant(11, MVT::i8));
15487   SDValue CWD2 =
15488     DAG.getNode(ISD::SRL, DL, MVT::i16,
15489                 DAG.getNode(ISD::AND, DL, MVT::i16,
15490                             CWD, DAG.getConstant(0x400, MVT::i16)),
15491                 DAG.getConstant(9, MVT::i8));
15492
15493   SDValue RetVal =
15494     DAG.getNode(ISD::AND, DL, MVT::i16,
15495                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15496                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15497                             DAG.getConstant(1, MVT::i16)),
15498                 DAG.getConstant(3, MVT::i16));
15499
15500   return DAG.getNode((VT.getSizeInBits() < 16 ?
15501                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15502 }
15503
15504 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15505   MVT VT = Op.getSimpleValueType();
15506   EVT OpVT = VT;
15507   unsigned NumBits = VT.getSizeInBits();
15508   SDLoc dl(Op);
15509
15510   Op = Op.getOperand(0);
15511   if (VT == MVT::i8) {
15512     // Zero extend to i32 since there is not an i8 bsr.
15513     OpVT = MVT::i32;
15514     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15515   }
15516
15517   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15518   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15519   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15520
15521   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15522   SDValue Ops[] = {
15523     Op,
15524     DAG.getConstant(NumBits+NumBits-1, OpVT),
15525     DAG.getConstant(X86::COND_E, MVT::i8),
15526     Op.getValue(1)
15527   };
15528   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15529
15530   // Finally xor with NumBits-1.
15531   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15532
15533   if (VT == MVT::i8)
15534     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15535   return Op;
15536 }
15537
15538 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15539   MVT VT = Op.getSimpleValueType();
15540   EVT OpVT = VT;
15541   unsigned NumBits = VT.getSizeInBits();
15542   SDLoc dl(Op);
15543
15544   Op = Op.getOperand(0);
15545   if (VT == MVT::i8) {
15546     // Zero extend to i32 since there is not an i8 bsr.
15547     OpVT = MVT::i32;
15548     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15549   }
15550
15551   // Issue a bsr (scan bits in reverse).
15552   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15553   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15554
15555   // And xor with NumBits-1.
15556   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15557
15558   if (VT == MVT::i8)
15559     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15560   return Op;
15561 }
15562
15563 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15564   MVT VT = Op.getSimpleValueType();
15565   unsigned NumBits = VT.getSizeInBits();
15566   SDLoc dl(Op);
15567   Op = Op.getOperand(0);
15568
15569   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15570   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15571   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15572
15573   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15574   SDValue Ops[] = {
15575     Op,
15576     DAG.getConstant(NumBits, VT),
15577     DAG.getConstant(X86::COND_E, MVT::i8),
15578     Op.getValue(1)
15579   };
15580   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15581 }
15582
15583 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15584 // ones, and then concatenate the result back.
15585 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15586   MVT VT = Op.getSimpleValueType();
15587
15588   assert(VT.is256BitVector() && VT.isInteger() &&
15589          "Unsupported value type for operation");
15590
15591   unsigned NumElems = VT.getVectorNumElements();
15592   SDLoc dl(Op);
15593
15594   // Extract the LHS vectors
15595   SDValue LHS = Op.getOperand(0);
15596   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15597   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15598
15599   // Extract the RHS vectors
15600   SDValue RHS = Op.getOperand(1);
15601   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15602   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15603
15604   MVT EltVT = VT.getVectorElementType();
15605   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15606
15607   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15608                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15609                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15610 }
15611
15612 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15613   assert(Op.getSimpleValueType().is256BitVector() &&
15614          Op.getSimpleValueType().isInteger() &&
15615          "Only handle AVX 256-bit vector integer operation");
15616   return Lower256IntArith(Op, DAG);
15617 }
15618
15619 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15620   assert(Op.getSimpleValueType().is256BitVector() &&
15621          Op.getSimpleValueType().isInteger() &&
15622          "Only handle AVX 256-bit vector integer operation");
15623   return Lower256IntArith(Op, DAG);
15624 }
15625
15626 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15627                         SelectionDAG &DAG) {
15628   SDLoc dl(Op);
15629   MVT VT = Op.getSimpleValueType();
15630
15631   // Decompose 256-bit ops into smaller 128-bit ops.
15632   if (VT.is256BitVector() && !Subtarget->hasInt256())
15633     return Lower256IntArith(Op, DAG);
15634
15635   SDValue A = Op.getOperand(0);
15636   SDValue B = Op.getOperand(1);
15637
15638   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15639   if (VT == MVT::v4i32) {
15640     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15641            "Should not custom lower when pmuldq is available!");
15642
15643     // Extract the odd parts.
15644     static const int UnpackMask[] = { 1, -1, 3, -1 };
15645     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15646     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15647
15648     // Multiply the even parts.
15649     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15650     // Now multiply odd parts.
15651     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15652
15653     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15654     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15655
15656     // Merge the two vectors back together with a shuffle. This expands into 2
15657     // shuffles.
15658     static const int ShufMask[] = { 0, 4, 2, 6 };
15659     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15660   }
15661
15662   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15663          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15664
15665   //  Ahi = psrlqi(a, 32);
15666   //  Bhi = psrlqi(b, 32);
15667   //
15668   //  AloBlo = pmuludq(a, b);
15669   //  AloBhi = pmuludq(a, Bhi);
15670   //  AhiBlo = pmuludq(Ahi, b);
15671
15672   //  AloBhi = psllqi(AloBhi, 32);
15673   //  AhiBlo = psllqi(AhiBlo, 32);
15674   //  return AloBlo + AloBhi + AhiBlo;
15675
15676   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15677   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15678
15679   // Bit cast to 32-bit vectors for MULUDQ
15680   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15681                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15682   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15683   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15684   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15685   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15686
15687   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15688   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15689   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15690
15691   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15692   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15693
15694   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15695   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15696 }
15697
15698 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15699   assert(Subtarget->isTargetWin64() && "Unexpected target");
15700   EVT VT = Op.getValueType();
15701   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15702          "Unexpected return type for lowering");
15703
15704   RTLIB::Libcall LC;
15705   bool isSigned;
15706   switch (Op->getOpcode()) {
15707   default: llvm_unreachable("Unexpected request for libcall!");
15708   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15709   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15710   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15711   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15712   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15713   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15714   }
15715
15716   SDLoc dl(Op);
15717   SDValue InChain = DAG.getEntryNode();
15718
15719   TargetLowering::ArgListTy Args;
15720   TargetLowering::ArgListEntry Entry;
15721   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15722     EVT ArgVT = Op->getOperand(i).getValueType();
15723     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15724            "Unexpected argument type for lowering");
15725     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15726     Entry.Node = StackPtr;
15727     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15728                            false, false, 16);
15729     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15730     Entry.Ty = PointerType::get(ArgTy,0);
15731     Entry.isSExt = false;
15732     Entry.isZExt = false;
15733     Args.push_back(Entry);
15734   }
15735
15736   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15737                                          getPointerTy());
15738
15739   TargetLowering::CallLoweringInfo CLI(DAG);
15740   CLI.setDebugLoc(dl).setChain(InChain)
15741     .setCallee(getLibcallCallingConv(LC),
15742                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15743                Callee, std::move(Args), 0)
15744     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15745
15746   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15747   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15748 }
15749
15750 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15751                              SelectionDAG &DAG) {
15752   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15753   EVT VT = Op0.getValueType();
15754   SDLoc dl(Op);
15755
15756   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15757          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15758
15759   // PMULxD operations multiply each even value (starting at 0) of LHS with
15760   // the related value of RHS and produce a widen result.
15761   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15762   // => <2 x i64> <ae|cg>
15763   //
15764   // In other word, to have all the results, we need to perform two PMULxD:
15765   // 1. one with the even values.
15766   // 2. one with the odd values.
15767   // To achieve #2, with need to place the odd values at an even position.
15768   //
15769   // Place the odd value at an even position (basically, shift all values 1
15770   // step to the left):
15771   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15772   // <a|b|c|d> => <b|undef|d|undef>
15773   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15774   // <e|f|g|h> => <f|undef|h|undef>
15775   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15776
15777   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15778   // ints.
15779   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15780   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15781   unsigned Opcode =
15782       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15783   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15784   // => <2 x i64> <ae|cg>
15785   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15786                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15787   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15788   // => <2 x i64> <bf|dh>
15789   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15790                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15791
15792   // Shuffle it back into the right order.
15793   SDValue Highs, Lows;
15794   if (VT == MVT::v8i32) {
15795     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15796     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15797     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15798     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15799   } else {
15800     const int HighMask[] = {1, 5, 3, 7};
15801     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15802     const int LowMask[] = {0, 4, 2, 6};
15803     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15804   }
15805
15806   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15807   // unsigned multiply.
15808   if (IsSigned && !Subtarget->hasSSE41()) {
15809     SDValue ShAmt =
15810         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15811     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15812                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15813     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15814                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15815
15816     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15817     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15818   }
15819
15820   // The first result of MUL_LOHI is actually the low value, followed by the
15821   // high value.
15822   SDValue Ops[] = {Lows, Highs};
15823   return DAG.getMergeValues(Ops, dl);
15824 }
15825
15826 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15827                                          const X86Subtarget *Subtarget) {
15828   MVT VT = Op.getSimpleValueType();
15829   SDLoc dl(Op);
15830   SDValue R = Op.getOperand(0);
15831   SDValue Amt = Op.getOperand(1);
15832
15833   // Optimize shl/srl/sra with constant shift amount.
15834   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15835     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15836       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15837
15838       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15839           (Subtarget->hasInt256() &&
15840            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15841           (Subtarget->hasAVX512() &&
15842            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15843         if (Op.getOpcode() == ISD::SHL)
15844           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15845                                             DAG);
15846         if (Op.getOpcode() == ISD::SRL)
15847           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15848                                             DAG);
15849         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15850           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15851                                             DAG);
15852       }
15853
15854       if (VT == MVT::v16i8) {
15855         if (Op.getOpcode() == ISD::SHL) {
15856           // Make a large shift.
15857           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15858                                                    MVT::v8i16, R, ShiftAmt,
15859                                                    DAG);
15860           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15861           // Zero out the rightmost bits.
15862           SmallVector<SDValue, 16> V(16,
15863                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15864                                                      MVT::i8));
15865           return DAG.getNode(ISD::AND, dl, VT, SHL,
15866                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15867         }
15868         if (Op.getOpcode() == ISD::SRL) {
15869           // Make a large shift.
15870           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15871                                                    MVT::v8i16, R, ShiftAmt,
15872                                                    DAG);
15873           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15874           // Zero out the leftmost bits.
15875           SmallVector<SDValue, 16> V(16,
15876                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15877                                                      MVT::i8));
15878           return DAG.getNode(ISD::AND, dl, VT, SRL,
15879                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15880         }
15881         if (Op.getOpcode() == ISD::SRA) {
15882           if (ShiftAmt == 7) {
15883             // R s>> 7  ===  R s< 0
15884             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15885             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15886           }
15887
15888           // R s>> a === ((R u>> a) ^ m) - m
15889           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15890           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15891                                                          MVT::i8));
15892           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15893           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15894           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15895           return Res;
15896         }
15897         llvm_unreachable("Unknown shift opcode.");
15898       }
15899
15900       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15901         if (Op.getOpcode() == ISD::SHL) {
15902           // Make a large shift.
15903           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15904                                                    MVT::v16i16, R, ShiftAmt,
15905                                                    DAG);
15906           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15907           // Zero out the rightmost bits.
15908           SmallVector<SDValue, 32> V(32,
15909                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15910                                                      MVT::i8));
15911           return DAG.getNode(ISD::AND, dl, VT, SHL,
15912                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15913         }
15914         if (Op.getOpcode() == ISD::SRL) {
15915           // Make a large shift.
15916           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15917                                                    MVT::v16i16, R, ShiftAmt,
15918                                                    DAG);
15919           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15920           // Zero out the leftmost bits.
15921           SmallVector<SDValue, 32> V(32,
15922                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15923                                                      MVT::i8));
15924           return DAG.getNode(ISD::AND, dl, VT, SRL,
15925                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15926         }
15927         if (Op.getOpcode() == ISD::SRA) {
15928           if (ShiftAmt == 7) {
15929             // R s>> 7  ===  R s< 0
15930             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15931             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15932           }
15933
15934           // R s>> a === ((R u>> a) ^ m) - m
15935           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15936           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15937                                                          MVT::i8));
15938           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15939           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15940           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15941           return Res;
15942         }
15943         llvm_unreachable("Unknown shift opcode.");
15944       }
15945     }
15946   }
15947
15948   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15949   if (!Subtarget->is64Bit() &&
15950       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15951       Amt.getOpcode() == ISD::BITCAST &&
15952       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15953     Amt = Amt.getOperand(0);
15954     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15955                      VT.getVectorNumElements();
15956     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15957     uint64_t ShiftAmt = 0;
15958     for (unsigned i = 0; i != Ratio; ++i) {
15959       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15960       if (!C)
15961         return SDValue();
15962       // 6 == Log2(64)
15963       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15964     }
15965     // Check remaining shift amounts.
15966     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15967       uint64_t ShAmt = 0;
15968       for (unsigned j = 0; j != Ratio; ++j) {
15969         ConstantSDNode *C =
15970           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15971         if (!C)
15972           return SDValue();
15973         // 6 == Log2(64)
15974         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15975       }
15976       if (ShAmt != ShiftAmt)
15977         return SDValue();
15978     }
15979     switch (Op.getOpcode()) {
15980     default:
15981       llvm_unreachable("Unknown shift opcode!");
15982     case ISD::SHL:
15983       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15984                                         DAG);
15985     case ISD::SRL:
15986       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15987                                         DAG);
15988     case ISD::SRA:
15989       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15990                                         DAG);
15991     }
15992   }
15993
15994   return SDValue();
15995 }
15996
15997 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15998                                         const X86Subtarget* Subtarget) {
15999   MVT VT = Op.getSimpleValueType();
16000   SDLoc dl(Op);
16001   SDValue R = Op.getOperand(0);
16002   SDValue Amt = Op.getOperand(1);
16003
16004   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16005       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16006       (Subtarget->hasInt256() &&
16007        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16008         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16009        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16010     SDValue BaseShAmt;
16011     EVT EltVT = VT.getVectorElementType();
16012
16013     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16014       unsigned NumElts = VT.getVectorNumElements();
16015       unsigned i, j;
16016       for (i = 0; i != NumElts; ++i) {
16017         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16018           continue;
16019         break;
16020       }
16021       for (j = i; j != NumElts; ++j) {
16022         SDValue Arg = Amt.getOperand(j);
16023         if (Arg.getOpcode() == ISD::UNDEF) continue;
16024         if (Arg != Amt.getOperand(i))
16025           break;
16026       }
16027       if (i != NumElts && j == NumElts)
16028         BaseShAmt = Amt.getOperand(i);
16029     } else {
16030       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16031         Amt = Amt.getOperand(0);
16032       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16033                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16034         SDValue InVec = Amt.getOperand(0);
16035         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16036           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16037           unsigned i = 0;
16038           for (; i != NumElts; ++i) {
16039             SDValue Arg = InVec.getOperand(i);
16040             if (Arg.getOpcode() == ISD::UNDEF) continue;
16041             BaseShAmt = Arg;
16042             break;
16043           }
16044         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16045            if (ConstantSDNode *C =
16046                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16047              unsigned SplatIdx =
16048                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16049              if (C->getZExtValue() == SplatIdx)
16050                BaseShAmt = InVec.getOperand(1);
16051            }
16052         }
16053         if (!BaseShAmt.getNode())
16054           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16055                                   DAG.getIntPtrConstant(0));
16056       }
16057     }
16058
16059     if (BaseShAmt.getNode()) {
16060       if (EltVT.bitsGT(MVT::i32))
16061         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16062       else if (EltVT.bitsLT(MVT::i32))
16063         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16064
16065       switch (Op.getOpcode()) {
16066       default:
16067         llvm_unreachable("Unknown shift opcode!");
16068       case ISD::SHL:
16069         switch (VT.SimpleTy) {
16070         default: return SDValue();
16071         case MVT::v2i64:
16072         case MVT::v4i32:
16073         case MVT::v8i16:
16074         case MVT::v4i64:
16075         case MVT::v8i32:
16076         case MVT::v16i16:
16077         case MVT::v16i32:
16078         case MVT::v8i64:
16079           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16080         }
16081       case ISD::SRA:
16082         switch (VT.SimpleTy) {
16083         default: return SDValue();
16084         case MVT::v4i32:
16085         case MVT::v8i16:
16086         case MVT::v8i32:
16087         case MVT::v16i16:
16088         case MVT::v16i32:
16089         case MVT::v8i64:
16090           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16091         }
16092       case ISD::SRL:
16093         switch (VT.SimpleTy) {
16094         default: return SDValue();
16095         case MVT::v2i64:
16096         case MVT::v4i32:
16097         case MVT::v8i16:
16098         case MVT::v4i64:
16099         case MVT::v8i32:
16100         case MVT::v16i16:
16101         case MVT::v16i32:
16102         case MVT::v8i64:
16103           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16104         }
16105       }
16106     }
16107   }
16108
16109   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16110   if (!Subtarget->is64Bit() &&
16111       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16112       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16113       Amt.getOpcode() == ISD::BITCAST &&
16114       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16115     Amt = Amt.getOperand(0);
16116     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16117                      VT.getVectorNumElements();
16118     std::vector<SDValue> Vals(Ratio);
16119     for (unsigned i = 0; i != Ratio; ++i)
16120       Vals[i] = Amt.getOperand(i);
16121     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16122       for (unsigned j = 0; j != Ratio; ++j)
16123         if (Vals[j] != Amt.getOperand(i + j))
16124           return SDValue();
16125     }
16126     switch (Op.getOpcode()) {
16127     default:
16128       llvm_unreachable("Unknown shift opcode!");
16129     case ISD::SHL:
16130       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16131     case ISD::SRL:
16132       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16133     case ISD::SRA:
16134       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16135     }
16136   }
16137
16138   return SDValue();
16139 }
16140
16141 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16142                           SelectionDAG &DAG) {
16143   MVT VT = Op.getSimpleValueType();
16144   SDLoc dl(Op);
16145   SDValue R = Op.getOperand(0);
16146   SDValue Amt = Op.getOperand(1);
16147   SDValue V;
16148
16149   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16150   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16151
16152   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16153   if (V.getNode())
16154     return V;
16155
16156   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16157   if (V.getNode())
16158       return V;
16159
16160   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16161     return Op;
16162   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16163   if (Subtarget->hasInt256()) {
16164     if (Op.getOpcode() == ISD::SRL &&
16165         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16166          VT == MVT::v4i64 || VT == MVT::v8i32))
16167       return Op;
16168     if (Op.getOpcode() == ISD::SHL &&
16169         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16170          VT == MVT::v4i64 || VT == MVT::v8i32))
16171       return Op;
16172     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16173       return Op;
16174   }
16175
16176   // If possible, lower this packed shift into a vector multiply instead of
16177   // expanding it into a sequence of scalar shifts.
16178   // Do this only if the vector shift count is a constant build_vector.
16179   if (Op.getOpcode() == ISD::SHL && 
16180       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16181        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16182       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16183     SmallVector<SDValue, 8> Elts;
16184     EVT SVT = VT.getScalarType();
16185     unsigned SVTBits = SVT.getSizeInBits();
16186     const APInt &One = APInt(SVTBits, 1);
16187     unsigned NumElems = VT.getVectorNumElements();
16188
16189     for (unsigned i=0; i !=NumElems; ++i) {
16190       SDValue Op = Amt->getOperand(i);
16191       if (Op->getOpcode() == ISD::UNDEF) {
16192         Elts.push_back(Op);
16193         continue;
16194       }
16195
16196       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16197       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16198       uint64_t ShAmt = C.getZExtValue();
16199       if (ShAmt >= SVTBits) {
16200         Elts.push_back(DAG.getUNDEF(SVT));
16201         continue;
16202       }
16203       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16204     }
16205     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16206     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16207   }
16208
16209   // Lower SHL with variable shift amount.
16210   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16211     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16212
16213     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16214     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16215     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16216     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16217   }
16218
16219   // If possible, lower this shift as a sequence of two shifts by
16220   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16221   // Example:
16222   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16223   //
16224   // Could be rewritten as:
16225   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16226   //
16227   // The advantage is that the two shifts from the example would be
16228   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16229   // the vector shift into four scalar shifts plus four pairs of vector
16230   // insert/extract.
16231   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16232       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16233     unsigned TargetOpcode = X86ISD::MOVSS;
16234     bool CanBeSimplified;
16235     // The splat value for the first packed shift (the 'X' from the example).
16236     SDValue Amt1 = Amt->getOperand(0);
16237     // The splat value for the second packed shift (the 'Y' from the example).
16238     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16239                                         Amt->getOperand(2);
16240
16241     // See if it is possible to replace this node with a sequence of
16242     // two shifts followed by a MOVSS/MOVSD
16243     if (VT == MVT::v4i32) {
16244       // Check if it is legal to use a MOVSS.
16245       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16246                         Amt2 == Amt->getOperand(3);
16247       if (!CanBeSimplified) {
16248         // Otherwise, check if we can still simplify this node using a MOVSD.
16249         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16250                           Amt->getOperand(2) == Amt->getOperand(3);
16251         TargetOpcode = X86ISD::MOVSD;
16252         Amt2 = Amt->getOperand(2);
16253       }
16254     } else {
16255       // Do similar checks for the case where the machine value type
16256       // is MVT::v8i16.
16257       CanBeSimplified = Amt1 == Amt->getOperand(1);
16258       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16259         CanBeSimplified = Amt2 == Amt->getOperand(i);
16260
16261       if (!CanBeSimplified) {
16262         TargetOpcode = X86ISD::MOVSD;
16263         CanBeSimplified = true;
16264         Amt2 = Amt->getOperand(4);
16265         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16266           CanBeSimplified = Amt1 == Amt->getOperand(i);
16267         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16268           CanBeSimplified = Amt2 == Amt->getOperand(j);
16269       }
16270     }
16271     
16272     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16273         isa<ConstantSDNode>(Amt2)) {
16274       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16275       EVT CastVT = MVT::v4i32;
16276       SDValue Splat1 = 
16277         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16278       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16279       SDValue Splat2 = 
16280         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16281       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16282       if (TargetOpcode == X86ISD::MOVSD)
16283         CastVT = MVT::v2i64;
16284       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16285       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16286       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16287                                             BitCast1, DAG);
16288       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16289     }
16290   }
16291
16292   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16293     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16294
16295     // a = a << 5;
16296     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16297     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16298
16299     // Turn 'a' into a mask suitable for VSELECT
16300     SDValue VSelM = DAG.getConstant(0x80, VT);
16301     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16302     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16303
16304     SDValue CM1 = DAG.getConstant(0x0f, VT);
16305     SDValue CM2 = DAG.getConstant(0x3f, VT);
16306
16307     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16308     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16309     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16310     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16311     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16312
16313     // a += a
16314     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16315     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16316     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16317
16318     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16319     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16320     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16321     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16322     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16323
16324     // a += a
16325     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16326     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16327     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16328
16329     // return VSELECT(r, r+r, a);
16330     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16331                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16332     return R;
16333   }
16334
16335   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16336   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16337   // solution better.
16338   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16339     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16340     unsigned ExtOpc =
16341         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16342     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16343     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16344     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16345                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16346     }
16347
16348   // Decompose 256-bit shifts into smaller 128-bit shifts.
16349   if (VT.is256BitVector()) {
16350     unsigned NumElems = VT.getVectorNumElements();
16351     MVT EltVT = VT.getVectorElementType();
16352     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16353
16354     // Extract the two vectors
16355     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16356     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16357
16358     // Recreate the shift amount vectors
16359     SDValue Amt1, Amt2;
16360     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16361       // Constant shift amount
16362       SmallVector<SDValue, 4> Amt1Csts;
16363       SmallVector<SDValue, 4> Amt2Csts;
16364       for (unsigned i = 0; i != NumElems/2; ++i)
16365         Amt1Csts.push_back(Amt->getOperand(i));
16366       for (unsigned i = NumElems/2; i != NumElems; ++i)
16367         Amt2Csts.push_back(Amt->getOperand(i));
16368
16369       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16370       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16371     } else {
16372       // Variable shift amount
16373       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16374       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16375     }
16376
16377     // Issue new vector shifts for the smaller types
16378     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16379     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16380
16381     // Concatenate the result back
16382     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16383   }
16384
16385   return SDValue();
16386 }
16387
16388 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16389   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16390   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16391   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16392   // has only one use.
16393   SDNode *N = Op.getNode();
16394   SDValue LHS = N->getOperand(0);
16395   SDValue RHS = N->getOperand(1);
16396   unsigned BaseOp = 0;
16397   unsigned Cond = 0;
16398   SDLoc DL(Op);
16399   switch (Op.getOpcode()) {
16400   default: llvm_unreachable("Unknown ovf instruction!");
16401   case ISD::SADDO:
16402     // A subtract of one will be selected as a INC. Note that INC doesn't
16403     // set CF, so we can't do this for UADDO.
16404     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16405       if (C->isOne()) {
16406         BaseOp = X86ISD::INC;
16407         Cond = X86::COND_O;
16408         break;
16409       }
16410     BaseOp = X86ISD::ADD;
16411     Cond = X86::COND_O;
16412     break;
16413   case ISD::UADDO:
16414     BaseOp = X86ISD::ADD;
16415     Cond = X86::COND_B;
16416     break;
16417   case ISD::SSUBO:
16418     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16419     // set CF, so we can't do this for USUBO.
16420     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16421       if (C->isOne()) {
16422         BaseOp = X86ISD::DEC;
16423         Cond = X86::COND_O;
16424         break;
16425       }
16426     BaseOp = X86ISD::SUB;
16427     Cond = X86::COND_O;
16428     break;
16429   case ISD::USUBO:
16430     BaseOp = X86ISD::SUB;
16431     Cond = X86::COND_B;
16432     break;
16433   case ISD::SMULO:
16434     BaseOp = X86ISD::SMUL;
16435     Cond = X86::COND_O;
16436     break;
16437   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16438     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16439                                  MVT::i32);
16440     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16441
16442     SDValue SetCC =
16443       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16444                   DAG.getConstant(X86::COND_O, MVT::i32),
16445                   SDValue(Sum.getNode(), 2));
16446
16447     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16448   }
16449   }
16450
16451   // Also sets EFLAGS.
16452   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16453   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16454
16455   SDValue SetCC =
16456     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16457                 DAG.getConstant(Cond, MVT::i32),
16458                 SDValue(Sum.getNode(), 1));
16459
16460   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16461 }
16462
16463 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16464                                                   SelectionDAG &DAG) const {
16465   SDLoc dl(Op);
16466   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16467   MVT VT = Op.getSimpleValueType();
16468
16469   if (!Subtarget->hasSSE2() || !VT.isVector())
16470     return SDValue();
16471
16472   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16473                       ExtraVT.getScalarType().getSizeInBits();
16474
16475   switch (VT.SimpleTy) {
16476     default: return SDValue();
16477     case MVT::v8i32:
16478     case MVT::v16i16:
16479       if (!Subtarget->hasFp256())
16480         return SDValue();
16481       if (!Subtarget->hasInt256()) {
16482         // needs to be split
16483         unsigned NumElems = VT.getVectorNumElements();
16484
16485         // Extract the LHS vectors
16486         SDValue LHS = Op.getOperand(0);
16487         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16488         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16489
16490         MVT EltVT = VT.getVectorElementType();
16491         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16492
16493         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16494         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16495         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16496                                    ExtraNumElems/2);
16497         SDValue Extra = DAG.getValueType(ExtraVT);
16498
16499         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16500         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16501
16502         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16503       }
16504       // fall through
16505     case MVT::v4i32:
16506     case MVT::v8i16: {
16507       SDValue Op0 = Op.getOperand(0);
16508       SDValue Op00 = Op0.getOperand(0);
16509       SDValue Tmp1;
16510       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16511       if (Op0.getOpcode() == ISD::BITCAST &&
16512           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16513         // (sext (vzext x)) -> (vsext x)
16514         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16515         if (Tmp1.getNode()) {
16516           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16517           // This folding is only valid when the in-reg type is a vector of i8,
16518           // i16, or i32.
16519           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16520               ExtraEltVT == MVT::i32) {
16521             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16522             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16523                    "This optimization is invalid without a VZEXT.");
16524             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16525           }
16526           Op0 = Tmp1;
16527         }
16528       }
16529
16530       // If the above didn't work, then just use Shift-Left + Shift-Right.
16531       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16532                                         DAG);
16533       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16534                                         DAG);
16535     }
16536   }
16537 }
16538
16539 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16540                                  SelectionDAG &DAG) {
16541   SDLoc dl(Op);
16542   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16543     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16544   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16545     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16546
16547   // The only fence that needs an instruction is a sequentially-consistent
16548   // cross-thread fence.
16549   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16550     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16551     // no-sse2). There isn't any reason to disable it if the target processor
16552     // supports it.
16553     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16554       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16555
16556     SDValue Chain = Op.getOperand(0);
16557     SDValue Zero = DAG.getConstant(0, MVT::i32);
16558     SDValue Ops[] = {
16559       DAG.getRegister(X86::ESP, MVT::i32), // Base
16560       DAG.getTargetConstant(1, MVT::i8),   // Scale
16561       DAG.getRegister(0, MVT::i32),        // Index
16562       DAG.getTargetConstant(0, MVT::i32),  // Disp
16563       DAG.getRegister(0, MVT::i32),        // Segment.
16564       Zero,
16565       Chain
16566     };
16567     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16568     return SDValue(Res, 0);
16569   }
16570
16571   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16572   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16573 }
16574
16575 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16576                              SelectionDAG &DAG) {
16577   MVT T = Op.getSimpleValueType();
16578   SDLoc DL(Op);
16579   unsigned Reg = 0;
16580   unsigned size = 0;
16581   switch(T.SimpleTy) {
16582   default: llvm_unreachable("Invalid value type!");
16583   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16584   case MVT::i16: Reg = X86::AX;  size = 2; break;
16585   case MVT::i32: Reg = X86::EAX; size = 4; break;
16586   case MVT::i64:
16587     assert(Subtarget->is64Bit() && "Node not type legal!");
16588     Reg = X86::RAX; size = 8;
16589     break;
16590   }
16591   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16592                                   Op.getOperand(2), SDValue());
16593   SDValue Ops[] = { cpIn.getValue(0),
16594                     Op.getOperand(1),
16595                     Op.getOperand(3),
16596                     DAG.getTargetConstant(size, MVT::i8),
16597                     cpIn.getValue(1) };
16598   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16599   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16600   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16601                                            Ops, T, MMO);
16602
16603   SDValue cpOut =
16604     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16605   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16606                                       MVT::i32, cpOut.getValue(2));
16607   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16608                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16609
16610   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16611   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16612   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16613   return SDValue();
16614 }
16615
16616 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16617                             SelectionDAG &DAG) {
16618   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16619   MVT DstVT = Op.getSimpleValueType();
16620
16621   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16622     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16623     if (DstVT != MVT::f64)
16624       // This conversion needs to be expanded.
16625       return SDValue();
16626
16627     SDValue InVec = Op->getOperand(0);
16628     SDLoc dl(Op);
16629     unsigned NumElts = SrcVT.getVectorNumElements();
16630     EVT SVT = SrcVT.getVectorElementType();
16631
16632     // Widen the vector in input in the case of MVT::v2i32.
16633     // Example: from MVT::v2i32 to MVT::v4i32.
16634     SmallVector<SDValue, 16> Elts;
16635     for (unsigned i = 0, e = NumElts; i != e; ++i)
16636       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16637                                  DAG.getIntPtrConstant(i)));
16638
16639     // Explicitly mark the extra elements as Undef.
16640     SDValue Undef = DAG.getUNDEF(SVT);
16641     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16642       Elts.push_back(Undef);
16643
16644     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16645     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16646     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16647     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16648                        DAG.getIntPtrConstant(0));
16649   }
16650
16651   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16652          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16653   assert((DstVT == MVT::i64 ||
16654           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16655          "Unexpected custom BITCAST");
16656   // i64 <=> MMX conversions are Legal.
16657   if (SrcVT==MVT::i64 && DstVT.isVector())
16658     return Op;
16659   if (DstVT==MVT::i64 && SrcVT.isVector())
16660     return Op;
16661   // MMX <=> MMX conversions are Legal.
16662   if (SrcVT.isVector() && DstVT.isVector())
16663     return Op;
16664   // All other conversions need to be expanded.
16665   return SDValue();
16666 }
16667
16668 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16669   SDNode *Node = Op.getNode();
16670   SDLoc dl(Node);
16671   EVT T = Node->getValueType(0);
16672   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16673                               DAG.getConstant(0, T), Node->getOperand(2));
16674   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16675                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16676                        Node->getOperand(0),
16677                        Node->getOperand(1), negOp,
16678                        cast<AtomicSDNode>(Node)->getMemOperand(),
16679                        cast<AtomicSDNode>(Node)->getOrdering(),
16680                        cast<AtomicSDNode>(Node)->getSynchScope());
16681 }
16682
16683 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16684   SDNode *Node = Op.getNode();
16685   SDLoc dl(Node);
16686   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16687
16688   // Convert seq_cst store -> xchg
16689   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16690   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16691   //        (The only way to get a 16-byte store is cmpxchg16b)
16692   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16693   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16694       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16695     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16696                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16697                                  Node->getOperand(0),
16698                                  Node->getOperand(1), Node->getOperand(2),
16699                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16700                                  cast<AtomicSDNode>(Node)->getOrdering(),
16701                                  cast<AtomicSDNode>(Node)->getSynchScope());
16702     return Swap.getValue(1);
16703   }
16704   // Other atomic stores have a simple pattern.
16705   return Op;
16706 }
16707
16708 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16709   EVT VT = Op.getNode()->getSimpleValueType(0);
16710
16711   // Let legalize expand this if it isn't a legal type yet.
16712   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16713     return SDValue();
16714
16715   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16716
16717   unsigned Opc;
16718   bool ExtraOp = false;
16719   switch (Op.getOpcode()) {
16720   default: llvm_unreachable("Invalid code");
16721   case ISD::ADDC: Opc = X86ISD::ADD; break;
16722   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16723   case ISD::SUBC: Opc = X86ISD::SUB; break;
16724   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16725   }
16726
16727   if (!ExtraOp)
16728     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16729                        Op.getOperand(1));
16730   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16731                      Op.getOperand(1), Op.getOperand(2));
16732 }
16733
16734 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16735                             SelectionDAG &DAG) {
16736   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16737
16738   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16739   // which returns the values as { float, float } (in XMM0) or
16740   // { double, double } (which is returned in XMM0, XMM1).
16741   SDLoc dl(Op);
16742   SDValue Arg = Op.getOperand(0);
16743   EVT ArgVT = Arg.getValueType();
16744   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16745
16746   TargetLowering::ArgListTy Args;
16747   TargetLowering::ArgListEntry Entry;
16748
16749   Entry.Node = Arg;
16750   Entry.Ty = ArgTy;
16751   Entry.isSExt = false;
16752   Entry.isZExt = false;
16753   Args.push_back(Entry);
16754
16755   bool isF64 = ArgVT == MVT::f64;
16756   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16757   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16758   // the results are returned via SRet in memory.
16759   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16761   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16762
16763   Type *RetTy = isF64
16764     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16765     : (Type*)VectorType::get(ArgTy, 4);
16766
16767   TargetLowering::CallLoweringInfo CLI(DAG);
16768   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16769     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16770
16771   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16772
16773   if (isF64)
16774     // Returned in xmm0 and xmm1.
16775     return CallResult.first;
16776
16777   // Returned in bits 0:31 and 32:64 xmm0.
16778   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16779                                CallResult.first, DAG.getIntPtrConstant(0));
16780   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16781                                CallResult.first, DAG.getIntPtrConstant(1));
16782   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16783   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16784 }
16785
16786 /// LowerOperation - Provide custom lowering hooks for some operations.
16787 ///
16788 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16789   switch (Op.getOpcode()) {
16790   default: llvm_unreachable("Should not custom lower this!");
16791   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16792   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16793   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16794     return LowerCMP_SWAP(Op, Subtarget, DAG);
16795   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16796   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16797   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16798   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16799   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16800   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16801   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16802   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16803   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16804   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16805   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16806   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16807   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16808   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16809   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16810   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16811   case ISD::SHL_PARTS:
16812   case ISD::SRA_PARTS:
16813   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16814   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16815   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16816   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16817   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16818   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16819   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16820   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16821   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16822   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16823   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16824   case ISD::FABS:               return LowerFABS(Op, DAG);
16825   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16826   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16827   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16828   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16829   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16830   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16831   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16832   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16833   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16834   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16835   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16836   case ISD::INTRINSIC_VOID:
16837   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16838   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16839   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16840   case ISD::FRAME_TO_ARGS_OFFSET:
16841                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16842   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16843   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16844   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16845   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16846   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16847   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16848   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16849   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16850   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16851   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16852   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16853   case ISD::UMUL_LOHI:
16854   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16855   case ISD::SRA:
16856   case ISD::SRL:
16857   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16858   case ISD::SADDO:
16859   case ISD::UADDO:
16860   case ISD::SSUBO:
16861   case ISD::USUBO:
16862   case ISD::SMULO:
16863   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16864   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16865   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16866   case ISD::ADDC:
16867   case ISD::ADDE:
16868   case ISD::SUBC:
16869   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16870   case ISD::ADD:                return LowerADD(Op, DAG);
16871   case ISD::SUB:                return LowerSUB(Op, DAG);
16872   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16873   }
16874 }
16875
16876 static void ReplaceATOMIC_LOAD(SDNode *Node,
16877                                SmallVectorImpl<SDValue> &Results,
16878                                SelectionDAG &DAG) {
16879   SDLoc dl(Node);
16880   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16881
16882   // Convert wide load -> cmpxchg8b/cmpxchg16b
16883   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16884   //        (The only way to get a 16-byte load is cmpxchg16b)
16885   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16886   SDValue Zero = DAG.getConstant(0, VT);
16887   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16888   SDValue Swap =
16889       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16890                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16891                            cast<AtomicSDNode>(Node)->getMemOperand(),
16892                            cast<AtomicSDNode>(Node)->getOrdering(),
16893                            cast<AtomicSDNode>(Node)->getOrdering(),
16894                            cast<AtomicSDNode>(Node)->getSynchScope());
16895   Results.push_back(Swap.getValue(0));
16896   Results.push_back(Swap.getValue(2));
16897 }
16898
16899 /// ReplaceNodeResults - Replace a node with an illegal result type
16900 /// with a new node built out of custom code.
16901 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16902                                            SmallVectorImpl<SDValue>&Results,
16903                                            SelectionDAG &DAG) const {
16904   SDLoc dl(N);
16905   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16906   switch (N->getOpcode()) {
16907   default:
16908     llvm_unreachable("Do not know how to custom type legalize this operation!");
16909   case ISD::SIGN_EXTEND_INREG:
16910   case ISD::ADDC:
16911   case ISD::ADDE:
16912   case ISD::SUBC:
16913   case ISD::SUBE:
16914     // We don't want to expand or promote these.
16915     return;
16916   case ISD::SDIV:
16917   case ISD::UDIV:
16918   case ISD::SREM:
16919   case ISD::UREM:
16920   case ISD::SDIVREM:
16921   case ISD::UDIVREM: {
16922     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16923     Results.push_back(V);
16924     return;
16925   }
16926   case ISD::FP_TO_SINT:
16927   case ISD::FP_TO_UINT: {
16928     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16929
16930     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16931       return;
16932
16933     std::pair<SDValue,SDValue> Vals =
16934         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16935     SDValue FIST = Vals.first, StackSlot = Vals.second;
16936     if (FIST.getNode()) {
16937       EVT VT = N->getValueType(0);
16938       // Return a load from the stack slot.
16939       if (StackSlot.getNode())
16940         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16941                                       MachinePointerInfo(),
16942                                       false, false, false, 0));
16943       else
16944         Results.push_back(FIST);
16945     }
16946     return;
16947   }
16948   case ISD::UINT_TO_FP: {
16949     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16950     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16951         N->getValueType(0) != MVT::v2f32)
16952       return;
16953     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16954                                  N->getOperand(0));
16955     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16956                                      MVT::f64);
16957     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16958     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16959                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16960     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16961     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16962     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16963     return;
16964   }
16965   case ISD::FP_ROUND: {
16966     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16967         return;
16968     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16969     Results.push_back(V);
16970     return;
16971   }
16972   case ISD::INTRINSIC_W_CHAIN: {
16973     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16974     switch (IntNo) {
16975     default : llvm_unreachable("Do not know how to custom type "
16976                                "legalize this intrinsic operation!");
16977     case Intrinsic::x86_rdtsc:
16978       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16979                                      Results);
16980     case Intrinsic::x86_rdtscp:
16981       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16982                                      Results);
16983     case Intrinsic::x86_rdpmc:
16984       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16985     }
16986   }
16987   case ISD::READCYCLECOUNTER: {
16988     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16989                                    Results);
16990   }
16991   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16992     EVT T = N->getValueType(0);
16993     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16994     bool Regs64bit = T == MVT::i128;
16995     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16996     SDValue cpInL, cpInH;
16997     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16998                         DAG.getConstant(0, HalfT));
16999     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17000                         DAG.getConstant(1, HalfT));
17001     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17002                              Regs64bit ? X86::RAX : X86::EAX,
17003                              cpInL, SDValue());
17004     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17005                              Regs64bit ? X86::RDX : X86::EDX,
17006                              cpInH, cpInL.getValue(1));
17007     SDValue swapInL, swapInH;
17008     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17009                           DAG.getConstant(0, HalfT));
17010     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17011                           DAG.getConstant(1, HalfT));
17012     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17013                                Regs64bit ? X86::RBX : X86::EBX,
17014                                swapInL, cpInH.getValue(1));
17015     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17016                                Regs64bit ? X86::RCX : X86::ECX,
17017                                swapInH, swapInL.getValue(1));
17018     SDValue Ops[] = { swapInH.getValue(0),
17019                       N->getOperand(1),
17020                       swapInH.getValue(1) };
17021     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17022     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17023     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17024                                   X86ISD::LCMPXCHG8_DAG;
17025     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17026     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17027                                         Regs64bit ? X86::RAX : X86::EAX,
17028                                         HalfT, Result.getValue(1));
17029     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17030                                         Regs64bit ? X86::RDX : X86::EDX,
17031                                         HalfT, cpOutL.getValue(2));
17032     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17033
17034     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17035                                         MVT::i32, cpOutH.getValue(2));
17036     SDValue Success =
17037         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17038                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17039     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17040
17041     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17042     Results.push_back(Success);
17043     Results.push_back(EFLAGS.getValue(1));
17044     return;
17045   }
17046   case ISD::ATOMIC_SWAP:
17047   case ISD::ATOMIC_LOAD_ADD:
17048   case ISD::ATOMIC_LOAD_SUB:
17049   case ISD::ATOMIC_LOAD_AND:
17050   case ISD::ATOMIC_LOAD_OR:
17051   case ISD::ATOMIC_LOAD_XOR:
17052   case ISD::ATOMIC_LOAD_NAND:
17053   case ISD::ATOMIC_LOAD_MIN:
17054   case ISD::ATOMIC_LOAD_MAX:
17055   case ISD::ATOMIC_LOAD_UMIN:
17056   case ISD::ATOMIC_LOAD_UMAX:
17057     // Delegate to generic TypeLegalization. Situations we can really handle
17058     // should have already been dealt with by X86AtomicExpandPass.cpp.
17059     break;
17060   case ISD::ATOMIC_LOAD: {
17061     ReplaceATOMIC_LOAD(N, Results, DAG);
17062     return;
17063   }
17064   case ISD::BITCAST: {
17065     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17066     EVT DstVT = N->getValueType(0);
17067     EVT SrcVT = N->getOperand(0)->getValueType(0);
17068
17069     if (SrcVT != MVT::f64 ||
17070         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17071       return;
17072
17073     unsigned NumElts = DstVT.getVectorNumElements();
17074     EVT SVT = DstVT.getVectorElementType();
17075     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17076     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17077                                    MVT::v2f64, N->getOperand(0));
17078     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17079
17080     if (ExperimentalVectorWideningLegalization) {
17081       // If we are legalizing vectors by widening, we already have the desired
17082       // legal vector type, just return it.
17083       Results.push_back(ToVecInt);
17084       return;
17085     }
17086
17087     SmallVector<SDValue, 8> Elts;
17088     for (unsigned i = 0, e = NumElts; i != e; ++i)
17089       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17090                                    ToVecInt, DAG.getIntPtrConstant(i)));
17091
17092     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17093   }
17094   }
17095 }
17096
17097 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17098   switch (Opcode) {
17099   default: return nullptr;
17100   case X86ISD::BSF:                return "X86ISD::BSF";
17101   case X86ISD::BSR:                return "X86ISD::BSR";
17102   case X86ISD::SHLD:               return "X86ISD::SHLD";
17103   case X86ISD::SHRD:               return "X86ISD::SHRD";
17104   case X86ISD::FAND:               return "X86ISD::FAND";
17105   case X86ISD::FANDN:              return "X86ISD::FANDN";
17106   case X86ISD::FOR:                return "X86ISD::FOR";
17107   case X86ISD::FXOR:               return "X86ISD::FXOR";
17108   case X86ISD::FSRL:               return "X86ISD::FSRL";
17109   case X86ISD::FILD:               return "X86ISD::FILD";
17110   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17111   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17112   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17113   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17114   case X86ISD::FLD:                return "X86ISD::FLD";
17115   case X86ISD::FST:                return "X86ISD::FST";
17116   case X86ISD::CALL:               return "X86ISD::CALL";
17117   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17118   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17119   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17120   case X86ISD::BT:                 return "X86ISD::BT";
17121   case X86ISD::CMP:                return "X86ISD::CMP";
17122   case X86ISD::COMI:               return "X86ISD::COMI";
17123   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17124   case X86ISD::CMPM:               return "X86ISD::CMPM";
17125   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17126   case X86ISD::SETCC:              return "X86ISD::SETCC";
17127   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17128   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17129   case X86ISD::CMOV:               return "X86ISD::CMOV";
17130   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17131   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17132   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17133   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17134   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17135   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17136   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17137   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17138   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17139   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17140   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17141   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17142   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17143   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17144   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17145   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17146   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17147   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17148   case X86ISD::HADD:               return "X86ISD::HADD";
17149   case X86ISD::HSUB:               return "X86ISD::HSUB";
17150   case X86ISD::FHADD:              return "X86ISD::FHADD";
17151   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17152   case X86ISD::UMAX:               return "X86ISD::UMAX";
17153   case X86ISD::UMIN:               return "X86ISD::UMIN";
17154   case X86ISD::SMAX:               return "X86ISD::SMAX";
17155   case X86ISD::SMIN:               return "X86ISD::SMIN";
17156   case X86ISD::FMAX:               return "X86ISD::FMAX";
17157   case X86ISD::FMIN:               return "X86ISD::FMIN";
17158   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17159   case X86ISD::FMINC:              return "X86ISD::FMINC";
17160   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17161   case X86ISD::FRCP:               return "X86ISD::FRCP";
17162   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17163   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17164   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17165   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17166   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17167   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17168   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17169   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17170   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17171   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17172   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17173   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17174   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17175   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17176   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17177   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17178   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17179   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17180   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17181   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17182   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17183   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17184   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17185   case X86ISD::VSHL:               return "X86ISD::VSHL";
17186   case X86ISD::VSRL:               return "X86ISD::VSRL";
17187   case X86ISD::VSRA:               return "X86ISD::VSRA";
17188   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17189   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17190   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17191   case X86ISD::CMPP:               return "X86ISD::CMPP";
17192   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17193   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17194   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17195   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17196   case X86ISD::ADD:                return "X86ISD::ADD";
17197   case X86ISD::SUB:                return "X86ISD::SUB";
17198   case X86ISD::ADC:                return "X86ISD::ADC";
17199   case X86ISD::SBB:                return "X86ISD::SBB";
17200   case X86ISD::SMUL:               return "X86ISD::SMUL";
17201   case X86ISD::UMUL:               return "X86ISD::UMUL";
17202   case X86ISD::INC:                return "X86ISD::INC";
17203   case X86ISD::DEC:                return "X86ISD::DEC";
17204   case X86ISD::OR:                 return "X86ISD::OR";
17205   case X86ISD::XOR:                return "X86ISD::XOR";
17206   case X86ISD::AND:                return "X86ISD::AND";
17207   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17208   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17209   case X86ISD::PTEST:              return "X86ISD::PTEST";
17210   case X86ISD::TESTP:              return "X86ISD::TESTP";
17211   case X86ISD::TESTM:              return "X86ISD::TESTM";
17212   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17213   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17214   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17215   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17216   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17217   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17218   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17219   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17220   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17221   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17222   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17223   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17224   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17225   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17226   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17227   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17228   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17229   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17230   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17231   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17232   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17233   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17234   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17235   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17236   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17237   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17238   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17239   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17240   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17241   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17242   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17243   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17244   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17245   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17246   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17247   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17248   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17249   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17250   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17251   case X86ISD::SAHF:               return "X86ISD::SAHF";
17252   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17253   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17254   case X86ISD::FMADD:              return "X86ISD::FMADD";
17255   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17256   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17257   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17258   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17259   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17260   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17261   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17262   case X86ISD::XTEST:              return "X86ISD::XTEST";
17263   }
17264 }
17265
17266 // isLegalAddressingMode - Return true if the addressing mode represented
17267 // by AM is legal for this target, for a load/store of the specified type.
17268 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17269                                               Type *Ty) const {
17270   // X86 supports extremely general addressing modes.
17271   CodeModel::Model M = getTargetMachine().getCodeModel();
17272   Reloc::Model R = getTargetMachine().getRelocationModel();
17273
17274   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17275   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17276     return false;
17277
17278   if (AM.BaseGV) {
17279     unsigned GVFlags =
17280       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17281
17282     // If a reference to this global requires an extra load, we can't fold it.
17283     if (isGlobalStubReference(GVFlags))
17284       return false;
17285
17286     // If BaseGV requires a register for the PIC base, we cannot also have a
17287     // BaseReg specified.
17288     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17289       return false;
17290
17291     // If lower 4G is not available, then we must use rip-relative addressing.
17292     if ((M != CodeModel::Small || R != Reloc::Static) &&
17293         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17294       return false;
17295   }
17296
17297   switch (AM.Scale) {
17298   case 0:
17299   case 1:
17300   case 2:
17301   case 4:
17302   case 8:
17303     // These scales always work.
17304     break;
17305   case 3:
17306   case 5:
17307   case 9:
17308     // These scales are formed with basereg+scalereg.  Only accept if there is
17309     // no basereg yet.
17310     if (AM.HasBaseReg)
17311       return false;
17312     break;
17313   default:  // Other stuff never works.
17314     return false;
17315   }
17316
17317   return true;
17318 }
17319
17320 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17321   unsigned Bits = Ty->getScalarSizeInBits();
17322
17323   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17324   // particularly cheaper than those without.
17325   if (Bits == 8)
17326     return false;
17327
17328   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17329   // variable shifts just as cheap as scalar ones.
17330   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17331     return false;
17332
17333   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17334   // fully general vector.
17335   return true;
17336 }
17337
17338 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17339   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17340     return false;
17341   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17342   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17343   return NumBits1 > NumBits2;
17344 }
17345
17346 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17347   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17348     return false;
17349
17350   if (!isTypeLegal(EVT::getEVT(Ty1)))
17351     return false;
17352
17353   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17354
17355   // Assuming the caller doesn't have a zeroext or signext return parameter,
17356   // truncation all the way down to i1 is valid.
17357   return true;
17358 }
17359
17360 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17361   return isInt<32>(Imm);
17362 }
17363
17364 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17365   // Can also use sub to handle negated immediates.
17366   return isInt<32>(Imm);
17367 }
17368
17369 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17370   if (!VT1.isInteger() || !VT2.isInteger())
17371     return false;
17372   unsigned NumBits1 = VT1.getSizeInBits();
17373   unsigned NumBits2 = VT2.getSizeInBits();
17374   return NumBits1 > NumBits2;
17375 }
17376
17377 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17378   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17379   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17380 }
17381
17382 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17383   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17384   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17385 }
17386
17387 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17388   EVT VT1 = Val.getValueType();
17389   if (isZExtFree(VT1, VT2))
17390     return true;
17391
17392   if (Val.getOpcode() != ISD::LOAD)
17393     return false;
17394
17395   if (!VT1.isSimple() || !VT1.isInteger() ||
17396       !VT2.isSimple() || !VT2.isInteger())
17397     return false;
17398
17399   switch (VT1.getSimpleVT().SimpleTy) {
17400   default: break;
17401   case MVT::i8:
17402   case MVT::i16:
17403   case MVT::i32:
17404     // X86 has 8, 16, and 32-bit zero-extending loads.
17405     return true;
17406   }
17407
17408   return false;
17409 }
17410
17411 bool
17412 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17413   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17414     return false;
17415
17416   VT = VT.getScalarType();
17417
17418   if (!VT.isSimple())
17419     return false;
17420
17421   switch (VT.getSimpleVT().SimpleTy) {
17422   case MVT::f32:
17423   case MVT::f64:
17424     return true;
17425   default:
17426     break;
17427   }
17428
17429   return false;
17430 }
17431
17432 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17433   // i16 instructions are longer (0x66 prefix) and potentially slower.
17434   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17435 }
17436
17437 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17438 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17439 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17440 /// are assumed to be legal.
17441 bool
17442 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17443                                       EVT VT) const {
17444   if (!VT.isSimple())
17445     return false;
17446
17447   MVT SVT = VT.getSimpleVT();
17448
17449   // Very little shuffling can be done for 64-bit vectors right now.
17450   if (VT.getSizeInBits() == 64)
17451     return false;
17452
17453   // If this is a single-input shuffle with no 128 bit lane crossings we can
17454   // lower it into pshufb.
17455   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17456       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17457     bool isLegal = true;
17458     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17459       if (M[I] >= (int)SVT.getVectorNumElements() ||
17460           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17461         isLegal = false;
17462         break;
17463       }
17464     }
17465     if (isLegal)
17466       return true;
17467   }
17468
17469   // FIXME: blends, shifts.
17470   return (SVT.getVectorNumElements() == 2 ||
17471           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17472           isMOVLMask(M, SVT) ||
17473           isMOVHLPSMask(M, SVT) ||
17474           isSHUFPMask(M, SVT) ||
17475           isPSHUFDMask(M, SVT) ||
17476           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17477           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17478           isPALIGNRMask(M, SVT, Subtarget) ||
17479           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17480           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17481           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17482           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17483           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17484 }
17485
17486 bool
17487 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17488                                           EVT VT) const {
17489   if (!VT.isSimple())
17490     return false;
17491
17492   MVT SVT = VT.getSimpleVT();
17493   unsigned NumElts = SVT.getVectorNumElements();
17494   // FIXME: This collection of masks seems suspect.
17495   if (NumElts == 2)
17496     return true;
17497   if (NumElts == 4 && SVT.is128BitVector()) {
17498     return (isMOVLMask(Mask, SVT)  ||
17499             isCommutedMOVLMask(Mask, SVT, true) ||
17500             isSHUFPMask(Mask, SVT) ||
17501             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17502   }
17503   return false;
17504 }
17505
17506 //===----------------------------------------------------------------------===//
17507 //                           X86 Scheduler Hooks
17508 //===----------------------------------------------------------------------===//
17509
17510 /// Utility function to emit xbegin specifying the start of an RTM region.
17511 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17512                                      const TargetInstrInfo *TII) {
17513   DebugLoc DL = MI->getDebugLoc();
17514
17515   const BasicBlock *BB = MBB->getBasicBlock();
17516   MachineFunction::iterator I = MBB;
17517   ++I;
17518
17519   // For the v = xbegin(), we generate
17520   //
17521   // thisMBB:
17522   //  xbegin sinkMBB
17523   //
17524   // mainMBB:
17525   //  eax = -1
17526   //
17527   // sinkMBB:
17528   //  v = eax
17529
17530   MachineBasicBlock *thisMBB = MBB;
17531   MachineFunction *MF = MBB->getParent();
17532   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17533   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17534   MF->insert(I, mainMBB);
17535   MF->insert(I, sinkMBB);
17536
17537   // Transfer the remainder of BB and its successor edges to sinkMBB.
17538   sinkMBB->splice(sinkMBB->begin(), MBB,
17539                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17540   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17541
17542   // thisMBB:
17543   //  xbegin sinkMBB
17544   //  # fallthrough to mainMBB
17545   //  # abortion to sinkMBB
17546   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17547   thisMBB->addSuccessor(mainMBB);
17548   thisMBB->addSuccessor(sinkMBB);
17549
17550   // mainMBB:
17551   //  EAX = -1
17552   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17553   mainMBB->addSuccessor(sinkMBB);
17554
17555   // sinkMBB:
17556   // EAX is live into the sinkMBB
17557   sinkMBB->addLiveIn(X86::EAX);
17558   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17559           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17560     .addReg(X86::EAX);
17561
17562   MI->eraseFromParent();
17563   return sinkMBB;
17564 }
17565
17566 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17567 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17568 // in the .td file.
17569 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17570                                        const TargetInstrInfo *TII) {
17571   unsigned Opc;
17572   switch (MI->getOpcode()) {
17573   default: llvm_unreachable("illegal opcode!");
17574   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17575   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17576   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17577   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17578   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17579   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17580   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17581   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17582   }
17583
17584   DebugLoc dl = MI->getDebugLoc();
17585   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17586
17587   unsigned NumArgs = MI->getNumOperands();
17588   for (unsigned i = 1; i < NumArgs; ++i) {
17589     MachineOperand &Op = MI->getOperand(i);
17590     if (!(Op.isReg() && Op.isImplicit()))
17591       MIB.addOperand(Op);
17592   }
17593   if (MI->hasOneMemOperand())
17594     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17595
17596   BuildMI(*BB, MI, dl,
17597     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17598     .addReg(X86::XMM0);
17599
17600   MI->eraseFromParent();
17601   return BB;
17602 }
17603
17604 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17605 // defs in an instruction pattern
17606 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17607                                        const TargetInstrInfo *TII) {
17608   unsigned Opc;
17609   switch (MI->getOpcode()) {
17610   default: llvm_unreachable("illegal opcode!");
17611   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17612   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17613   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17614   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17615   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17616   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17617   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17618   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17619   }
17620
17621   DebugLoc dl = MI->getDebugLoc();
17622   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17623
17624   unsigned NumArgs = MI->getNumOperands(); // remove the results
17625   for (unsigned i = 1; i < NumArgs; ++i) {
17626     MachineOperand &Op = MI->getOperand(i);
17627     if (!(Op.isReg() && Op.isImplicit()))
17628       MIB.addOperand(Op);
17629   }
17630   if (MI->hasOneMemOperand())
17631     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17632
17633   BuildMI(*BB, MI, dl,
17634     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17635     .addReg(X86::ECX);
17636
17637   MI->eraseFromParent();
17638   return BB;
17639 }
17640
17641 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17642                                        const TargetInstrInfo *TII,
17643                                        const X86Subtarget* Subtarget) {
17644   DebugLoc dl = MI->getDebugLoc();
17645
17646   // Address into RAX/EAX, other two args into ECX, EDX.
17647   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17648   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17649   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17650   for (int i = 0; i < X86::AddrNumOperands; ++i)
17651     MIB.addOperand(MI->getOperand(i));
17652
17653   unsigned ValOps = X86::AddrNumOperands;
17654   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17655     .addReg(MI->getOperand(ValOps).getReg());
17656   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17657     .addReg(MI->getOperand(ValOps+1).getReg());
17658
17659   // The instruction doesn't actually take any operands though.
17660   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17661
17662   MI->eraseFromParent(); // The pseudo is gone now.
17663   return BB;
17664 }
17665
17666 MachineBasicBlock *
17667 X86TargetLowering::EmitVAARG64WithCustomInserter(
17668                    MachineInstr *MI,
17669                    MachineBasicBlock *MBB) const {
17670   // Emit va_arg instruction on X86-64.
17671
17672   // Operands to this pseudo-instruction:
17673   // 0  ) Output        : destination address (reg)
17674   // 1-5) Input         : va_list address (addr, i64mem)
17675   // 6  ) ArgSize       : Size (in bytes) of vararg type
17676   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17677   // 8  ) Align         : Alignment of type
17678   // 9  ) EFLAGS (implicit-def)
17679
17680   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17681   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17682
17683   unsigned DestReg = MI->getOperand(0).getReg();
17684   MachineOperand &Base = MI->getOperand(1);
17685   MachineOperand &Scale = MI->getOperand(2);
17686   MachineOperand &Index = MI->getOperand(3);
17687   MachineOperand &Disp = MI->getOperand(4);
17688   MachineOperand &Segment = MI->getOperand(5);
17689   unsigned ArgSize = MI->getOperand(6).getImm();
17690   unsigned ArgMode = MI->getOperand(7).getImm();
17691   unsigned Align = MI->getOperand(8).getImm();
17692
17693   // Memory Reference
17694   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17695   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17696   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17697
17698   // Machine Information
17699   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17700   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17701   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17702   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17703   DebugLoc DL = MI->getDebugLoc();
17704
17705   // struct va_list {
17706   //   i32   gp_offset
17707   //   i32   fp_offset
17708   //   i64   overflow_area (address)
17709   //   i64   reg_save_area (address)
17710   // }
17711   // sizeof(va_list) = 24
17712   // alignment(va_list) = 8
17713
17714   unsigned TotalNumIntRegs = 6;
17715   unsigned TotalNumXMMRegs = 8;
17716   bool UseGPOffset = (ArgMode == 1);
17717   bool UseFPOffset = (ArgMode == 2);
17718   unsigned MaxOffset = TotalNumIntRegs * 8 +
17719                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17720
17721   /* Align ArgSize to a multiple of 8 */
17722   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17723   bool NeedsAlign = (Align > 8);
17724
17725   MachineBasicBlock *thisMBB = MBB;
17726   MachineBasicBlock *overflowMBB;
17727   MachineBasicBlock *offsetMBB;
17728   MachineBasicBlock *endMBB;
17729
17730   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17731   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17732   unsigned OffsetReg = 0;
17733
17734   if (!UseGPOffset && !UseFPOffset) {
17735     // If we only pull from the overflow region, we don't create a branch.
17736     // We don't need to alter control flow.
17737     OffsetDestReg = 0; // unused
17738     OverflowDestReg = DestReg;
17739
17740     offsetMBB = nullptr;
17741     overflowMBB = thisMBB;
17742     endMBB = thisMBB;
17743   } else {
17744     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17745     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17746     // If not, pull from overflow_area. (branch to overflowMBB)
17747     //
17748     //       thisMBB
17749     //         |     .
17750     //         |        .
17751     //     offsetMBB   overflowMBB
17752     //         |        .
17753     //         |     .
17754     //        endMBB
17755
17756     // Registers for the PHI in endMBB
17757     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17758     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17759
17760     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17761     MachineFunction *MF = MBB->getParent();
17762     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17763     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17764     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17765
17766     MachineFunction::iterator MBBIter = MBB;
17767     ++MBBIter;
17768
17769     // Insert the new basic blocks
17770     MF->insert(MBBIter, offsetMBB);
17771     MF->insert(MBBIter, overflowMBB);
17772     MF->insert(MBBIter, endMBB);
17773
17774     // Transfer the remainder of MBB and its successor edges to endMBB.
17775     endMBB->splice(endMBB->begin(), thisMBB,
17776                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17777     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17778
17779     // Make offsetMBB and overflowMBB successors of thisMBB
17780     thisMBB->addSuccessor(offsetMBB);
17781     thisMBB->addSuccessor(overflowMBB);
17782
17783     // endMBB is a successor of both offsetMBB and overflowMBB
17784     offsetMBB->addSuccessor(endMBB);
17785     overflowMBB->addSuccessor(endMBB);
17786
17787     // Load the offset value into a register
17788     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17789     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17790       .addOperand(Base)
17791       .addOperand(Scale)
17792       .addOperand(Index)
17793       .addDisp(Disp, UseFPOffset ? 4 : 0)
17794       .addOperand(Segment)
17795       .setMemRefs(MMOBegin, MMOEnd);
17796
17797     // Check if there is enough room left to pull this argument.
17798     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17799       .addReg(OffsetReg)
17800       .addImm(MaxOffset + 8 - ArgSizeA8);
17801
17802     // Branch to "overflowMBB" if offset >= max
17803     // Fall through to "offsetMBB" otherwise
17804     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17805       .addMBB(overflowMBB);
17806   }
17807
17808   // In offsetMBB, emit code to use the reg_save_area.
17809   if (offsetMBB) {
17810     assert(OffsetReg != 0);
17811
17812     // Read the reg_save_area address.
17813     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17814     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17815       .addOperand(Base)
17816       .addOperand(Scale)
17817       .addOperand(Index)
17818       .addDisp(Disp, 16)
17819       .addOperand(Segment)
17820       .setMemRefs(MMOBegin, MMOEnd);
17821
17822     // Zero-extend the offset
17823     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17824       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17825         .addImm(0)
17826         .addReg(OffsetReg)
17827         .addImm(X86::sub_32bit);
17828
17829     // Add the offset to the reg_save_area to get the final address.
17830     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17831       .addReg(OffsetReg64)
17832       .addReg(RegSaveReg);
17833
17834     // Compute the offset for the next argument
17835     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17836     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17837       .addReg(OffsetReg)
17838       .addImm(UseFPOffset ? 16 : 8);
17839
17840     // Store it back into the va_list.
17841     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17842       .addOperand(Base)
17843       .addOperand(Scale)
17844       .addOperand(Index)
17845       .addDisp(Disp, UseFPOffset ? 4 : 0)
17846       .addOperand(Segment)
17847       .addReg(NextOffsetReg)
17848       .setMemRefs(MMOBegin, MMOEnd);
17849
17850     // Jump to endMBB
17851     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17852       .addMBB(endMBB);
17853   }
17854
17855   //
17856   // Emit code to use overflow area
17857   //
17858
17859   // Load the overflow_area address into a register.
17860   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17861   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17862     .addOperand(Base)
17863     .addOperand(Scale)
17864     .addOperand(Index)
17865     .addDisp(Disp, 8)
17866     .addOperand(Segment)
17867     .setMemRefs(MMOBegin, MMOEnd);
17868
17869   // If we need to align it, do so. Otherwise, just copy the address
17870   // to OverflowDestReg.
17871   if (NeedsAlign) {
17872     // Align the overflow address
17873     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17874     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17875
17876     // aligned_addr = (addr + (align-1)) & ~(align-1)
17877     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17878       .addReg(OverflowAddrReg)
17879       .addImm(Align-1);
17880
17881     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17882       .addReg(TmpReg)
17883       .addImm(~(uint64_t)(Align-1));
17884   } else {
17885     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17886       .addReg(OverflowAddrReg);
17887   }
17888
17889   // Compute the next overflow address after this argument.
17890   // (the overflow address should be kept 8-byte aligned)
17891   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17892   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17893     .addReg(OverflowDestReg)
17894     .addImm(ArgSizeA8);
17895
17896   // Store the new overflow address.
17897   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17898     .addOperand(Base)
17899     .addOperand(Scale)
17900     .addOperand(Index)
17901     .addDisp(Disp, 8)
17902     .addOperand(Segment)
17903     .addReg(NextAddrReg)
17904     .setMemRefs(MMOBegin, MMOEnd);
17905
17906   // If we branched, emit the PHI to the front of endMBB.
17907   if (offsetMBB) {
17908     BuildMI(*endMBB, endMBB->begin(), DL,
17909             TII->get(X86::PHI), DestReg)
17910       .addReg(OffsetDestReg).addMBB(offsetMBB)
17911       .addReg(OverflowDestReg).addMBB(overflowMBB);
17912   }
17913
17914   // Erase the pseudo instruction
17915   MI->eraseFromParent();
17916
17917   return endMBB;
17918 }
17919
17920 MachineBasicBlock *
17921 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17922                                                  MachineInstr *MI,
17923                                                  MachineBasicBlock *MBB) const {
17924   // Emit code to save XMM registers to the stack. The ABI says that the
17925   // number of registers to save is given in %al, so it's theoretically
17926   // possible to do an indirect jump trick to avoid saving all of them,
17927   // however this code takes a simpler approach and just executes all
17928   // of the stores if %al is non-zero. It's less code, and it's probably
17929   // easier on the hardware branch predictor, and stores aren't all that
17930   // expensive anyway.
17931
17932   // Create the new basic blocks. One block contains all the XMM stores,
17933   // and one block is the final destination regardless of whether any
17934   // stores were performed.
17935   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17936   MachineFunction *F = MBB->getParent();
17937   MachineFunction::iterator MBBIter = MBB;
17938   ++MBBIter;
17939   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17940   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17941   F->insert(MBBIter, XMMSaveMBB);
17942   F->insert(MBBIter, EndMBB);
17943
17944   // Transfer the remainder of MBB and its successor edges to EndMBB.
17945   EndMBB->splice(EndMBB->begin(), MBB,
17946                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17947   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17948
17949   // The original block will now fall through to the XMM save block.
17950   MBB->addSuccessor(XMMSaveMBB);
17951   // The XMMSaveMBB will fall through to the end block.
17952   XMMSaveMBB->addSuccessor(EndMBB);
17953
17954   // Now add the instructions.
17955   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17956   DebugLoc DL = MI->getDebugLoc();
17957
17958   unsigned CountReg = MI->getOperand(0).getReg();
17959   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17960   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17961
17962   if (!Subtarget->isTargetWin64()) {
17963     // If %al is 0, branch around the XMM save block.
17964     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17965     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17966     MBB->addSuccessor(EndMBB);
17967   }
17968
17969   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17970   // that was just emitted, but clearly shouldn't be "saved".
17971   assert((MI->getNumOperands() <= 3 ||
17972           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17973           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17974          && "Expected last argument to be EFLAGS");
17975   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17976   // In the XMM save block, save all the XMM argument registers.
17977   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17978     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17979     MachineMemOperand *MMO =
17980       F->getMachineMemOperand(
17981           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17982         MachineMemOperand::MOStore,
17983         /*Size=*/16, /*Align=*/16);
17984     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17985       .addFrameIndex(RegSaveFrameIndex)
17986       .addImm(/*Scale=*/1)
17987       .addReg(/*IndexReg=*/0)
17988       .addImm(/*Disp=*/Offset)
17989       .addReg(/*Segment=*/0)
17990       .addReg(MI->getOperand(i).getReg())
17991       .addMemOperand(MMO);
17992   }
17993
17994   MI->eraseFromParent();   // The pseudo instruction is gone now.
17995
17996   return EndMBB;
17997 }
17998
17999 // The EFLAGS operand of SelectItr might be missing a kill marker
18000 // because there were multiple uses of EFLAGS, and ISel didn't know
18001 // which to mark. Figure out whether SelectItr should have had a
18002 // kill marker, and set it if it should. Returns the correct kill
18003 // marker value.
18004 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18005                                      MachineBasicBlock* BB,
18006                                      const TargetRegisterInfo* TRI) {
18007   // Scan forward through BB for a use/def of EFLAGS.
18008   MachineBasicBlock::iterator miI(std::next(SelectItr));
18009   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18010     const MachineInstr& mi = *miI;
18011     if (mi.readsRegister(X86::EFLAGS))
18012       return false;
18013     if (mi.definesRegister(X86::EFLAGS))
18014       break; // Should have kill-flag - update below.
18015   }
18016
18017   // If we hit the end of the block, check whether EFLAGS is live into a
18018   // successor.
18019   if (miI == BB->end()) {
18020     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18021                                           sEnd = BB->succ_end();
18022          sItr != sEnd; ++sItr) {
18023       MachineBasicBlock* succ = *sItr;
18024       if (succ->isLiveIn(X86::EFLAGS))
18025         return false;
18026     }
18027   }
18028
18029   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18030   // out. SelectMI should have a kill flag on EFLAGS.
18031   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18032   return true;
18033 }
18034
18035 MachineBasicBlock *
18036 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18037                                      MachineBasicBlock *BB) const {
18038   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18039   DebugLoc DL = MI->getDebugLoc();
18040
18041   // To "insert" a SELECT_CC instruction, we actually have to insert the
18042   // diamond control-flow pattern.  The incoming instruction knows the
18043   // destination vreg to set, the condition code register to branch on, the
18044   // true/false values to select between, and a branch opcode to use.
18045   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18046   MachineFunction::iterator It = BB;
18047   ++It;
18048
18049   //  thisMBB:
18050   //  ...
18051   //   TrueVal = ...
18052   //   cmpTY ccX, r1, r2
18053   //   bCC copy1MBB
18054   //   fallthrough --> copy0MBB
18055   MachineBasicBlock *thisMBB = BB;
18056   MachineFunction *F = BB->getParent();
18057   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18058   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18059   F->insert(It, copy0MBB);
18060   F->insert(It, sinkMBB);
18061
18062   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18063   // live into the sink and copy blocks.
18064   const TargetRegisterInfo *TRI =
18065       BB->getParent()->getSubtarget().getRegisterInfo();
18066   if (!MI->killsRegister(X86::EFLAGS) &&
18067       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18068     copy0MBB->addLiveIn(X86::EFLAGS);
18069     sinkMBB->addLiveIn(X86::EFLAGS);
18070   }
18071
18072   // Transfer the remainder of BB and its successor edges to sinkMBB.
18073   sinkMBB->splice(sinkMBB->begin(), BB,
18074                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18075   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18076
18077   // Add the true and fallthrough blocks as its successors.
18078   BB->addSuccessor(copy0MBB);
18079   BB->addSuccessor(sinkMBB);
18080
18081   // Create the conditional branch instruction.
18082   unsigned Opc =
18083     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18084   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18085
18086   //  copy0MBB:
18087   //   %FalseValue = ...
18088   //   # fallthrough to sinkMBB
18089   copy0MBB->addSuccessor(sinkMBB);
18090
18091   //  sinkMBB:
18092   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18093   //  ...
18094   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18095           TII->get(X86::PHI), MI->getOperand(0).getReg())
18096     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18097     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18098
18099   MI->eraseFromParent();   // The pseudo instruction is gone now.
18100   return sinkMBB;
18101 }
18102
18103 MachineBasicBlock *
18104 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18105                                         bool Is64Bit) const {
18106   MachineFunction *MF = BB->getParent();
18107   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18108   DebugLoc DL = MI->getDebugLoc();
18109   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18110
18111   assert(MF->shouldSplitStack());
18112
18113   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18114   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18115
18116   // BB:
18117   //  ... [Till the alloca]
18118   // If stacklet is not large enough, jump to mallocMBB
18119   //
18120   // bumpMBB:
18121   //  Allocate by subtracting from RSP
18122   //  Jump to continueMBB
18123   //
18124   // mallocMBB:
18125   //  Allocate by call to runtime
18126   //
18127   // continueMBB:
18128   //  ...
18129   //  [rest of original BB]
18130   //
18131
18132   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18133   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18134   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18135
18136   MachineRegisterInfo &MRI = MF->getRegInfo();
18137   const TargetRegisterClass *AddrRegClass =
18138     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18139
18140   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18141     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18142     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18143     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18144     sizeVReg = MI->getOperand(1).getReg(),
18145     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18146
18147   MachineFunction::iterator MBBIter = BB;
18148   ++MBBIter;
18149
18150   MF->insert(MBBIter, bumpMBB);
18151   MF->insert(MBBIter, mallocMBB);
18152   MF->insert(MBBIter, continueMBB);
18153
18154   continueMBB->splice(continueMBB->begin(), BB,
18155                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18156   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18157
18158   // Add code to the main basic block to check if the stack limit has been hit,
18159   // and if so, jump to mallocMBB otherwise to bumpMBB.
18160   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18161   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18162     .addReg(tmpSPVReg).addReg(sizeVReg);
18163   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18164     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18165     .addReg(SPLimitVReg);
18166   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18167
18168   // bumpMBB simply decreases the stack pointer, since we know the current
18169   // stacklet has enough space.
18170   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18171     .addReg(SPLimitVReg);
18172   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18173     .addReg(SPLimitVReg);
18174   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18175
18176   // Calls into a routine in libgcc to allocate more space from the heap.
18177   const uint32_t *RegMask = MF->getTarget()
18178                                 .getSubtargetImpl()
18179                                 ->getRegisterInfo()
18180                                 ->getCallPreservedMask(CallingConv::C);
18181   if (Is64Bit) {
18182     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18183       .addReg(sizeVReg);
18184     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18185       .addExternalSymbol("__morestack_allocate_stack_space")
18186       .addRegMask(RegMask)
18187       .addReg(X86::RDI, RegState::Implicit)
18188       .addReg(X86::RAX, RegState::ImplicitDefine);
18189   } else {
18190     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18191       .addImm(12);
18192     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18193     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18194       .addExternalSymbol("__morestack_allocate_stack_space")
18195       .addRegMask(RegMask)
18196       .addReg(X86::EAX, RegState::ImplicitDefine);
18197   }
18198
18199   if (!Is64Bit)
18200     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18201       .addImm(16);
18202
18203   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18204     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18205   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18206
18207   // Set up the CFG correctly.
18208   BB->addSuccessor(bumpMBB);
18209   BB->addSuccessor(mallocMBB);
18210   mallocMBB->addSuccessor(continueMBB);
18211   bumpMBB->addSuccessor(continueMBB);
18212
18213   // Take care of the PHI nodes.
18214   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18215           MI->getOperand(0).getReg())
18216     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18217     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18218
18219   // Delete the original pseudo instruction.
18220   MI->eraseFromParent();
18221
18222   // And we're done.
18223   return continueMBB;
18224 }
18225
18226 MachineBasicBlock *
18227 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18228                                         MachineBasicBlock *BB) const {
18229   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18230   DebugLoc DL = MI->getDebugLoc();
18231
18232   assert(!Subtarget->isTargetMacho());
18233
18234   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18235   // non-trivial part is impdef of ESP.
18236
18237   if (Subtarget->isTargetWin64()) {
18238     if (Subtarget->isTargetCygMing()) {
18239       // ___chkstk(Mingw64):
18240       // Clobbers R10, R11, RAX and EFLAGS.
18241       // Updates RSP.
18242       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18243         .addExternalSymbol("___chkstk")
18244         .addReg(X86::RAX, RegState::Implicit)
18245         .addReg(X86::RSP, RegState::Implicit)
18246         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18247         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18248         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18249     } else {
18250       // __chkstk(MSVCRT): does not update stack pointer.
18251       // Clobbers R10, R11 and EFLAGS.
18252       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18253         .addExternalSymbol("__chkstk")
18254         .addReg(X86::RAX, RegState::Implicit)
18255         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18256       // RAX has the offset to be subtracted from RSP.
18257       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18258         .addReg(X86::RSP)
18259         .addReg(X86::RAX);
18260     }
18261   } else {
18262     const char *StackProbeSymbol =
18263       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18264
18265     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18266       .addExternalSymbol(StackProbeSymbol)
18267       .addReg(X86::EAX, RegState::Implicit)
18268       .addReg(X86::ESP, RegState::Implicit)
18269       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18270       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18271       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18272   }
18273
18274   MI->eraseFromParent();   // The pseudo instruction is gone now.
18275   return BB;
18276 }
18277
18278 MachineBasicBlock *
18279 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18280                                       MachineBasicBlock *BB) const {
18281   // This is pretty easy.  We're taking the value that we received from
18282   // our load from the relocation, sticking it in either RDI (x86-64)
18283   // or EAX and doing an indirect call.  The return value will then
18284   // be in the normal return register.
18285   MachineFunction *F = BB->getParent();
18286   const X86InstrInfo *TII =
18287       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18288   DebugLoc DL = MI->getDebugLoc();
18289
18290   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18291   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18292
18293   // Get a register mask for the lowered call.
18294   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18295   // proper register mask.
18296   const uint32_t *RegMask = F->getTarget()
18297                                 .getSubtargetImpl()
18298                                 ->getRegisterInfo()
18299                                 ->getCallPreservedMask(CallingConv::C);
18300   if (Subtarget->is64Bit()) {
18301     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18302                                       TII->get(X86::MOV64rm), X86::RDI)
18303     .addReg(X86::RIP)
18304     .addImm(0).addReg(0)
18305     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18306                       MI->getOperand(3).getTargetFlags())
18307     .addReg(0);
18308     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18309     addDirectMem(MIB, X86::RDI);
18310     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18311   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18312     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18313                                       TII->get(X86::MOV32rm), X86::EAX)
18314     .addReg(0)
18315     .addImm(0).addReg(0)
18316     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18317                       MI->getOperand(3).getTargetFlags())
18318     .addReg(0);
18319     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18320     addDirectMem(MIB, X86::EAX);
18321     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18322   } else {
18323     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18324                                       TII->get(X86::MOV32rm), X86::EAX)
18325     .addReg(TII->getGlobalBaseReg(F))
18326     .addImm(0).addReg(0)
18327     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18328                       MI->getOperand(3).getTargetFlags())
18329     .addReg(0);
18330     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18331     addDirectMem(MIB, X86::EAX);
18332     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18333   }
18334
18335   MI->eraseFromParent(); // The pseudo instruction is gone now.
18336   return BB;
18337 }
18338
18339 MachineBasicBlock *
18340 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18341                                     MachineBasicBlock *MBB) const {
18342   DebugLoc DL = MI->getDebugLoc();
18343   MachineFunction *MF = MBB->getParent();
18344   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18345   MachineRegisterInfo &MRI = MF->getRegInfo();
18346
18347   const BasicBlock *BB = MBB->getBasicBlock();
18348   MachineFunction::iterator I = MBB;
18349   ++I;
18350
18351   // Memory Reference
18352   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18353   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18354
18355   unsigned DstReg;
18356   unsigned MemOpndSlot = 0;
18357
18358   unsigned CurOp = 0;
18359
18360   DstReg = MI->getOperand(CurOp++).getReg();
18361   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18362   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18363   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18364   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18365
18366   MemOpndSlot = CurOp;
18367
18368   MVT PVT = getPointerTy();
18369   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18370          "Invalid Pointer Size!");
18371
18372   // For v = setjmp(buf), we generate
18373   //
18374   // thisMBB:
18375   //  buf[LabelOffset] = restoreMBB
18376   //  SjLjSetup restoreMBB
18377   //
18378   // mainMBB:
18379   //  v_main = 0
18380   //
18381   // sinkMBB:
18382   //  v = phi(main, restore)
18383   //
18384   // restoreMBB:
18385   //  v_restore = 1
18386
18387   MachineBasicBlock *thisMBB = MBB;
18388   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18389   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18390   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18391   MF->insert(I, mainMBB);
18392   MF->insert(I, sinkMBB);
18393   MF->push_back(restoreMBB);
18394
18395   MachineInstrBuilder MIB;
18396
18397   // Transfer the remainder of BB and its successor edges to sinkMBB.
18398   sinkMBB->splice(sinkMBB->begin(), MBB,
18399                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18400   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18401
18402   // thisMBB:
18403   unsigned PtrStoreOpc = 0;
18404   unsigned LabelReg = 0;
18405   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18406   Reloc::Model RM = MF->getTarget().getRelocationModel();
18407   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18408                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18409
18410   // Prepare IP either in reg or imm.
18411   if (!UseImmLabel) {
18412     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18413     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18414     LabelReg = MRI.createVirtualRegister(PtrRC);
18415     if (Subtarget->is64Bit()) {
18416       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18417               .addReg(X86::RIP)
18418               .addImm(0)
18419               .addReg(0)
18420               .addMBB(restoreMBB)
18421               .addReg(0);
18422     } else {
18423       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18424       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18425               .addReg(XII->getGlobalBaseReg(MF))
18426               .addImm(0)
18427               .addReg(0)
18428               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18429               .addReg(0);
18430     }
18431   } else
18432     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18433   // Store IP
18434   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18435   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18436     if (i == X86::AddrDisp)
18437       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18438     else
18439       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18440   }
18441   if (!UseImmLabel)
18442     MIB.addReg(LabelReg);
18443   else
18444     MIB.addMBB(restoreMBB);
18445   MIB.setMemRefs(MMOBegin, MMOEnd);
18446   // Setup
18447   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18448           .addMBB(restoreMBB);
18449
18450   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18451       MF->getSubtarget().getRegisterInfo());
18452   MIB.addRegMask(RegInfo->getNoPreservedMask());
18453   thisMBB->addSuccessor(mainMBB);
18454   thisMBB->addSuccessor(restoreMBB);
18455
18456   // mainMBB:
18457   //  EAX = 0
18458   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18459   mainMBB->addSuccessor(sinkMBB);
18460
18461   // sinkMBB:
18462   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18463           TII->get(X86::PHI), DstReg)
18464     .addReg(mainDstReg).addMBB(mainMBB)
18465     .addReg(restoreDstReg).addMBB(restoreMBB);
18466
18467   // restoreMBB:
18468   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18469   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18470   restoreMBB->addSuccessor(sinkMBB);
18471
18472   MI->eraseFromParent();
18473   return sinkMBB;
18474 }
18475
18476 MachineBasicBlock *
18477 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18478                                      MachineBasicBlock *MBB) const {
18479   DebugLoc DL = MI->getDebugLoc();
18480   MachineFunction *MF = MBB->getParent();
18481   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18482   MachineRegisterInfo &MRI = MF->getRegInfo();
18483
18484   // Memory Reference
18485   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18486   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18487
18488   MVT PVT = getPointerTy();
18489   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18490          "Invalid Pointer Size!");
18491
18492   const TargetRegisterClass *RC =
18493     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18494   unsigned Tmp = MRI.createVirtualRegister(RC);
18495   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18496   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18497       MF->getSubtarget().getRegisterInfo());
18498   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18499   unsigned SP = RegInfo->getStackRegister();
18500
18501   MachineInstrBuilder MIB;
18502
18503   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18504   const int64_t SPOffset = 2 * PVT.getStoreSize();
18505
18506   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18507   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18508
18509   // Reload FP
18510   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18511   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18512     MIB.addOperand(MI->getOperand(i));
18513   MIB.setMemRefs(MMOBegin, MMOEnd);
18514   // Reload IP
18515   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18516   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18517     if (i == X86::AddrDisp)
18518       MIB.addDisp(MI->getOperand(i), LabelOffset);
18519     else
18520       MIB.addOperand(MI->getOperand(i));
18521   }
18522   MIB.setMemRefs(MMOBegin, MMOEnd);
18523   // Reload SP
18524   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18525   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18526     if (i == X86::AddrDisp)
18527       MIB.addDisp(MI->getOperand(i), SPOffset);
18528     else
18529       MIB.addOperand(MI->getOperand(i));
18530   }
18531   MIB.setMemRefs(MMOBegin, MMOEnd);
18532   // Jump
18533   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18534
18535   MI->eraseFromParent();
18536   return MBB;
18537 }
18538
18539 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18540 // accumulator loops. Writing back to the accumulator allows the coalescer
18541 // to remove extra copies in the loop.   
18542 MachineBasicBlock *
18543 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18544                                  MachineBasicBlock *MBB) const {
18545   MachineOperand &AddendOp = MI->getOperand(3);
18546
18547   // Bail out early if the addend isn't a register - we can't switch these.
18548   if (!AddendOp.isReg())
18549     return MBB;
18550
18551   MachineFunction &MF = *MBB->getParent();
18552   MachineRegisterInfo &MRI = MF.getRegInfo();
18553
18554   // Check whether the addend is defined by a PHI:
18555   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18556   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18557   if (!AddendDef.isPHI())
18558     return MBB;
18559
18560   // Look for the following pattern:
18561   // loop:
18562   //   %addend = phi [%entry, 0], [%loop, %result]
18563   //   ...
18564   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18565
18566   // Replace with:
18567   //   loop:
18568   //   %addend = phi [%entry, 0], [%loop, %result]
18569   //   ...
18570   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18571
18572   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18573     assert(AddendDef.getOperand(i).isReg());
18574     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18575     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18576     if (&PHISrcInst == MI) {
18577       // Found a matching instruction.
18578       unsigned NewFMAOpc = 0;
18579       switch (MI->getOpcode()) {
18580         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18581         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18582         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18583         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18584         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18585         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18586         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18587         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18588         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18589         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18590         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18591         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18592         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18593         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18594         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18595         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18596         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18597         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18598         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18599         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18600         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18601         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18602         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18603         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18604         default: llvm_unreachable("Unrecognized FMA variant.");
18605       }
18606
18607       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18608       MachineInstrBuilder MIB =
18609         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18610         .addOperand(MI->getOperand(0))
18611         .addOperand(MI->getOperand(3))
18612         .addOperand(MI->getOperand(2))
18613         .addOperand(MI->getOperand(1));
18614       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18615       MI->eraseFromParent();
18616     }
18617   }
18618
18619   return MBB;
18620 }
18621
18622 MachineBasicBlock *
18623 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18624                                                MachineBasicBlock *BB) const {
18625   switch (MI->getOpcode()) {
18626   default: llvm_unreachable("Unexpected instr type to insert");
18627   case X86::TAILJMPd64:
18628   case X86::TAILJMPr64:
18629   case X86::TAILJMPm64:
18630     llvm_unreachable("TAILJMP64 would not be touched here.");
18631   case X86::TCRETURNdi64:
18632   case X86::TCRETURNri64:
18633   case X86::TCRETURNmi64:
18634     return BB;
18635   case X86::WIN_ALLOCA:
18636     return EmitLoweredWinAlloca(MI, BB);
18637   case X86::SEG_ALLOCA_32:
18638     return EmitLoweredSegAlloca(MI, BB, false);
18639   case X86::SEG_ALLOCA_64:
18640     return EmitLoweredSegAlloca(MI, BB, true);
18641   case X86::TLSCall_32:
18642   case X86::TLSCall_64:
18643     return EmitLoweredTLSCall(MI, BB);
18644   case X86::CMOV_GR8:
18645   case X86::CMOV_FR32:
18646   case X86::CMOV_FR64:
18647   case X86::CMOV_V4F32:
18648   case X86::CMOV_V2F64:
18649   case X86::CMOV_V2I64:
18650   case X86::CMOV_V8F32:
18651   case X86::CMOV_V4F64:
18652   case X86::CMOV_V4I64:
18653   case X86::CMOV_V16F32:
18654   case X86::CMOV_V8F64:
18655   case X86::CMOV_V8I64:
18656   case X86::CMOV_GR16:
18657   case X86::CMOV_GR32:
18658   case X86::CMOV_RFP32:
18659   case X86::CMOV_RFP64:
18660   case X86::CMOV_RFP80:
18661     return EmitLoweredSelect(MI, BB);
18662
18663   case X86::FP32_TO_INT16_IN_MEM:
18664   case X86::FP32_TO_INT32_IN_MEM:
18665   case X86::FP32_TO_INT64_IN_MEM:
18666   case X86::FP64_TO_INT16_IN_MEM:
18667   case X86::FP64_TO_INT32_IN_MEM:
18668   case X86::FP64_TO_INT64_IN_MEM:
18669   case X86::FP80_TO_INT16_IN_MEM:
18670   case X86::FP80_TO_INT32_IN_MEM:
18671   case X86::FP80_TO_INT64_IN_MEM: {
18672     MachineFunction *F = BB->getParent();
18673     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18674     DebugLoc DL = MI->getDebugLoc();
18675
18676     // Change the floating point control register to use "round towards zero"
18677     // mode when truncating to an integer value.
18678     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18679     addFrameReference(BuildMI(*BB, MI, DL,
18680                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18681
18682     // Load the old value of the high byte of the control word...
18683     unsigned OldCW =
18684       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18685     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18686                       CWFrameIdx);
18687
18688     // Set the high part to be round to zero...
18689     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18690       .addImm(0xC7F);
18691
18692     // Reload the modified control word now...
18693     addFrameReference(BuildMI(*BB, MI, DL,
18694                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18695
18696     // Restore the memory image of control word to original value
18697     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18698       .addReg(OldCW);
18699
18700     // Get the X86 opcode to use.
18701     unsigned Opc;
18702     switch (MI->getOpcode()) {
18703     default: llvm_unreachable("illegal opcode!");
18704     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18705     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18706     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18707     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18708     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18709     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18710     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18711     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18712     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18713     }
18714
18715     X86AddressMode AM;
18716     MachineOperand &Op = MI->getOperand(0);
18717     if (Op.isReg()) {
18718       AM.BaseType = X86AddressMode::RegBase;
18719       AM.Base.Reg = Op.getReg();
18720     } else {
18721       AM.BaseType = X86AddressMode::FrameIndexBase;
18722       AM.Base.FrameIndex = Op.getIndex();
18723     }
18724     Op = MI->getOperand(1);
18725     if (Op.isImm())
18726       AM.Scale = Op.getImm();
18727     Op = MI->getOperand(2);
18728     if (Op.isImm())
18729       AM.IndexReg = Op.getImm();
18730     Op = MI->getOperand(3);
18731     if (Op.isGlobal()) {
18732       AM.GV = Op.getGlobal();
18733     } else {
18734       AM.Disp = Op.getImm();
18735     }
18736     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18737                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18738
18739     // Reload the original control word now.
18740     addFrameReference(BuildMI(*BB, MI, DL,
18741                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18742
18743     MI->eraseFromParent();   // The pseudo instruction is gone now.
18744     return BB;
18745   }
18746     // String/text processing lowering.
18747   case X86::PCMPISTRM128REG:
18748   case X86::VPCMPISTRM128REG:
18749   case X86::PCMPISTRM128MEM:
18750   case X86::VPCMPISTRM128MEM:
18751   case X86::PCMPESTRM128REG:
18752   case X86::VPCMPESTRM128REG:
18753   case X86::PCMPESTRM128MEM:
18754   case X86::VPCMPESTRM128MEM:
18755     assert(Subtarget->hasSSE42() &&
18756            "Target must have SSE4.2 or AVX features enabled");
18757     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18758
18759   // String/text processing lowering.
18760   case X86::PCMPISTRIREG:
18761   case X86::VPCMPISTRIREG:
18762   case X86::PCMPISTRIMEM:
18763   case X86::VPCMPISTRIMEM:
18764   case X86::PCMPESTRIREG:
18765   case X86::VPCMPESTRIREG:
18766   case X86::PCMPESTRIMEM:
18767   case X86::VPCMPESTRIMEM:
18768     assert(Subtarget->hasSSE42() &&
18769            "Target must have SSE4.2 or AVX features enabled");
18770     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18771
18772   // Thread synchronization.
18773   case X86::MONITOR:
18774     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18775                        Subtarget);
18776
18777   // xbegin
18778   case X86::XBEGIN:
18779     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18780
18781   case X86::VASTART_SAVE_XMM_REGS:
18782     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18783
18784   case X86::VAARG_64:
18785     return EmitVAARG64WithCustomInserter(MI, BB);
18786
18787   case X86::EH_SjLj_SetJmp32:
18788   case X86::EH_SjLj_SetJmp64:
18789     return emitEHSjLjSetJmp(MI, BB);
18790
18791   case X86::EH_SjLj_LongJmp32:
18792   case X86::EH_SjLj_LongJmp64:
18793     return emitEHSjLjLongJmp(MI, BB);
18794
18795   case TargetOpcode::STACKMAP:
18796   case TargetOpcode::PATCHPOINT:
18797     return emitPatchPoint(MI, BB);
18798
18799   case X86::VFMADDPDr213r:
18800   case X86::VFMADDPSr213r:
18801   case X86::VFMADDSDr213r:
18802   case X86::VFMADDSSr213r:
18803   case X86::VFMSUBPDr213r:
18804   case X86::VFMSUBPSr213r:
18805   case X86::VFMSUBSDr213r:
18806   case X86::VFMSUBSSr213r:
18807   case X86::VFNMADDPDr213r:
18808   case X86::VFNMADDPSr213r:
18809   case X86::VFNMADDSDr213r:
18810   case X86::VFNMADDSSr213r:
18811   case X86::VFNMSUBPDr213r:
18812   case X86::VFNMSUBPSr213r:
18813   case X86::VFNMSUBSDr213r:
18814   case X86::VFNMSUBSSr213r:
18815   case X86::VFMADDPDr213rY:
18816   case X86::VFMADDPSr213rY:
18817   case X86::VFMSUBPDr213rY:
18818   case X86::VFMSUBPSr213rY:
18819   case X86::VFNMADDPDr213rY:
18820   case X86::VFNMADDPSr213rY:
18821   case X86::VFNMSUBPDr213rY:
18822   case X86::VFNMSUBPSr213rY:
18823     return emitFMA3Instr(MI, BB);
18824   }
18825 }
18826
18827 //===----------------------------------------------------------------------===//
18828 //                           X86 Optimization Hooks
18829 //===----------------------------------------------------------------------===//
18830
18831 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18832                                                       APInt &KnownZero,
18833                                                       APInt &KnownOne,
18834                                                       const SelectionDAG &DAG,
18835                                                       unsigned Depth) const {
18836   unsigned BitWidth = KnownZero.getBitWidth();
18837   unsigned Opc = Op.getOpcode();
18838   assert((Opc >= ISD::BUILTIN_OP_END ||
18839           Opc == ISD::INTRINSIC_WO_CHAIN ||
18840           Opc == ISD::INTRINSIC_W_CHAIN ||
18841           Opc == ISD::INTRINSIC_VOID) &&
18842          "Should use MaskedValueIsZero if you don't know whether Op"
18843          " is a target node!");
18844
18845   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18846   switch (Opc) {
18847   default: break;
18848   case X86ISD::ADD:
18849   case X86ISD::SUB:
18850   case X86ISD::ADC:
18851   case X86ISD::SBB:
18852   case X86ISD::SMUL:
18853   case X86ISD::UMUL:
18854   case X86ISD::INC:
18855   case X86ISD::DEC:
18856   case X86ISD::OR:
18857   case X86ISD::XOR:
18858   case X86ISD::AND:
18859     // These nodes' second result is a boolean.
18860     if (Op.getResNo() == 0)
18861       break;
18862     // Fallthrough
18863   case X86ISD::SETCC:
18864     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18865     break;
18866   case ISD::INTRINSIC_WO_CHAIN: {
18867     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18868     unsigned NumLoBits = 0;
18869     switch (IntId) {
18870     default: break;
18871     case Intrinsic::x86_sse_movmsk_ps:
18872     case Intrinsic::x86_avx_movmsk_ps_256:
18873     case Intrinsic::x86_sse2_movmsk_pd:
18874     case Intrinsic::x86_avx_movmsk_pd_256:
18875     case Intrinsic::x86_mmx_pmovmskb:
18876     case Intrinsic::x86_sse2_pmovmskb_128:
18877     case Intrinsic::x86_avx2_pmovmskb: {
18878       // High bits of movmskp{s|d}, pmovmskb are known zero.
18879       switch (IntId) {
18880         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18881         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18882         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18883         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18884         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18885         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18886         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18887         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18888       }
18889       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18890       break;
18891     }
18892     }
18893     break;
18894   }
18895   }
18896 }
18897
18898 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18899   SDValue Op,
18900   const SelectionDAG &,
18901   unsigned Depth) const {
18902   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18903   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18904     return Op.getValueType().getScalarType().getSizeInBits();
18905
18906   // Fallback case.
18907   return 1;
18908 }
18909
18910 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18911 /// node is a GlobalAddress + offset.
18912 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18913                                        const GlobalValue* &GA,
18914                                        int64_t &Offset) const {
18915   if (N->getOpcode() == X86ISD::Wrapper) {
18916     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18917       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18918       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18919       return true;
18920     }
18921   }
18922   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18923 }
18924
18925 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18926 /// same as extracting the high 128-bit part of 256-bit vector and then
18927 /// inserting the result into the low part of a new 256-bit vector
18928 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18929   EVT VT = SVOp->getValueType(0);
18930   unsigned NumElems = VT.getVectorNumElements();
18931
18932   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18933   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18934     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18935         SVOp->getMaskElt(j) >= 0)
18936       return false;
18937
18938   return true;
18939 }
18940
18941 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18942 /// same as extracting the low 128-bit part of 256-bit vector and then
18943 /// inserting the result into the high part of a new 256-bit vector
18944 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18945   EVT VT = SVOp->getValueType(0);
18946   unsigned NumElems = VT.getVectorNumElements();
18947
18948   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18949   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18950     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18951         SVOp->getMaskElt(j) >= 0)
18952       return false;
18953
18954   return true;
18955 }
18956
18957 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18958 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18959                                         TargetLowering::DAGCombinerInfo &DCI,
18960                                         const X86Subtarget* Subtarget) {
18961   SDLoc dl(N);
18962   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18963   SDValue V1 = SVOp->getOperand(0);
18964   SDValue V2 = SVOp->getOperand(1);
18965   EVT VT = SVOp->getValueType(0);
18966   unsigned NumElems = VT.getVectorNumElements();
18967
18968   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18969       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18970     //
18971     //                   0,0,0,...
18972     //                      |
18973     //    V      UNDEF    BUILD_VECTOR    UNDEF
18974     //     \      /           \           /
18975     //  CONCAT_VECTOR         CONCAT_VECTOR
18976     //         \                  /
18977     //          \                /
18978     //          RESULT: V + zero extended
18979     //
18980     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18981         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18982         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18983       return SDValue();
18984
18985     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18986       return SDValue();
18987
18988     // To match the shuffle mask, the first half of the mask should
18989     // be exactly the first vector, and all the rest a splat with the
18990     // first element of the second one.
18991     for (unsigned i = 0; i != NumElems/2; ++i)
18992       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18993           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18994         return SDValue();
18995
18996     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18997     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18998       if (Ld->hasNUsesOfValue(1, 0)) {
18999         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19000         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19001         SDValue ResNode =
19002           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19003                                   Ld->getMemoryVT(),
19004                                   Ld->getPointerInfo(),
19005                                   Ld->getAlignment(),
19006                                   false/*isVolatile*/, true/*ReadMem*/,
19007                                   false/*WriteMem*/);
19008
19009         // Make sure the newly-created LOAD is in the same position as Ld in
19010         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19011         // and update uses of Ld's output chain to use the TokenFactor.
19012         if (Ld->hasAnyUseOfValue(1)) {
19013           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19014                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19015           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19016           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19017                                  SDValue(ResNode.getNode(), 1));
19018         }
19019
19020         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19021       }
19022     }
19023
19024     // Emit a zeroed vector and insert the desired subvector on its
19025     // first half.
19026     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19027     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19028     return DCI.CombineTo(N, InsV);
19029   }
19030
19031   //===--------------------------------------------------------------------===//
19032   // Combine some shuffles into subvector extracts and inserts:
19033   //
19034
19035   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19036   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19037     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19038     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19039     return DCI.CombineTo(N, InsV);
19040   }
19041
19042   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19043   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19044     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19045     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19046     return DCI.CombineTo(N, InsV);
19047   }
19048
19049   return SDValue();
19050 }
19051
19052 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19053 /// possible.
19054 ///
19055 /// This is the leaf of the recursive combinine below. When we have found some
19056 /// chain of single-use x86 shuffle instructions and accumulated the combined
19057 /// shuffle mask represented by them, this will try to pattern match that mask
19058 /// into either a single instruction if there is a special purpose instruction
19059 /// for this operation, or into a PSHUFB instruction which is a fully general
19060 /// instruction but should only be used to replace chains over a certain depth.
19061 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19062                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19063                                    TargetLowering::DAGCombinerInfo &DCI,
19064                                    const X86Subtarget *Subtarget) {
19065   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19066
19067   // Find the operand that enters the chain. Note that multiple uses are OK
19068   // here, we're not going to remove the operand we find.
19069   SDValue Input = Op.getOperand(0);
19070   while (Input.getOpcode() == ISD::BITCAST)
19071     Input = Input.getOperand(0);
19072
19073   MVT VT = Input.getSimpleValueType();
19074   MVT RootVT = Root.getSimpleValueType();
19075   SDLoc DL(Root);
19076
19077   // Just remove no-op shuffle masks.
19078   if (Mask.size() == 1) {
19079     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19080                   /*AddTo*/ true);
19081     return true;
19082   }
19083
19084   // Use the float domain if the operand type is a floating point type.
19085   bool FloatDomain = VT.isFloatingPoint();
19086
19087   // If we don't have access to VEX encodings, the generic PSHUF instructions
19088   // are preferable to some of the specialized forms despite requiring one more
19089   // byte to encode because they can implicitly copy.
19090   //
19091   // IF we *do* have VEX encodings, than we can use shorter, more specific
19092   // shuffle instructions freely as they can copy due to the extra register
19093   // operand.
19094   if (Subtarget->hasAVX()) {
19095     // We have both floating point and integer variants of shuffles that dup
19096     // either the low or high half of the vector.
19097     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19098       bool Lo = Mask.equals(0, 0);
19099       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19100                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19101       if (Depth == 1 && Root->getOpcode() == Shuffle)
19102         return false; // Nothing to do!
19103       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19104       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19105       DCI.AddToWorklist(Op.getNode());
19106       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19107       DCI.AddToWorklist(Op.getNode());
19108       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19109                     /*AddTo*/ true);
19110       return true;
19111     }
19112
19113     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19114
19115     // For the integer domain we have specialized instructions for duplicating
19116     // any element size from the low or high half.
19117     if (!FloatDomain &&
19118         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19119          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19120          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19121          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19122          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19123                      15))) {
19124       bool Lo = Mask[0] == 0;
19125       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19126       if (Depth == 1 && Root->getOpcode() == Shuffle)
19127         return false; // Nothing to do!
19128       MVT ShuffleVT;
19129       switch (Mask.size()) {
19130       case 4: ShuffleVT = MVT::v4i32; break;
19131       case 8: ShuffleVT = MVT::v8i16; break;
19132       case 16: ShuffleVT = MVT::v16i8; break;
19133       };
19134       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19135       DCI.AddToWorklist(Op.getNode());
19136       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19137       DCI.AddToWorklist(Op.getNode());
19138       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19139                     /*AddTo*/ true);
19140       return true;
19141     }
19142   }
19143
19144   // Don't try to re-form single instruction chains under any circumstances now
19145   // that we've done encoding canonicalization for them.
19146   if (Depth < 2)
19147     return false;
19148
19149   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19150   // can replace them with a single PSHUFB instruction profitably. Intel's
19151   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19152   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19153   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19154     SmallVector<SDValue, 16> PSHUFBMask;
19155     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19156     int Ratio = 16 / Mask.size();
19157     for (unsigned i = 0; i < 16; ++i) {
19158       int M = Mask[i / Ratio] != SM_SentinelZero
19159                   ? Ratio * Mask[i / Ratio] + i % Ratio
19160                   : 255;
19161       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19162     }
19163     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19164     DCI.AddToWorklist(Op.getNode());
19165     SDValue PSHUFBMaskOp =
19166         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19167     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19168     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19169     DCI.AddToWorklist(Op.getNode());
19170     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19171                   /*AddTo*/ true);
19172     return true;
19173   }
19174
19175   // Failed to find any combines.
19176   return false;
19177 }
19178
19179 /// \brief Fully generic combining of x86 shuffle instructions.
19180 ///
19181 /// This should be the last combine run over the x86 shuffle instructions. Once
19182 /// they have been fully optimized, this will recursively consider all chains
19183 /// of single-use shuffle instructions, build a generic model of the cumulative
19184 /// shuffle operation, and check for simpler instructions which implement this
19185 /// operation. We use this primarily for two purposes:
19186 ///
19187 /// 1) Collapse generic shuffles to specialized single instructions when
19188 ///    equivalent. In most cases, this is just an encoding size win, but
19189 ///    sometimes we will collapse multiple generic shuffles into a single
19190 ///    special-purpose shuffle.
19191 /// 2) Look for sequences of shuffle instructions with 3 or more total
19192 ///    instructions, and replace them with the slightly more expensive SSSE3
19193 ///    PSHUFB instruction if available. We do this as the last combining step
19194 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19195 ///    a suitable short sequence of other instructions. The PHUFB will either
19196 ///    use a register or have to read from memory and so is slightly (but only
19197 ///    slightly) more expensive than the other shuffle instructions.
19198 ///
19199 /// Because this is inherently a quadratic operation (for each shuffle in
19200 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19201 /// This should never be an issue in practice as the shuffle lowering doesn't
19202 /// produce sequences of more than 8 instructions.
19203 ///
19204 /// FIXME: We will currently miss some cases where the redundant shuffling
19205 /// would simplify under the threshold for PSHUFB formation because of
19206 /// combine-ordering. To fix this, we should do the redundant instruction
19207 /// combining in this recursive walk.
19208 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19209                                           ArrayRef<int> RootMask,
19210                                           int Depth, bool HasPSHUFB,
19211                                           SelectionDAG &DAG,
19212                                           TargetLowering::DAGCombinerInfo &DCI,
19213                                           const X86Subtarget *Subtarget) {
19214   // Bound the depth of our recursive combine because this is ultimately
19215   // quadratic in nature.
19216   if (Depth > 8)
19217     return false;
19218
19219   // Directly rip through bitcasts to find the underlying operand.
19220   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19221     Op = Op.getOperand(0);
19222
19223   MVT VT = Op.getSimpleValueType();
19224   if (!VT.isVector())
19225     return false; // Bail if we hit a non-vector.
19226   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19227   // version should be added.
19228   if (VT.getSizeInBits() != 128)
19229     return false;
19230
19231   assert(Root.getSimpleValueType().isVector() &&
19232          "Shuffles operate on vector types!");
19233   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19234          "Can only combine shuffles of the same vector register size.");
19235
19236   if (!isTargetShuffle(Op.getOpcode()))
19237     return false;
19238   SmallVector<int, 16> OpMask;
19239   bool IsUnary;
19240   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19241   // We only can combine unary shuffles which we can decode the mask for.
19242   if (!HaveMask || !IsUnary)
19243     return false;
19244
19245   assert(VT.getVectorNumElements() == OpMask.size() &&
19246          "Different mask size from vector size!");
19247   assert(((RootMask.size() > OpMask.size() &&
19248            RootMask.size() % OpMask.size() == 0) ||
19249           (OpMask.size() > RootMask.size() &&
19250            OpMask.size() % RootMask.size() == 0) ||
19251           OpMask.size() == RootMask.size()) &&
19252          "The smaller number of elements must divide the larger.");
19253   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19254   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19255   assert(((RootRatio == 1 && OpRatio == 1) ||
19256           (RootRatio == 1) != (OpRatio == 1)) &&
19257          "Must not have a ratio for both incoming and op masks!");
19258
19259   SmallVector<int, 16> Mask;
19260   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19261
19262   // Merge this shuffle operation's mask into our accumulated mask. Note that
19263   // this shuffle's mask will be the first applied to the input, followed by the
19264   // root mask to get us all the way to the root value arrangement. The reason
19265   // for this order is that we are recursing up the operation chain.
19266   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19267     int RootIdx = i / RootRatio;
19268     if (RootMask[RootIdx] == SM_SentinelZero) {
19269       // This is a zero-ed lane, we're done.
19270       Mask.push_back(SM_SentinelZero);
19271       continue;
19272     }
19273
19274     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19275     int OpIdx = RootMaskedIdx / OpRatio;
19276     if (OpMask[OpIdx] == SM_SentinelZero) {
19277       // The incoming lanes are zero, it doesn't matter which ones we are using.
19278       Mask.push_back(SM_SentinelZero);
19279       continue;
19280     }
19281
19282     // Ok, we have non-zero lanes, map them through.
19283     Mask.push_back(OpMask[OpIdx] * OpRatio +
19284                    RootMaskedIdx % OpRatio);
19285   }
19286
19287   // See if we can recurse into the operand to combine more things.
19288   switch (Op.getOpcode()) {
19289     case X86ISD::PSHUFB:
19290       HasPSHUFB = true;
19291     case X86ISD::PSHUFD:
19292     case X86ISD::PSHUFHW:
19293     case X86ISD::PSHUFLW:
19294       if (Op.getOperand(0).hasOneUse() &&
19295           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19296                                         HasPSHUFB, DAG, DCI, Subtarget))
19297         return true;
19298       break;
19299
19300     case X86ISD::UNPCKL:
19301     case X86ISD::UNPCKH:
19302       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19303       // We can't check for single use, we have to check that this shuffle is the only user.
19304       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19305           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19306                                         HasPSHUFB, DAG, DCI, Subtarget))
19307           return true;
19308       break;
19309   }
19310
19311   // Minor canonicalization of the accumulated shuffle mask to make it easier
19312   // to match below. All this does is detect masks with squential pairs of
19313   // elements, and shrink them to the half-width mask. It does this in a loop
19314   // so it will reduce the size of the mask to the minimal width mask which
19315   // performs an equivalent shuffle.
19316   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19317     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19318       Mask[i] = Mask[2 * i] / 2;
19319     Mask.resize(Mask.size() / 2);
19320   }
19321
19322   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19323                                 Subtarget);
19324 }
19325
19326 /// \brief Get the PSHUF-style mask from PSHUF node.
19327 ///
19328 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19329 /// PSHUF-style masks that can be reused with such instructions.
19330 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19331   SmallVector<int, 4> Mask;
19332   bool IsUnary;
19333   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19334   (void)HaveMask;
19335   assert(HaveMask);
19336
19337   switch (N.getOpcode()) {
19338   case X86ISD::PSHUFD:
19339     return Mask;
19340   case X86ISD::PSHUFLW:
19341     Mask.resize(4);
19342     return Mask;
19343   case X86ISD::PSHUFHW:
19344     Mask.erase(Mask.begin(), Mask.begin() + 4);
19345     for (int &M : Mask)
19346       M -= 4;
19347     return Mask;
19348   default:
19349     llvm_unreachable("No valid shuffle instruction found!");
19350   }
19351 }
19352
19353 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19354 ///
19355 /// We walk up the chain and look for a combinable shuffle, skipping over
19356 /// shuffles that we could hoist this shuffle's transformation past without
19357 /// altering anything.
19358 static SDValue
19359 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19360                              SelectionDAG &DAG,
19361                              TargetLowering::DAGCombinerInfo &DCI) {
19362   assert(N.getOpcode() == X86ISD::PSHUFD &&
19363          "Called with something other than an x86 128-bit half shuffle!");
19364   SDLoc DL(N);
19365
19366   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19367   // of the shuffles in the chain so that we can form a fresh chain to replace
19368   // this one.
19369   SmallVector<SDValue, 8> Chain;
19370   SDValue V = N.getOperand(0);
19371   for (; V.hasOneUse(); V = V.getOperand(0)) {
19372     switch (V.getOpcode()) {
19373     default:
19374       return SDValue(); // Nothing combined!
19375
19376     case ISD::BITCAST:
19377       // Skip bitcasts as we always know the type for the target specific
19378       // instructions.
19379       continue;
19380
19381     case X86ISD::PSHUFD:
19382       // Found another dword shuffle.
19383       break;
19384
19385     case X86ISD::PSHUFLW:
19386       // Check that the low words (being shuffled) are the identity in the
19387       // dword shuffle, and the high words are self-contained.
19388       if (Mask[0] != 0 || Mask[1] != 1 ||
19389           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19390         return SDValue();
19391
19392       Chain.push_back(V);
19393       continue;
19394
19395     case X86ISD::PSHUFHW:
19396       // Check that the high words (being shuffled) are the identity in the
19397       // dword shuffle, and the low words are self-contained.
19398       if (Mask[2] != 2 || Mask[3] != 3 ||
19399           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19400         return SDValue();
19401
19402       Chain.push_back(V);
19403       continue;
19404
19405     case X86ISD::UNPCKL:
19406     case X86ISD::UNPCKH:
19407       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19408       // shuffle into a preceding word shuffle.
19409       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19410         return SDValue();
19411
19412       // Search for a half-shuffle which we can combine with.
19413       unsigned CombineOp =
19414           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19415       if (V.getOperand(0) != V.getOperand(1) ||
19416           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19417         return SDValue();
19418       Chain.push_back(V);
19419       V = V.getOperand(0);
19420       do {
19421         switch (V.getOpcode()) {
19422         default:
19423           return SDValue(); // Nothing to combine.
19424
19425         case X86ISD::PSHUFLW:
19426         case X86ISD::PSHUFHW:
19427           if (V.getOpcode() == CombineOp)
19428             break;
19429
19430           Chain.push_back(V);
19431
19432           // Fallthrough!
19433         case ISD::BITCAST:
19434           V = V.getOperand(0);
19435           continue;
19436         }
19437         break;
19438       } while (V.hasOneUse());
19439       break;
19440     }
19441     // Break out of the loop if we break out of the switch.
19442     break;
19443   }
19444
19445   if (!V.hasOneUse())
19446     // We fell out of the loop without finding a viable combining instruction.
19447     return SDValue();
19448
19449   // Merge this node's mask and our incoming mask.
19450   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19451   for (int &M : Mask)
19452     M = VMask[M];
19453   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19454                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19455
19456   // Rebuild the chain around this new shuffle.
19457   while (!Chain.empty()) {
19458     SDValue W = Chain.pop_back_val();
19459
19460     if (V.getValueType() != W.getOperand(0).getValueType())
19461       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19462
19463     switch (W.getOpcode()) {
19464     default:
19465       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19466
19467     case X86ISD::UNPCKL:
19468     case X86ISD::UNPCKH:
19469       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19470       break;
19471
19472     case X86ISD::PSHUFD:
19473     case X86ISD::PSHUFLW:
19474     case X86ISD::PSHUFHW:
19475       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19476       break;
19477     }
19478   }
19479   if (V.getValueType() != N.getValueType())
19480     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19481
19482   // Return the new chain to replace N.
19483   return V;
19484 }
19485
19486 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19487 ///
19488 /// We walk up the chain, skipping shuffles of the other half and looking
19489 /// through shuffles which switch halves trying to find a shuffle of the same
19490 /// pair of dwords.
19491 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19492                                         SelectionDAG &DAG,
19493                                         TargetLowering::DAGCombinerInfo &DCI) {
19494   assert(
19495       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19496       "Called with something other than an x86 128-bit half shuffle!");
19497   SDLoc DL(N);
19498   unsigned CombineOpcode = N.getOpcode();
19499
19500   // Walk up a single-use chain looking for a combinable shuffle.
19501   SDValue V = N.getOperand(0);
19502   for (; V.hasOneUse(); V = V.getOperand(0)) {
19503     switch (V.getOpcode()) {
19504     default:
19505       return false; // Nothing combined!
19506
19507     case ISD::BITCAST:
19508       // Skip bitcasts as we always know the type for the target specific
19509       // instructions.
19510       continue;
19511
19512     case X86ISD::PSHUFLW:
19513     case X86ISD::PSHUFHW:
19514       if (V.getOpcode() == CombineOpcode)
19515         break;
19516
19517       // Other-half shuffles are no-ops.
19518       continue;
19519     }
19520     // Break out of the loop if we break out of the switch.
19521     break;
19522   }
19523
19524   if (!V.hasOneUse())
19525     // We fell out of the loop without finding a viable combining instruction.
19526     return false;
19527
19528   // Combine away the bottom node as its shuffle will be accumulated into
19529   // a preceding shuffle.
19530   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19531
19532   // Record the old value.
19533   SDValue Old = V;
19534
19535   // Merge this node's mask and our incoming mask (adjusted to account for all
19536   // the pshufd instructions encountered).
19537   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19538   for (int &M : Mask)
19539     M = VMask[M];
19540   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19541                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19542
19543   // Check that the shuffles didn't cancel each other out. If not, we need to
19544   // combine to the new one.
19545   if (Old != V)
19546     // Replace the combinable shuffle with the combined one, updating all users
19547     // so that we re-evaluate the chain here.
19548     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19549
19550   return true;
19551 }
19552
19553 /// \brief Try to combine x86 target specific shuffles.
19554 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19555                                            TargetLowering::DAGCombinerInfo &DCI,
19556                                            const X86Subtarget *Subtarget) {
19557   SDLoc DL(N);
19558   MVT VT = N.getSimpleValueType();
19559   SmallVector<int, 4> Mask;
19560
19561   switch (N.getOpcode()) {
19562   case X86ISD::PSHUFD:
19563   case X86ISD::PSHUFLW:
19564   case X86ISD::PSHUFHW:
19565     Mask = getPSHUFShuffleMask(N);
19566     assert(Mask.size() == 4);
19567     break;
19568   default:
19569     return SDValue();
19570   }
19571
19572   // Nuke no-op shuffles that show up after combining.
19573   if (isNoopShuffleMask(Mask))
19574     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19575
19576   // Look for simplifications involving one or two shuffle instructions.
19577   SDValue V = N.getOperand(0);
19578   switch (N.getOpcode()) {
19579   default:
19580     break;
19581   case X86ISD::PSHUFLW:
19582   case X86ISD::PSHUFHW:
19583     assert(VT == MVT::v8i16);
19584     (void)VT;
19585
19586     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19587       return SDValue(); // We combined away this shuffle, so we're done.
19588
19589     // See if this reduces to a PSHUFD which is no more expensive and can
19590     // combine with more operations.
19591     if (canWidenShuffleElements(Mask)) {
19592       int DMask[] = {-1, -1, -1, -1};
19593       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19594       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19595       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19596       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19597       DCI.AddToWorklist(V.getNode());
19598       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19599                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19600       DCI.AddToWorklist(V.getNode());
19601       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19602     }
19603
19604     // Look for shuffle patterns which can be implemented as a single unpack.
19605     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19606     // only works when we have a PSHUFD followed by two half-shuffles.
19607     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19608         (V.getOpcode() == X86ISD::PSHUFLW ||
19609          V.getOpcode() == X86ISD::PSHUFHW) &&
19610         V.getOpcode() != N.getOpcode() &&
19611         V.hasOneUse()) {
19612       SDValue D = V.getOperand(0);
19613       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19614         D = D.getOperand(0);
19615       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19616         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19617         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19618         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19619         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19620         int WordMask[8];
19621         for (int i = 0; i < 4; ++i) {
19622           WordMask[i + NOffset] = Mask[i] + NOffset;
19623           WordMask[i + VOffset] = VMask[i] + VOffset;
19624         }
19625         // Map the word mask through the DWord mask.
19626         int MappedMask[8];
19627         for (int i = 0; i < 8; ++i)
19628           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19629         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19630         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19631         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19632                        std::begin(UnpackLoMask)) ||
19633             std::equal(std::begin(MappedMask), std::end(MappedMask),
19634                        std::begin(UnpackHiMask))) {
19635           // We can replace all three shuffles with an unpack.
19636           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19637           DCI.AddToWorklist(V.getNode());
19638           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19639                                                 : X86ISD::UNPCKH,
19640                              DL, MVT::v8i16, V, V);
19641         }
19642       }
19643     }
19644
19645     break;
19646
19647   case X86ISD::PSHUFD:
19648     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19649       return NewN;
19650
19651     break;
19652   }
19653
19654   return SDValue();
19655 }
19656
19657 /// PerformShuffleCombine - Performs several different shuffle combines.
19658 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19659                                      TargetLowering::DAGCombinerInfo &DCI,
19660                                      const X86Subtarget *Subtarget) {
19661   SDLoc dl(N);
19662   SDValue N0 = N->getOperand(0);
19663   SDValue N1 = N->getOperand(1);
19664   EVT VT = N->getValueType(0);
19665
19666   // Don't create instructions with illegal types after legalize types has run.
19667   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19668   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19669     return SDValue();
19670
19671   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19672   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19673       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19674     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19675
19676   // During Type Legalization, when promoting illegal vector types,
19677   // the backend might introduce new shuffle dag nodes and bitcasts.
19678   //
19679   // This code performs the following transformation:
19680   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19681   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19682   //
19683   // We do this only if both the bitcast and the BINOP dag nodes have
19684   // one use. Also, perform this transformation only if the new binary
19685   // operation is legal. This is to avoid introducing dag nodes that
19686   // potentially need to be further expanded (or custom lowered) into a
19687   // less optimal sequence of dag nodes.
19688   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19689       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19690       N0.getOpcode() == ISD::BITCAST) {
19691     SDValue BC0 = N0.getOperand(0);
19692     EVT SVT = BC0.getValueType();
19693     unsigned Opcode = BC0.getOpcode();
19694     unsigned NumElts = VT.getVectorNumElements();
19695     
19696     if (BC0.hasOneUse() && SVT.isVector() &&
19697         SVT.getVectorNumElements() * 2 == NumElts &&
19698         TLI.isOperationLegal(Opcode, VT)) {
19699       bool CanFold = false;
19700       switch (Opcode) {
19701       default : break;
19702       case ISD::ADD :
19703       case ISD::FADD :
19704       case ISD::SUB :
19705       case ISD::FSUB :
19706       case ISD::MUL :
19707       case ISD::FMUL :
19708         CanFold = true;
19709       }
19710
19711       unsigned SVTNumElts = SVT.getVectorNumElements();
19712       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19713       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19714         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19715       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19716         CanFold = SVOp->getMaskElt(i) < 0;
19717
19718       if (CanFold) {
19719         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19720         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19721         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19722         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19723       }
19724     }
19725   }
19726
19727   // Only handle 128 wide vector from here on.
19728   if (!VT.is128BitVector())
19729     return SDValue();
19730
19731   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19732   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19733   // consecutive, non-overlapping, and in the right order.
19734   SmallVector<SDValue, 16> Elts;
19735   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19736     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19737
19738   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19739   if (LD.getNode())
19740     return LD;
19741
19742   if (isTargetShuffle(N->getOpcode())) {
19743     SDValue Shuffle =
19744         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19745     if (Shuffle.getNode())
19746       return Shuffle;
19747
19748     // Try recursively combining arbitrary sequences of x86 shuffle
19749     // instructions into higher-order shuffles. We do this after combining
19750     // specific PSHUF instruction sequences into their minimal form so that we
19751     // can evaluate how many specialized shuffle instructions are involved in
19752     // a particular chain.
19753     SmallVector<int, 1> NonceMask; // Just a placeholder.
19754     NonceMask.push_back(0);
19755     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19756                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19757                                       DCI, Subtarget))
19758       return SDValue(); // This routine will use CombineTo to replace N.
19759   }
19760
19761   return SDValue();
19762 }
19763
19764 /// PerformTruncateCombine - Converts truncate operation to
19765 /// a sequence of vector shuffle operations.
19766 /// It is possible when we truncate 256-bit vector to 128-bit vector
19767 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19768                                       TargetLowering::DAGCombinerInfo &DCI,
19769                                       const X86Subtarget *Subtarget)  {
19770   return SDValue();
19771 }
19772
19773 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19774 /// specific shuffle of a load can be folded into a single element load.
19775 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19776 /// shuffles have been customed lowered so we need to handle those here.
19777 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19778                                          TargetLowering::DAGCombinerInfo &DCI) {
19779   if (DCI.isBeforeLegalizeOps())
19780     return SDValue();
19781
19782   SDValue InVec = N->getOperand(0);
19783   SDValue EltNo = N->getOperand(1);
19784
19785   if (!isa<ConstantSDNode>(EltNo))
19786     return SDValue();
19787
19788   EVT VT = InVec.getValueType();
19789
19790   bool HasShuffleIntoBitcast = false;
19791   if (InVec.getOpcode() == ISD::BITCAST) {
19792     // Don't duplicate a load with other uses.
19793     if (!InVec.hasOneUse())
19794       return SDValue();
19795     EVT BCVT = InVec.getOperand(0).getValueType();
19796     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19797       return SDValue();
19798     InVec = InVec.getOperand(0);
19799     HasShuffleIntoBitcast = true;
19800   }
19801
19802   if (!isTargetShuffle(InVec.getOpcode()))
19803     return SDValue();
19804
19805   // Don't duplicate a load with other uses.
19806   if (!InVec.hasOneUse())
19807     return SDValue();
19808
19809   SmallVector<int, 16> ShuffleMask;
19810   bool UnaryShuffle;
19811   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19812                             UnaryShuffle))
19813     return SDValue();
19814
19815   // Select the input vector, guarding against out of range extract vector.
19816   unsigned NumElems = VT.getVectorNumElements();
19817   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19818   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19819   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19820                                          : InVec.getOperand(1);
19821
19822   // If inputs to shuffle are the same for both ops, then allow 2 uses
19823   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19824
19825   if (LdNode.getOpcode() == ISD::BITCAST) {
19826     // Don't duplicate a load with other uses.
19827     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19828       return SDValue();
19829
19830     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19831     LdNode = LdNode.getOperand(0);
19832   }
19833
19834   if (!ISD::isNormalLoad(LdNode.getNode()))
19835     return SDValue();
19836
19837   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19838
19839   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19840     return SDValue();
19841
19842   if (HasShuffleIntoBitcast) {
19843     // If there's a bitcast before the shuffle, check if the load type and
19844     // alignment is valid.
19845     unsigned Align = LN0->getAlignment();
19846     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19847     unsigned NewAlign = TLI.getDataLayout()->
19848       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19849
19850     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19851       return SDValue();
19852   }
19853
19854   // All checks match so transform back to vector_shuffle so that DAG combiner
19855   // can finish the job
19856   SDLoc dl(N);
19857
19858   // Create shuffle node taking into account the case that its a unary shuffle
19859   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19860   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19861                                  InVec.getOperand(0), Shuffle,
19862                                  &ShuffleMask[0]);
19863   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19864   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19865                      EltNo);
19866 }
19867
19868 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19869 /// generation and convert it from being a bunch of shuffles and extracts
19870 /// to a simple store and scalar loads to extract the elements.
19871 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19872                                          TargetLowering::DAGCombinerInfo &DCI) {
19873   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19874   if (NewOp.getNode())
19875     return NewOp;
19876
19877   SDValue InputVector = N->getOperand(0);
19878
19879   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19880   // from mmx to v2i32 has a single usage.
19881   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19882       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19883       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19884     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19885                        N->getValueType(0),
19886                        InputVector.getNode()->getOperand(0));
19887
19888   // Only operate on vectors of 4 elements, where the alternative shuffling
19889   // gets to be more expensive.
19890   if (InputVector.getValueType() != MVT::v4i32)
19891     return SDValue();
19892
19893   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19894   // single use which is a sign-extend or zero-extend, and all elements are
19895   // used.
19896   SmallVector<SDNode *, 4> Uses;
19897   unsigned ExtractedElements = 0;
19898   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19899        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19900     if (UI.getUse().getResNo() != InputVector.getResNo())
19901       return SDValue();
19902
19903     SDNode *Extract = *UI;
19904     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19905       return SDValue();
19906
19907     if (Extract->getValueType(0) != MVT::i32)
19908       return SDValue();
19909     if (!Extract->hasOneUse())
19910       return SDValue();
19911     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19912         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19913       return SDValue();
19914     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19915       return SDValue();
19916
19917     // Record which element was extracted.
19918     ExtractedElements |=
19919       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19920
19921     Uses.push_back(Extract);
19922   }
19923
19924   // If not all the elements were used, this may not be worthwhile.
19925   if (ExtractedElements != 15)
19926     return SDValue();
19927
19928   // Ok, we've now decided to do the transformation.
19929   SDLoc dl(InputVector);
19930
19931   // Store the value to a temporary stack slot.
19932   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19933   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19934                             MachinePointerInfo(), false, false, 0);
19935
19936   // Replace each use (extract) with a load of the appropriate element.
19937   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19938        UE = Uses.end(); UI != UE; ++UI) {
19939     SDNode *Extract = *UI;
19940
19941     // cOMpute the element's address.
19942     SDValue Idx = Extract->getOperand(1);
19943     unsigned EltSize =
19944         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19945     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19946     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19947     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19948
19949     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19950                                      StackPtr, OffsetVal);
19951
19952     // Load the scalar.
19953     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19954                                      ScalarAddr, MachinePointerInfo(),
19955                                      false, false, false, 0);
19956
19957     // Replace the exact with the load.
19958     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19959   }
19960
19961   // The replacement was made in place; don't return anything.
19962   return SDValue();
19963 }
19964
19965 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19966 static std::pair<unsigned, bool>
19967 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19968                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19969   if (!VT.isVector())
19970     return std::make_pair(0, false);
19971
19972   bool NeedSplit = false;
19973   switch (VT.getSimpleVT().SimpleTy) {
19974   default: return std::make_pair(0, false);
19975   case MVT::v32i8:
19976   case MVT::v16i16:
19977   case MVT::v8i32:
19978     if (!Subtarget->hasAVX2())
19979       NeedSplit = true;
19980     if (!Subtarget->hasAVX())
19981       return std::make_pair(0, false);
19982     break;
19983   case MVT::v16i8:
19984   case MVT::v8i16:
19985   case MVT::v4i32:
19986     if (!Subtarget->hasSSE2())
19987       return std::make_pair(0, false);
19988   }
19989
19990   // SSE2 has only a small subset of the operations.
19991   bool hasUnsigned = Subtarget->hasSSE41() ||
19992                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19993   bool hasSigned = Subtarget->hasSSE41() ||
19994                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19995
19996   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19997
19998   unsigned Opc = 0;
19999   // Check for x CC y ? x : y.
20000   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20001       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20002     switch (CC) {
20003     default: break;
20004     case ISD::SETULT:
20005     case ISD::SETULE:
20006       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20007     case ISD::SETUGT:
20008     case ISD::SETUGE:
20009       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20010     case ISD::SETLT:
20011     case ISD::SETLE:
20012       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20013     case ISD::SETGT:
20014     case ISD::SETGE:
20015       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20016     }
20017   // Check for x CC y ? y : x -- a min/max with reversed arms.
20018   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20019              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20020     switch (CC) {
20021     default: break;
20022     case ISD::SETULT:
20023     case ISD::SETULE:
20024       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20025     case ISD::SETUGT:
20026     case ISD::SETUGE:
20027       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20028     case ISD::SETLT:
20029     case ISD::SETLE:
20030       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20031     case ISD::SETGT:
20032     case ISD::SETGE:
20033       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20034     }
20035   }
20036
20037   return std::make_pair(Opc, NeedSplit);
20038 }
20039
20040 static SDValue
20041 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20042                                       const X86Subtarget *Subtarget) {
20043   SDLoc dl(N);
20044   SDValue Cond = N->getOperand(0);
20045   SDValue LHS = N->getOperand(1);
20046   SDValue RHS = N->getOperand(2);
20047
20048   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20049     SDValue CondSrc = Cond->getOperand(0);
20050     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20051       Cond = CondSrc->getOperand(0);
20052   }
20053
20054   MVT VT = N->getSimpleValueType(0);
20055   MVT EltVT = VT.getVectorElementType();
20056   unsigned NumElems = VT.getVectorNumElements();
20057   // There is no blend with immediate in AVX-512.
20058   if (VT.is512BitVector())
20059     return SDValue();
20060
20061   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20062     return SDValue();
20063   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20064     return SDValue();
20065
20066   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20067     return SDValue();
20068
20069   // A vselect where all conditions and data are constants can be optimized into
20070   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20071   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20072       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20073     return SDValue();
20074
20075   unsigned MaskValue = 0;
20076   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20077     return SDValue();
20078
20079   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20080   for (unsigned i = 0; i < NumElems; ++i) {
20081     // Be sure we emit undef where we can.
20082     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20083       ShuffleMask[i] = -1;
20084     else
20085       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20086   }
20087
20088   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20089 }
20090
20091 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20092 /// nodes.
20093 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20094                                     TargetLowering::DAGCombinerInfo &DCI,
20095                                     const X86Subtarget *Subtarget) {
20096   SDLoc DL(N);
20097   SDValue Cond = N->getOperand(0);
20098   // Get the LHS/RHS of the select.
20099   SDValue LHS = N->getOperand(1);
20100   SDValue RHS = N->getOperand(2);
20101   EVT VT = LHS.getValueType();
20102   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20103
20104   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20105   // instructions match the semantics of the common C idiom x<y?x:y but not
20106   // x<=y?x:y, because of how they handle negative zero (which can be
20107   // ignored in unsafe-math mode).
20108   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20109       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20110       (Subtarget->hasSSE2() ||
20111        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20112     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20113
20114     unsigned Opcode = 0;
20115     // Check for x CC y ? x : y.
20116     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20117         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20118       switch (CC) {
20119       default: break;
20120       case ISD::SETULT:
20121         // Converting this to a min would handle NaNs incorrectly, and swapping
20122         // the operands would cause it to handle comparisons between positive
20123         // and negative zero incorrectly.
20124         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20125           if (!DAG.getTarget().Options.UnsafeFPMath &&
20126               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20127             break;
20128           std::swap(LHS, RHS);
20129         }
20130         Opcode = X86ISD::FMIN;
20131         break;
20132       case ISD::SETOLE:
20133         // Converting this to a min would handle comparisons between positive
20134         // and negative zero incorrectly.
20135         if (!DAG.getTarget().Options.UnsafeFPMath &&
20136             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20137           break;
20138         Opcode = X86ISD::FMIN;
20139         break;
20140       case ISD::SETULE:
20141         // Converting this to a min would handle both negative zeros and NaNs
20142         // incorrectly, but we can swap the operands to fix both.
20143         std::swap(LHS, RHS);
20144       case ISD::SETOLT:
20145       case ISD::SETLT:
20146       case ISD::SETLE:
20147         Opcode = X86ISD::FMIN;
20148         break;
20149
20150       case ISD::SETOGE:
20151         // Converting this to a max would handle comparisons between positive
20152         // and negative zero incorrectly.
20153         if (!DAG.getTarget().Options.UnsafeFPMath &&
20154             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20155           break;
20156         Opcode = X86ISD::FMAX;
20157         break;
20158       case ISD::SETUGT:
20159         // Converting this to a max would handle NaNs incorrectly, and swapping
20160         // the operands would cause it to handle comparisons between positive
20161         // and negative zero incorrectly.
20162         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20163           if (!DAG.getTarget().Options.UnsafeFPMath &&
20164               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20165             break;
20166           std::swap(LHS, RHS);
20167         }
20168         Opcode = X86ISD::FMAX;
20169         break;
20170       case ISD::SETUGE:
20171         // Converting this to a max would handle both negative zeros and NaNs
20172         // incorrectly, but we can swap the operands to fix both.
20173         std::swap(LHS, RHS);
20174       case ISD::SETOGT:
20175       case ISD::SETGT:
20176       case ISD::SETGE:
20177         Opcode = X86ISD::FMAX;
20178         break;
20179       }
20180     // Check for x CC y ? y : x -- a min/max with reversed arms.
20181     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20182                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20183       switch (CC) {
20184       default: break;
20185       case ISD::SETOGE:
20186         // Converting this to a min would handle comparisons between positive
20187         // and negative zero incorrectly, and swapping the operands would
20188         // cause it to handle NaNs incorrectly.
20189         if (!DAG.getTarget().Options.UnsafeFPMath &&
20190             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20191           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20192             break;
20193           std::swap(LHS, RHS);
20194         }
20195         Opcode = X86ISD::FMIN;
20196         break;
20197       case ISD::SETUGT:
20198         // Converting this to a min would handle NaNs incorrectly.
20199         if (!DAG.getTarget().Options.UnsafeFPMath &&
20200             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20201           break;
20202         Opcode = X86ISD::FMIN;
20203         break;
20204       case ISD::SETUGE:
20205         // Converting this to a min would handle both negative zeros and NaNs
20206         // incorrectly, but we can swap the operands to fix both.
20207         std::swap(LHS, RHS);
20208       case ISD::SETOGT:
20209       case ISD::SETGT:
20210       case ISD::SETGE:
20211         Opcode = X86ISD::FMIN;
20212         break;
20213
20214       case ISD::SETULT:
20215         // Converting this to a max would handle NaNs incorrectly.
20216         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20217           break;
20218         Opcode = X86ISD::FMAX;
20219         break;
20220       case ISD::SETOLE:
20221         // Converting this to a max would handle comparisons between positive
20222         // and negative zero incorrectly, and swapping the operands would
20223         // cause it to handle NaNs incorrectly.
20224         if (!DAG.getTarget().Options.UnsafeFPMath &&
20225             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20226           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20227             break;
20228           std::swap(LHS, RHS);
20229         }
20230         Opcode = X86ISD::FMAX;
20231         break;
20232       case ISD::SETULE:
20233         // Converting this to a max would handle both negative zeros and NaNs
20234         // incorrectly, but we can swap the operands to fix both.
20235         std::swap(LHS, RHS);
20236       case ISD::SETOLT:
20237       case ISD::SETLT:
20238       case ISD::SETLE:
20239         Opcode = X86ISD::FMAX;
20240         break;
20241       }
20242     }
20243
20244     if (Opcode)
20245       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20246   }
20247
20248   EVT CondVT = Cond.getValueType();
20249   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20250       CondVT.getVectorElementType() == MVT::i1) {
20251     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20252     // lowering on AVX-512. In this case we convert it to
20253     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20254     // The same situation for all 128 and 256-bit vectors of i8 and i16
20255     EVT OpVT = LHS.getValueType();
20256     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20257         (OpVT.getVectorElementType() == MVT::i8 ||
20258          OpVT.getVectorElementType() == MVT::i16)) {
20259       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20260       DCI.AddToWorklist(Cond.getNode());
20261       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20262     }
20263   }
20264   // If this is a select between two integer constants, try to do some
20265   // optimizations.
20266   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20267     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20268       // Don't do this for crazy integer types.
20269       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20270         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20271         // so that TrueC (the true value) is larger than FalseC.
20272         bool NeedsCondInvert = false;
20273
20274         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20275             // Efficiently invertible.
20276             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20277              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20278               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20279           NeedsCondInvert = true;
20280           std::swap(TrueC, FalseC);
20281         }
20282
20283         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20284         if (FalseC->getAPIntValue() == 0 &&
20285             TrueC->getAPIntValue().isPowerOf2()) {
20286           if (NeedsCondInvert) // Invert the condition if needed.
20287             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20288                                DAG.getConstant(1, Cond.getValueType()));
20289
20290           // Zero extend the condition if needed.
20291           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20292
20293           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20294           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20295                              DAG.getConstant(ShAmt, MVT::i8));
20296         }
20297
20298         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20299         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20300           if (NeedsCondInvert) // Invert the condition if needed.
20301             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20302                                DAG.getConstant(1, Cond.getValueType()));
20303
20304           // Zero extend the condition if needed.
20305           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20306                              FalseC->getValueType(0), Cond);
20307           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20308                              SDValue(FalseC, 0));
20309         }
20310
20311         // Optimize cases that will turn into an LEA instruction.  This requires
20312         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20313         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20314           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20315           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20316
20317           bool isFastMultiplier = false;
20318           if (Diff < 10) {
20319             switch ((unsigned char)Diff) {
20320               default: break;
20321               case 1:  // result = add base, cond
20322               case 2:  // result = lea base(    , cond*2)
20323               case 3:  // result = lea base(cond, cond*2)
20324               case 4:  // result = lea base(    , cond*4)
20325               case 5:  // result = lea base(cond, cond*4)
20326               case 8:  // result = lea base(    , cond*8)
20327               case 9:  // result = lea base(cond, cond*8)
20328                 isFastMultiplier = true;
20329                 break;
20330             }
20331           }
20332
20333           if (isFastMultiplier) {
20334             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20335             if (NeedsCondInvert) // Invert the condition if needed.
20336               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20337                                  DAG.getConstant(1, Cond.getValueType()));
20338
20339             // Zero extend the condition if needed.
20340             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20341                                Cond);
20342             // Scale the condition by the difference.
20343             if (Diff != 1)
20344               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20345                                  DAG.getConstant(Diff, Cond.getValueType()));
20346
20347             // Add the base if non-zero.
20348             if (FalseC->getAPIntValue() != 0)
20349               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20350                                  SDValue(FalseC, 0));
20351             return Cond;
20352           }
20353         }
20354       }
20355   }
20356
20357   // Canonicalize max and min:
20358   // (x > y) ? x : y -> (x >= y) ? x : y
20359   // (x < y) ? x : y -> (x <= y) ? x : y
20360   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20361   // the need for an extra compare
20362   // against zero. e.g.
20363   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20364   // subl   %esi, %edi
20365   // testl  %edi, %edi
20366   // movl   $0, %eax
20367   // cmovgl %edi, %eax
20368   // =>
20369   // xorl   %eax, %eax
20370   // subl   %esi, $edi
20371   // cmovsl %eax, %edi
20372   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20373       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20374       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20375     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20376     switch (CC) {
20377     default: break;
20378     case ISD::SETLT:
20379     case ISD::SETGT: {
20380       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20381       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20382                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20383       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20384     }
20385     }
20386   }
20387
20388   // Early exit check
20389   if (!TLI.isTypeLegal(VT))
20390     return SDValue();
20391
20392   // Match VSELECTs into subs with unsigned saturation.
20393   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20394       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20395       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20396        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20397     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20398
20399     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20400     // left side invert the predicate to simplify logic below.
20401     SDValue Other;
20402     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20403       Other = RHS;
20404       CC = ISD::getSetCCInverse(CC, true);
20405     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20406       Other = LHS;
20407     }
20408
20409     if (Other.getNode() && Other->getNumOperands() == 2 &&
20410         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20411       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20412       SDValue CondRHS = Cond->getOperand(1);
20413
20414       // Look for a general sub with unsigned saturation first.
20415       // x >= y ? x-y : 0 --> subus x, y
20416       // x >  y ? x-y : 0 --> subus x, y
20417       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20418           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20419         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20420
20421       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20422         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20423           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20424             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20425               // If the RHS is a constant we have to reverse the const
20426               // canonicalization.
20427               // x > C-1 ? x+-C : 0 --> subus x, C
20428               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20429                   CondRHSConst->getAPIntValue() ==
20430                       (-OpRHSConst->getAPIntValue() - 1))
20431                 return DAG.getNode(
20432                     X86ISD::SUBUS, DL, VT, OpLHS,
20433                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20434
20435           // Another special case: If C was a sign bit, the sub has been
20436           // canonicalized into a xor.
20437           // FIXME: Would it be better to use computeKnownBits to determine
20438           //        whether it's safe to decanonicalize the xor?
20439           // x s< 0 ? x^C : 0 --> subus x, C
20440           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20441               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20442               OpRHSConst->getAPIntValue().isSignBit())
20443             // Note that we have to rebuild the RHS constant here to ensure we
20444             // don't rely on particular values of undef lanes.
20445             return DAG.getNode(
20446                 X86ISD::SUBUS, DL, VT, OpLHS,
20447                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20448         }
20449     }
20450   }
20451
20452   // Try to match a min/max vector operation.
20453   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20454     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20455     unsigned Opc = ret.first;
20456     bool NeedSplit = ret.second;
20457
20458     if (Opc && NeedSplit) {
20459       unsigned NumElems = VT.getVectorNumElements();
20460       // Extract the LHS vectors
20461       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20462       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20463
20464       // Extract the RHS vectors
20465       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20466       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20467
20468       // Create min/max for each subvector
20469       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20470       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20471
20472       // Merge the result
20473       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20474     } else if (Opc)
20475       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20476   }
20477
20478   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20479   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20480       // Check if SETCC has already been promoted
20481       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20482       // Check that condition value type matches vselect operand type
20483       CondVT == VT) { 
20484
20485     assert(Cond.getValueType().isVector() &&
20486            "vector select expects a vector selector!");
20487
20488     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20489     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20490
20491     if (!TValIsAllOnes && !FValIsAllZeros) {
20492       // Try invert the condition if true value is not all 1s and false value
20493       // is not all 0s.
20494       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20495       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20496
20497       if (TValIsAllZeros || FValIsAllOnes) {
20498         SDValue CC = Cond.getOperand(2);
20499         ISD::CondCode NewCC =
20500           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20501                                Cond.getOperand(0).getValueType().isInteger());
20502         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20503         std::swap(LHS, RHS);
20504         TValIsAllOnes = FValIsAllOnes;
20505         FValIsAllZeros = TValIsAllZeros;
20506       }
20507     }
20508
20509     if (TValIsAllOnes || FValIsAllZeros) {
20510       SDValue Ret;
20511
20512       if (TValIsAllOnes && FValIsAllZeros)
20513         Ret = Cond;
20514       else if (TValIsAllOnes)
20515         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20516                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20517       else if (FValIsAllZeros)
20518         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20519                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20520
20521       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20522     }
20523   }
20524
20525   // Try to fold this VSELECT into a MOVSS/MOVSD
20526   if (N->getOpcode() == ISD::VSELECT &&
20527       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20528     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20529         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20530       bool CanFold = false;
20531       unsigned NumElems = Cond.getNumOperands();
20532       SDValue A = LHS;
20533       SDValue B = RHS;
20534       
20535       if (isZero(Cond.getOperand(0))) {
20536         CanFold = true;
20537
20538         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20539         // fold (vselect <0,-1> -> (movsd A, B)
20540         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20541           CanFold = isAllOnes(Cond.getOperand(i));
20542       } else if (isAllOnes(Cond.getOperand(0))) {
20543         CanFold = true;
20544         std::swap(A, B);
20545
20546         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20547         // fold (vselect <-1,0> -> (movsd B, A)
20548         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20549           CanFold = isZero(Cond.getOperand(i));
20550       }
20551
20552       if (CanFold) {
20553         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20554           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20555         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20556       }
20557
20558       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20559         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20560         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20561         //                             (v2i64 (bitcast B)))))
20562         //
20563         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20564         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20565         //                             (v2f64 (bitcast B)))))
20566         //
20567         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20568         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20569         //                             (v2i64 (bitcast A)))))
20570         //
20571         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20572         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20573         //                             (v2f64 (bitcast A)))))
20574
20575         CanFold = (isZero(Cond.getOperand(0)) &&
20576                    isZero(Cond.getOperand(1)) &&
20577                    isAllOnes(Cond.getOperand(2)) &&
20578                    isAllOnes(Cond.getOperand(3)));
20579
20580         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20581             isAllOnes(Cond.getOperand(1)) &&
20582             isZero(Cond.getOperand(2)) &&
20583             isZero(Cond.getOperand(3))) {
20584           CanFold = true;
20585           std::swap(LHS, RHS);
20586         }
20587
20588         if (CanFold) {
20589           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20590           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20591           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20592           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20593                                                 NewB, DAG);
20594           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20595         }
20596       }
20597     }
20598   }
20599
20600   // If we know that this node is legal then we know that it is going to be
20601   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20602   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20603   // to simplify previous instructions.
20604   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20605       !DCI.isBeforeLegalize() &&
20606       // We explicitly check against v8i16 and v16i16 because, although
20607       // they're marked as Custom, they might only be legal when Cond is a
20608       // build_vector of constants. This will be taken care in a later
20609       // condition.
20610       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20611        VT != MVT::v8i16)) {
20612     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20613
20614     // Don't optimize vector selects that map to mask-registers.
20615     if (BitWidth == 1)
20616       return SDValue();
20617
20618     // Check all uses of that condition operand to check whether it will be
20619     // consumed by non-BLEND instructions, which may depend on all bits are set
20620     // properly.
20621     for (SDNode::use_iterator I = Cond->use_begin(),
20622                               E = Cond->use_end(); I != E; ++I)
20623       if (I->getOpcode() != ISD::VSELECT)
20624         // TODO: Add other opcodes eventually lowered into BLEND.
20625         return SDValue();
20626
20627     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20628     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20629
20630     APInt KnownZero, KnownOne;
20631     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20632                                           DCI.isBeforeLegalizeOps());
20633     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20634         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20635       DCI.CommitTargetLoweringOpt(TLO);
20636   }
20637
20638   // We should generate an X86ISD::BLENDI from a vselect if its argument
20639   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20640   // constants. This specific pattern gets generated when we split a
20641   // selector for a 512 bit vector in a machine without AVX512 (but with
20642   // 256-bit vectors), during legalization:
20643   //
20644   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20645   //
20646   // Iff we find this pattern and the build_vectors are built from
20647   // constants, we translate the vselect into a shuffle_vector that we
20648   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20649   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20650     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20651     if (Shuffle.getNode())
20652       return Shuffle;
20653   }
20654
20655   return SDValue();
20656 }
20657
20658 // Check whether a boolean test is testing a boolean value generated by
20659 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20660 // code.
20661 //
20662 // Simplify the following patterns:
20663 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20664 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20665 // to (Op EFLAGS Cond)
20666 //
20667 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20668 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20669 // to (Op EFLAGS !Cond)
20670 //
20671 // where Op could be BRCOND or CMOV.
20672 //
20673 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20674   // Quit if not CMP and SUB with its value result used.
20675   if (Cmp.getOpcode() != X86ISD::CMP &&
20676       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20677       return SDValue();
20678
20679   // Quit if not used as a boolean value.
20680   if (CC != X86::COND_E && CC != X86::COND_NE)
20681     return SDValue();
20682
20683   // Check CMP operands. One of them should be 0 or 1 and the other should be
20684   // an SetCC or extended from it.
20685   SDValue Op1 = Cmp.getOperand(0);
20686   SDValue Op2 = Cmp.getOperand(1);
20687
20688   SDValue SetCC;
20689   const ConstantSDNode* C = nullptr;
20690   bool needOppositeCond = (CC == X86::COND_E);
20691   bool checkAgainstTrue = false; // Is it a comparison against 1?
20692
20693   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20694     SetCC = Op2;
20695   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20696     SetCC = Op1;
20697   else // Quit if all operands are not constants.
20698     return SDValue();
20699
20700   if (C->getZExtValue() == 1) {
20701     needOppositeCond = !needOppositeCond;
20702     checkAgainstTrue = true;
20703   } else if (C->getZExtValue() != 0)
20704     // Quit if the constant is neither 0 or 1.
20705     return SDValue();
20706
20707   bool truncatedToBoolWithAnd = false;
20708   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20709   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20710          SetCC.getOpcode() == ISD::TRUNCATE ||
20711          SetCC.getOpcode() == ISD::AND) {
20712     if (SetCC.getOpcode() == ISD::AND) {
20713       int OpIdx = -1;
20714       ConstantSDNode *CS;
20715       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20716           CS->getZExtValue() == 1)
20717         OpIdx = 1;
20718       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20719           CS->getZExtValue() == 1)
20720         OpIdx = 0;
20721       if (OpIdx == -1)
20722         break;
20723       SetCC = SetCC.getOperand(OpIdx);
20724       truncatedToBoolWithAnd = true;
20725     } else
20726       SetCC = SetCC.getOperand(0);
20727   }
20728
20729   switch (SetCC.getOpcode()) {
20730   case X86ISD::SETCC_CARRY:
20731     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20732     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20733     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20734     // truncated to i1 using 'and'.
20735     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20736       break;
20737     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20738            "Invalid use of SETCC_CARRY!");
20739     // FALL THROUGH
20740   case X86ISD::SETCC:
20741     // Set the condition code or opposite one if necessary.
20742     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20743     if (needOppositeCond)
20744       CC = X86::GetOppositeBranchCondition(CC);
20745     return SetCC.getOperand(1);
20746   case X86ISD::CMOV: {
20747     // Check whether false/true value has canonical one, i.e. 0 or 1.
20748     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20749     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20750     // Quit if true value is not a constant.
20751     if (!TVal)
20752       return SDValue();
20753     // Quit if false value is not a constant.
20754     if (!FVal) {
20755       SDValue Op = SetCC.getOperand(0);
20756       // Skip 'zext' or 'trunc' node.
20757       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20758           Op.getOpcode() == ISD::TRUNCATE)
20759         Op = Op.getOperand(0);
20760       // A special case for rdrand/rdseed, where 0 is set if false cond is
20761       // found.
20762       if ((Op.getOpcode() != X86ISD::RDRAND &&
20763            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20764         return SDValue();
20765     }
20766     // Quit if false value is not the constant 0 or 1.
20767     bool FValIsFalse = true;
20768     if (FVal && FVal->getZExtValue() != 0) {
20769       if (FVal->getZExtValue() != 1)
20770         return SDValue();
20771       // If FVal is 1, opposite cond is needed.
20772       needOppositeCond = !needOppositeCond;
20773       FValIsFalse = false;
20774     }
20775     // Quit if TVal is not the constant opposite of FVal.
20776     if (FValIsFalse && TVal->getZExtValue() != 1)
20777       return SDValue();
20778     if (!FValIsFalse && TVal->getZExtValue() != 0)
20779       return SDValue();
20780     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20781     if (needOppositeCond)
20782       CC = X86::GetOppositeBranchCondition(CC);
20783     return SetCC.getOperand(3);
20784   }
20785   }
20786
20787   return SDValue();
20788 }
20789
20790 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20791 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20792                                   TargetLowering::DAGCombinerInfo &DCI,
20793                                   const X86Subtarget *Subtarget) {
20794   SDLoc DL(N);
20795
20796   // If the flag operand isn't dead, don't touch this CMOV.
20797   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20798     return SDValue();
20799
20800   SDValue FalseOp = N->getOperand(0);
20801   SDValue TrueOp = N->getOperand(1);
20802   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20803   SDValue Cond = N->getOperand(3);
20804
20805   if (CC == X86::COND_E || CC == X86::COND_NE) {
20806     switch (Cond.getOpcode()) {
20807     default: break;
20808     case X86ISD::BSR:
20809     case X86ISD::BSF:
20810       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20811       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20812         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20813     }
20814   }
20815
20816   SDValue Flags;
20817
20818   Flags = checkBoolTestSetCCCombine(Cond, CC);
20819   if (Flags.getNode() &&
20820       // Extra check as FCMOV only supports a subset of X86 cond.
20821       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20822     SDValue Ops[] = { FalseOp, TrueOp,
20823                       DAG.getConstant(CC, MVT::i8), Flags };
20824     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20825   }
20826
20827   // If this is a select between two integer constants, try to do some
20828   // optimizations.  Note that the operands are ordered the opposite of SELECT
20829   // operands.
20830   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20831     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20832       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20833       // larger than FalseC (the false value).
20834       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20835         CC = X86::GetOppositeBranchCondition(CC);
20836         std::swap(TrueC, FalseC);
20837         std::swap(TrueOp, FalseOp);
20838       }
20839
20840       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20841       // This is efficient for any integer data type (including i8/i16) and
20842       // shift amount.
20843       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20844         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20845                            DAG.getConstant(CC, MVT::i8), Cond);
20846
20847         // Zero extend the condition if needed.
20848         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20849
20850         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20851         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20852                            DAG.getConstant(ShAmt, MVT::i8));
20853         if (N->getNumValues() == 2)  // Dead flag value?
20854           return DCI.CombineTo(N, Cond, SDValue());
20855         return Cond;
20856       }
20857
20858       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20859       // for any integer data type, including i8/i16.
20860       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20861         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20862                            DAG.getConstant(CC, MVT::i8), Cond);
20863
20864         // Zero extend the condition if needed.
20865         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20866                            FalseC->getValueType(0), Cond);
20867         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20868                            SDValue(FalseC, 0));
20869
20870         if (N->getNumValues() == 2)  // Dead flag value?
20871           return DCI.CombineTo(N, Cond, SDValue());
20872         return Cond;
20873       }
20874
20875       // Optimize cases that will turn into an LEA instruction.  This requires
20876       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20877       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20878         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20879         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20880
20881         bool isFastMultiplier = false;
20882         if (Diff < 10) {
20883           switch ((unsigned char)Diff) {
20884           default: break;
20885           case 1:  // result = add base, cond
20886           case 2:  // result = lea base(    , cond*2)
20887           case 3:  // result = lea base(cond, cond*2)
20888           case 4:  // result = lea base(    , cond*4)
20889           case 5:  // result = lea base(cond, cond*4)
20890           case 8:  // result = lea base(    , cond*8)
20891           case 9:  // result = lea base(cond, cond*8)
20892             isFastMultiplier = true;
20893             break;
20894           }
20895         }
20896
20897         if (isFastMultiplier) {
20898           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20899           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20900                              DAG.getConstant(CC, MVT::i8), Cond);
20901           // Zero extend the condition if needed.
20902           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20903                              Cond);
20904           // Scale the condition by the difference.
20905           if (Diff != 1)
20906             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20907                                DAG.getConstant(Diff, Cond.getValueType()));
20908
20909           // Add the base if non-zero.
20910           if (FalseC->getAPIntValue() != 0)
20911             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20912                                SDValue(FalseC, 0));
20913           if (N->getNumValues() == 2)  // Dead flag value?
20914             return DCI.CombineTo(N, Cond, SDValue());
20915           return Cond;
20916         }
20917       }
20918     }
20919   }
20920
20921   // Handle these cases:
20922   //   (select (x != c), e, c) -> select (x != c), e, x),
20923   //   (select (x == c), c, e) -> select (x == c), x, e)
20924   // where the c is an integer constant, and the "select" is the combination
20925   // of CMOV and CMP.
20926   //
20927   // The rationale for this change is that the conditional-move from a constant
20928   // needs two instructions, however, conditional-move from a register needs
20929   // only one instruction.
20930   //
20931   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20932   //  some instruction-combining opportunities. This opt needs to be
20933   //  postponed as late as possible.
20934   //
20935   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20936     // the DCI.xxxx conditions are provided to postpone the optimization as
20937     // late as possible.
20938
20939     ConstantSDNode *CmpAgainst = nullptr;
20940     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20941         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20942         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20943
20944       if (CC == X86::COND_NE &&
20945           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20946         CC = X86::GetOppositeBranchCondition(CC);
20947         std::swap(TrueOp, FalseOp);
20948       }
20949
20950       if (CC == X86::COND_E &&
20951           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20952         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20953                           DAG.getConstant(CC, MVT::i8), Cond };
20954         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20955       }
20956     }
20957   }
20958
20959   return SDValue();
20960 }
20961
20962 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20963                                                 const X86Subtarget *Subtarget) {
20964   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20965   switch (IntNo) {
20966   default: return SDValue();
20967   // SSE/AVX/AVX2 blend intrinsics.
20968   case Intrinsic::x86_avx2_pblendvb:
20969   case Intrinsic::x86_avx2_pblendw:
20970   case Intrinsic::x86_avx2_pblendd_128:
20971   case Intrinsic::x86_avx2_pblendd_256:
20972     // Don't try to simplify this intrinsic if we don't have AVX2.
20973     if (!Subtarget->hasAVX2())
20974       return SDValue();
20975     // FALL-THROUGH
20976   case Intrinsic::x86_avx_blend_pd_256:
20977   case Intrinsic::x86_avx_blend_ps_256:
20978   case Intrinsic::x86_avx_blendv_pd_256:
20979   case Intrinsic::x86_avx_blendv_ps_256:
20980     // Don't try to simplify this intrinsic if we don't have AVX.
20981     if (!Subtarget->hasAVX())
20982       return SDValue();
20983     // FALL-THROUGH
20984   case Intrinsic::x86_sse41_pblendw:
20985   case Intrinsic::x86_sse41_blendpd:
20986   case Intrinsic::x86_sse41_blendps:
20987   case Intrinsic::x86_sse41_blendvps:
20988   case Intrinsic::x86_sse41_blendvpd:
20989   case Intrinsic::x86_sse41_pblendvb: {
20990     SDValue Op0 = N->getOperand(1);
20991     SDValue Op1 = N->getOperand(2);
20992     SDValue Mask = N->getOperand(3);
20993
20994     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20995     if (!Subtarget->hasSSE41())
20996       return SDValue();
20997
20998     // fold (blend A, A, Mask) -> A
20999     if (Op0 == Op1)
21000       return Op0;
21001     // fold (blend A, B, allZeros) -> A
21002     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21003       return Op0;
21004     // fold (blend A, B, allOnes) -> B
21005     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21006       return Op1;
21007     
21008     // Simplify the case where the mask is a constant i32 value.
21009     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21010       if (C->isNullValue())
21011         return Op0;
21012       if (C->isAllOnesValue())
21013         return Op1;
21014     }
21015
21016     return SDValue();
21017   }
21018
21019   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21020   case Intrinsic::x86_sse2_psrai_w:
21021   case Intrinsic::x86_sse2_psrai_d:
21022   case Intrinsic::x86_avx2_psrai_w:
21023   case Intrinsic::x86_avx2_psrai_d:
21024   case Intrinsic::x86_sse2_psra_w:
21025   case Intrinsic::x86_sse2_psra_d:
21026   case Intrinsic::x86_avx2_psra_w:
21027   case Intrinsic::x86_avx2_psra_d: {
21028     SDValue Op0 = N->getOperand(1);
21029     SDValue Op1 = N->getOperand(2);
21030     EVT VT = Op0.getValueType();
21031     assert(VT.isVector() && "Expected a vector type!");
21032
21033     if (isa<BuildVectorSDNode>(Op1))
21034       Op1 = Op1.getOperand(0);
21035
21036     if (!isa<ConstantSDNode>(Op1))
21037       return SDValue();
21038
21039     EVT SVT = VT.getVectorElementType();
21040     unsigned SVTBits = SVT.getSizeInBits();
21041
21042     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21043     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21044     uint64_t ShAmt = C.getZExtValue();
21045
21046     // Don't try to convert this shift into a ISD::SRA if the shift
21047     // count is bigger than or equal to the element size.
21048     if (ShAmt >= SVTBits)
21049       return SDValue();
21050
21051     // Trivial case: if the shift count is zero, then fold this
21052     // into the first operand.
21053     if (ShAmt == 0)
21054       return Op0;
21055
21056     // Replace this packed shift intrinsic with a target independent
21057     // shift dag node.
21058     SDValue Splat = DAG.getConstant(C, VT);
21059     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21060   }
21061   }
21062 }
21063
21064 /// PerformMulCombine - Optimize a single multiply with constant into two
21065 /// in order to implement it with two cheaper instructions, e.g.
21066 /// LEA + SHL, LEA + LEA.
21067 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21068                                  TargetLowering::DAGCombinerInfo &DCI) {
21069   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21070     return SDValue();
21071
21072   EVT VT = N->getValueType(0);
21073   if (VT != MVT::i64)
21074     return SDValue();
21075
21076   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21077   if (!C)
21078     return SDValue();
21079   uint64_t MulAmt = C->getZExtValue();
21080   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21081     return SDValue();
21082
21083   uint64_t MulAmt1 = 0;
21084   uint64_t MulAmt2 = 0;
21085   if ((MulAmt % 9) == 0) {
21086     MulAmt1 = 9;
21087     MulAmt2 = MulAmt / 9;
21088   } else if ((MulAmt % 5) == 0) {
21089     MulAmt1 = 5;
21090     MulAmt2 = MulAmt / 5;
21091   } else if ((MulAmt % 3) == 0) {
21092     MulAmt1 = 3;
21093     MulAmt2 = MulAmt / 3;
21094   }
21095   if (MulAmt2 &&
21096       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21097     SDLoc DL(N);
21098
21099     if (isPowerOf2_64(MulAmt2) &&
21100         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21101       // If second multiplifer is pow2, issue it first. We want the multiply by
21102       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21103       // is an add.
21104       std::swap(MulAmt1, MulAmt2);
21105
21106     SDValue NewMul;
21107     if (isPowerOf2_64(MulAmt1))
21108       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21109                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21110     else
21111       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21112                            DAG.getConstant(MulAmt1, VT));
21113
21114     if (isPowerOf2_64(MulAmt2))
21115       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21116                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21117     else
21118       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21119                            DAG.getConstant(MulAmt2, VT));
21120
21121     // Do not add new nodes to DAG combiner worklist.
21122     DCI.CombineTo(N, NewMul, false);
21123   }
21124   return SDValue();
21125 }
21126
21127 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21128   SDValue N0 = N->getOperand(0);
21129   SDValue N1 = N->getOperand(1);
21130   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21131   EVT VT = N0.getValueType();
21132
21133   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21134   // since the result of setcc_c is all zero's or all ones.
21135   if (VT.isInteger() && !VT.isVector() &&
21136       N1C && N0.getOpcode() == ISD::AND &&
21137       N0.getOperand(1).getOpcode() == ISD::Constant) {
21138     SDValue N00 = N0.getOperand(0);
21139     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21140         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21141           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21142          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21143       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21144       APInt ShAmt = N1C->getAPIntValue();
21145       Mask = Mask.shl(ShAmt);
21146       if (Mask != 0)
21147         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21148                            N00, DAG.getConstant(Mask, VT));
21149     }
21150   }
21151
21152   // Hardware support for vector shifts is sparse which makes us scalarize the
21153   // vector operations in many cases. Also, on sandybridge ADD is faster than
21154   // shl.
21155   // (shl V, 1) -> add V,V
21156   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21157     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21158       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21159       // We shift all of the values by one. In many cases we do not have
21160       // hardware support for this operation. This is better expressed as an ADD
21161       // of two values.
21162       if (N1SplatC->getZExtValue() == 1)
21163         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21164     }
21165
21166   return SDValue();
21167 }
21168
21169 /// \brief Returns a vector of 0s if the node in input is a vector logical
21170 /// shift by a constant amount which is known to be bigger than or equal
21171 /// to the vector element size in bits.
21172 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21173                                       const X86Subtarget *Subtarget) {
21174   EVT VT = N->getValueType(0);
21175
21176   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21177       (!Subtarget->hasInt256() ||
21178        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21179     return SDValue();
21180
21181   SDValue Amt = N->getOperand(1);
21182   SDLoc DL(N);
21183   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21184     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21185       APInt ShiftAmt = AmtSplat->getAPIntValue();
21186       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21187
21188       // SSE2/AVX2 logical shifts always return a vector of 0s
21189       // if the shift amount is bigger than or equal to
21190       // the element size. The constant shift amount will be
21191       // encoded as a 8-bit immediate.
21192       if (ShiftAmt.trunc(8).uge(MaxAmount))
21193         return getZeroVector(VT, Subtarget, DAG, DL);
21194     }
21195
21196   return SDValue();
21197 }
21198
21199 /// PerformShiftCombine - Combine shifts.
21200 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21201                                    TargetLowering::DAGCombinerInfo &DCI,
21202                                    const X86Subtarget *Subtarget) {
21203   if (N->getOpcode() == ISD::SHL) {
21204     SDValue V = PerformSHLCombine(N, DAG);
21205     if (V.getNode()) return V;
21206   }
21207
21208   if (N->getOpcode() != ISD::SRA) {
21209     // Try to fold this logical shift into a zero vector.
21210     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21211     if (V.getNode()) return V;
21212   }
21213
21214   return SDValue();
21215 }
21216
21217 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21218 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21219 // and friends.  Likewise for OR -> CMPNEQSS.
21220 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21221                             TargetLowering::DAGCombinerInfo &DCI,
21222                             const X86Subtarget *Subtarget) {
21223   unsigned opcode;
21224
21225   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21226   // we're requiring SSE2 for both.
21227   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21228     SDValue N0 = N->getOperand(0);
21229     SDValue N1 = N->getOperand(1);
21230     SDValue CMP0 = N0->getOperand(1);
21231     SDValue CMP1 = N1->getOperand(1);
21232     SDLoc DL(N);
21233
21234     // The SETCCs should both refer to the same CMP.
21235     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21236       return SDValue();
21237
21238     SDValue CMP00 = CMP0->getOperand(0);
21239     SDValue CMP01 = CMP0->getOperand(1);
21240     EVT     VT    = CMP00.getValueType();
21241
21242     if (VT == MVT::f32 || VT == MVT::f64) {
21243       bool ExpectingFlags = false;
21244       // Check for any users that want flags:
21245       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21246            !ExpectingFlags && UI != UE; ++UI)
21247         switch (UI->getOpcode()) {
21248         default:
21249         case ISD::BR_CC:
21250         case ISD::BRCOND:
21251         case ISD::SELECT:
21252           ExpectingFlags = true;
21253           break;
21254         case ISD::CopyToReg:
21255         case ISD::SIGN_EXTEND:
21256         case ISD::ZERO_EXTEND:
21257         case ISD::ANY_EXTEND:
21258           break;
21259         }
21260
21261       if (!ExpectingFlags) {
21262         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21263         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21264
21265         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21266           X86::CondCode tmp = cc0;
21267           cc0 = cc1;
21268           cc1 = tmp;
21269         }
21270
21271         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21272             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21273           // FIXME: need symbolic constants for these magic numbers.
21274           // See X86ATTInstPrinter.cpp:printSSECC().
21275           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21276           if (Subtarget->hasAVX512()) {
21277             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21278                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21279             if (N->getValueType(0) != MVT::i1)
21280               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21281                                  FSetCC);
21282             return FSetCC;
21283           }
21284           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21285                                               CMP00.getValueType(), CMP00, CMP01,
21286                                               DAG.getConstant(x86cc, MVT::i8));
21287
21288           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21289           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21290
21291           if (is64BitFP && !Subtarget->is64Bit()) {
21292             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21293             // 64-bit integer, since that's not a legal type. Since
21294             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21295             // bits, but can do this little dance to extract the lowest 32 bits
21296             // and work with those going forward.
21297             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21298                                            OnesOrZeroesF);
21299             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21300                                            Vector64);
21301             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21302                                         Vector32, DAG.getIntPtrConstant(0));
21303             IntVT = MVT::i32;
21304           }
21305
21306           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21307           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21308                                       DAG.getConstant(1, IntVT));
21309           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21310           return OneBitOfTruth;
21311         }
21312       }
21313     }
21314   }
21315   return SDValue();
21316 }
21317
21318 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21319 /// so it can be folded inside ANDNP.
21320 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21321   EVT VT = N->getValueType(0);
21322
21323   // Match direct AllOnes for 128 and 256-bit vectors
21324   if (ISD::isBuildVectorAllOnes(N))
21325     return true;
21326
21327   // Look through a bit convert.
21328   if (N->getOpcode() == ISD::BITCAST)
21329     N = N->getOperand(0).getNode();
21330
21331   // Sometimes the operand may come from a insert_subvector building a 256-bit
21332   // allones vector
21333   if (VT.is256BitVector() &&
21334       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21335     SDValue V1 = N->getOperand(0);
21336     SDValue V2 = N->getOperand(1);
21337
21338     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21339         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21340         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21341         ISD::isBuildVectorAllOnes(V2.getNode()))
21342       return true;
21343   }
21344
21345   return false;
21346 }
21347
21348 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21349 // register. In most cases we actually compare or select YMM-sized registers
21350 // and mixing the two types creates horrible code. This method optimizes
21351 // some of the transition sequences.
21352 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21353                                  TargetLowering::DAGCombinerInfo &DCI,
21354                                  const X86Subtarget *Subtarget) {
21355   EVT VT = N->getValueType(0);
21356   if (!VT.is256BitVector())
21357     return SDValue();
21358
21359   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21360           N->getOpcode() == ISD::ZERO_EXTEND ||
21361           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21362
21363   SDValue Narrow = N->getOperand(0);
21364   EVT NarrowVT = Narrow->getValueType(0);
21365   if (!NarrowVT.is128BitVector())
21366     return SDValue();
21367
21368   if (Narrow->getOpcode() != ISD::XOR &&
21369       Narrow->getOpcode() != ISD::AND &&
21370       Narrow->getOpcode() != ISD::OR)
21371     return SDValue();
21372
21373   SDValue N0  = Narrow->getOperand(0);
21374   SDValue N1  = Narrow->getOperand(1);
21375   SDLoc DL(Narrow);
21376
21377   // The Left side has to be a trunc.
21378   if (N0.getOpcode() != ISD::TRUNCATE)
21379     return SDValue();
21380
21381   // The type of the truncated inputs.
21382   EVT WideVT = N0->getOperand(0)->getValueType(0);
21383   if (WideVT != VT)
21384     return SDValue();
21385
21386   // The right side has to be a 'trunc' or a constant vector.
21387   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21388   ConstantSDNode *RHSConstSplat = nullptr;
21389   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21390     RHSConstSplat = RHSBV->getConstantSplatNode();
21391   if (!RHSTrunc && !RHSConstSplat)
21392     return SDValue();
21393
21394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21395
21396   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21397     return SDValue();
21398
21399   // Set N0 and N1 to hold the inputs to the new wide operation.
21400   N0 = N0->getOperand(0);
21401   if (RHSConstSplat) {
21402     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21403                      SDValue(RHSConstSplat, 0));
21404     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21405     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21406   } else if (RHSTrunc) {
21407     N1 = N1->getOperand(0);
21408   }
21409
21410   // Generate the wide operation.
21411   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21412   unsigned Opcode = N->getOpcode();
21413   switch (Opcode) {
21414   case ISD::ANY_EXTEND:
21415     return Op;
21416   case ISD::ZERO_EXTEND: {
21417     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21418     APInt Mask = APInt::getAllOnesValue(InBits);
21419     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21420     return DAG.getNode(ISD::AND, DL, VT,
21421                        Op, DAG.getConstant(Mask, VT));
21422   }
21423   case ISD::SIGN_EXTEND:
21424     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21425                        Op, DAG.getValueType(NarrowVT));
21426   default:
21427     llvm_unreachable("Unexpected opcode");
21428   }
21429 }
21430
21431 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21432                                  TargetLowering::DAGCombinerInfo &DCI,
21433                                  const X86Subtarget *Subtarget) {
21434   EVT VT = N->getValueType(0);
21435   if (DCI.isBeforeLegalizeOps())
21436     return SDValue();
21437
21438   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21439   if (R.getNode())
21440     return R;
21441
21442   // Create BEXTR instructions
21443   // BEXTR is ((X >> imm) & (2**size-1))
21444   if (VT == MVT::i32 || VT == MVT::i64) {
21445     SDValue N0 = N->getOperand(0);
21446     SDValue N1 = N->getOperand(1);
21447     SDLoc DL(N);
21448
21449     // Check for BEXTR.
21450     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21451         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21452       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21453       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21454       if (MaskNode && ShiftNode) {
21455         uint64_t Mask = MaskNode->getZExtValue();
21456         uint64_t Shift = ShiftNode->getZExtValue();
21457         if (isMask_64(Mask)) {
21458           uint64_t MaskSize = CountPopulation_64(Mask);
21459           if (Shift + MaskSize <= VT.getSizeInBits())
21460             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21461                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21462         }
21463       }
21464     } // BEXTR
21465
21466     return SDValue();
21467   }
21468
21469   // Want to form ANDNP nodes:
21470   // 1) In the hopes of then easily combining them with OR and AND nodes
21471   //    to form PBLEND/PSIGN.
21472   // 2) To match ANDN packed intrinsics
21473   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21474     return SDValue();
21475
21476   SDValue N0 = N->getOperand(0);
21477   SDValue N1 = N->getOperand(1);
21478   SDLoc DL(N);
21479
21480   // Check LHS for vnot
21481   if (N0.getOpcode() == ISD::XOR &&
21482       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21483       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21484     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21485
21486   // Check RHS for vnot
21487   if (N1.getOpcode() == ISD::XOR &&
21488       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21489       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21490     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21491
21492   return SDValue();
21493 }
21494
21495 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21496                                 TargetLowering::DAGCombinerInfo &DCI,
21497                                 const X86Subtarget *Subtarget) {
21498   if (DCI.isBeforeLegalizeOps())
21499     return SDValue();
21500
21501   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21502   if (R.getNode())
21503     return R;
21504
21505   SDValue N0 = N->getOperand(0);
21506   SDValue N1 = N->getOperand(1);
21507   EVT VT = N->getValueType(0);
21508
21509   // look for psign/blend
21510   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21511     if (!Subtarget->hasSSSE3() ||
21512         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21513       return SDValue();
21514
21515     // Canonicalize pandn to RHS
21516     if (N0.getOpcode() == X86ISD::ANDNP)
21517       std::swap(N0, N1);
21518     // or (and (m, y), (pandn m, x))
21519     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21520       SDValue Mask = N1.getOperand(0);
21521       SDValue X    = N1.getOperand(1);
21522       SDValue Y;
21523       if (N0.getOperand(0) == Mask)
21524         Y = N0.getOperand(1);
21525       if (N0.getOperand(1) == Mask)
21526         Y = N0.getOperand(0);
21527
21528       // Check to see if the mask appeared in both the AND and ANDNP and
21529       if (!Y.getNode())
21530         return SDValue();
21531
21532       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21533       // Look through mask bitcast.
21534       if (Mask.getOpcode() == ISD::BITCAST)
21535         Mask = Mask.getOperand(0);
21536       if (X.getOpcode() == ISD::BITCAST)
21537         X = X.getOperand(0);
21538       if (Y.getOpcode() == ISD::BITCAST)
21539         Y = Y.getOperand(0);
21540
21541       EVT MaskVT = Mask.getValueType();
21542
21543       // Validate that the Mask operand is a vector sra node.
21544       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21545       // there is no psrai.b
21546       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21547       unsigned SraAmt = ~0;
21548       if (Mask.getOpcode() == ISD::SRA) {
21549         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21550           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21551             SraAmt = AmtConst->getZExtValue();
21552       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21553         SDValue SraC = Mask.getOperand(1);
21554         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21555       }
21556       if ((SraAmt + 1) != EltBits)
21557         return SDValue();
21558
21559       SDLoc DL(N);
21560
21561       // Now we know we at least have a plendvb with the mask val.  See if
21562       // we can form a psignb/w/d.
21563       // psign = x.type == y.type == mask.type && y = sub(0, x);
21564       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21565           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21566           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21567         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21568                "Unsupported VT for PSIGN");
21569         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21570         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21571       }
21572       // PBLENDVB only available on SSE 4.1
21573       if (!Subtarget->hasSSE41())
21574         return SDValue();
21575
21576       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21577
21578       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21579       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21580       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21581       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21582       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21583     }
21584   }
21585
21586   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21587     return SDValue();
21588
21589   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21590   MachineFunction &MF = DAG.getMachineFunction();
21591   bool OptForSize = MF.getFunction()->getAttributes().
21592     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21593
21594   // SHLD/SHRD instructions have lower register pressure, but on some
21595   // platforms they have higher latency than the equivalent
21596   // series of shifts/or that would otherwise be generated.
21597   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21598   // have higher latencies and we are not optimizing for size.
21599   if (!OptForSize && Subtarget->isSHLDSlow())
21600     return SDValue();
21601
21602   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21603     std::swap(N0, N1);
21604   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21605     return SDValue();
21606   if (!N0.hasOneUse() || !N1.hasOneUse())
21607     return SDValue();
21608
21609   SDValue ShAmt0 = N0.getOperand(1);
21610   if (ShAmt0.getValueType() != MVT::i8)
21611     return SDValue();
21612   SDValue ShAmt1 = N1.getOperand(1);
21613   if (ShAmt1.getValueType() != MVT::i8)
21614     return SDValue();
21615   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21616     ShAmt0 = ShAmt0.getOperand(0);
21617   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21618     ShAmt1 = ShAmt1.getOperand(0);
21619
21620   SDLoc DL(N);
21621   unsigned Opc = X86ISD::SHLD;
21622   SDValue Op0 = N0.getOperand(0);
21623   SDValue Op1 = N1.getOperand(0);
21624   if (ShAmt0.getOpcode() == ISD::SUB) {
21625     Opc = X86ISD::SHRD;
21626     std::swap(Op0, Op1);
21627     std::swap(ShAmt0, ShAmt1);
21628   }
21629
21630   unsigned Bits = VT.getSizeInBits();
21631   if (ShAmt1.getOpcode() == ISD::SUB) {
21632     SDValue Sum = ShAmt1.getOperand(0);
21633     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21634       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21635       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21636         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21637       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21638         return DAG.getNode(Opc, DL, VT,
21639                            Op0, Op1,
21640                            DAG.getNode(ISD::TRUNCATE, DL,
21641                                        MVT::i8, ShAmt0));
21642     }
21643   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21644     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21645     if (ShAmt0C &&
21646         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21647       return DAG.getNode(Opc, DL, VT,
21648                          N0.getOperand(0), N1.getOperand(0),
21649                          DAG.getNode(ISD::TRUNCATE, DL,
21650                                        MVT::i8, ShAmt0));
21651   }
21652
21653   return SDValue();
21654 }
21655
21656 // Generate NEG and CMOV for integer abs.
21657 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21658   EVT VT = N->getValueType(0);
21659
21660   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21661   // 8-bit integer abs to NEG and CMOV.
21662   if (VT.isInteger() && VT.getSizeInBits() == 8)
21663     return SDValue();
21664
21665   SDValue N0 = N->getOperand(0);
21666   SDValue N1 = N->getOperand(1);
21667   SDLoc DL(N);
21668
21669   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21670   // and change it to SUB and CMOV.
21671   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21672       N0.getOpcode() == ISD::ADD &&
21673       N0.getOperand(1) == N1 &&
21674       N1.getOpcode() == ISD::SRA &&
21675       N1.getOperand(0) == N0.getOperand(0))
21676     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21677       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21678         // Generate SUB & CMOV.
21679         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21680                                   DAG.getConstant(0, VT), N0.getOperand(0));
21681
21682         SDValue Ops[] = { N0.getOperand(0), Neg,
21683                           DAG.getConstant(X86::COND_GE, MVT::i8),
21684                           SDValue(Neg.getNode(), 1) };
21685         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21686       }
21687   return SDValue();
21688 }
21689
21690 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21691 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21692                                  TargetLowering::DAGCombinerInfo &DCI,
21693                                  const X86Subtarget *Subtarget) {
21694   if (DCI.isBeforeLegalizeOps())
21695     return SDValue();
21696
21697   if (Subtarget->hasCMov()) {
21698     SDValue RV = performIntegerAbsCombine(N, DAG);
21699     if (RV.getNode())
21700       return RV;
21701   }
21702
21703   return SDValue();
21704 }
21705
21706 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21707 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21708                                   TargetLowering::DAGCombinerInfo &DCI,
21709                                   const X86Subtarget *Subtarget) {
21710   LoadSDNode *Ld = cast<LoadSDNode>(N);
21711   EVT RegVT = Ld->getValueType(0);
21712   EVT MemVT = Ld->getMemoryVT();
21713   SDLoc dl(Ld);
21714   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21715
21716   // On Sandybridge unaligned 256bit loads are inefficient.
21717   ISD::LoadExtType Ext = Ld->getExtensionType();
21718   unsigned Alignment = Ld->getAlignment();
21719   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21720   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21721       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21722     unsigned NumElems = RegVT.getVectorNumElements();
21723     if (NumElems < 2)
21724       return SDValue();
21725
21726     SDValue Ptr = Ld->getBasePtr();
21727     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21728
21729     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21730                                   NumElems/2);
21731     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21732                                 Ld->getPointerInfo(), Ld->isVolatile(),
21733                                 Ld->isNonTemporal(), Ld->isInvariant(),
21734                                 Alignment);
21735     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21736     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21737                                 Ld->getPointerInfo(), Ld->isVolatile(),
21738                                 Ld->isNonTemporal(), Ld->isInvariant(),
21739                                 std::min(16U, Alignment));
21740     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21741                              Load1.getValue(1),
21742                              Load2.getValue(1));
21743
21744     SDValue NewVec = DAG.getUNDEF(RegVT);
21745     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21746     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21747     return DCI.CombineTo(N, NewVec, TF, true);
21748   }
21749
21750   return SDValue();
21751 }
21752
21753 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21754 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21755                                    const X86Subtarget *Subtarget) {
21756   StoreSDNode *St = cast<StoreSDNode>(N);
21757   EVT VT = St->getValue().getValueType();
21758   EVT StVT = St->getMemoryVT();
21759   SDLoc dl(St);
21760   SDValue StoredVal = St->getOperand(1);
21761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21762
21763   // If we are saving a concatenation of two XMM registers, perform two stores.
21764   // On Sandy Bridge, 256-bit memory operations are executed by two
21765   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21766   // memory  operation.
21767   unsigned Alignment = St->getAlignment();
21768   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21769   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21770       StVT == VT && !IsAligned) {
21771     unsigned NumElems = VT.getVectorNumElements();
21772     if (NumElems < 2)
21773       return SDValue();
21774
21775     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21776     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21777
21778     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21779     SDValue Ptr0 = St->getBasePtr();
21780     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21781
21782     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21783                                 St->getPointerInfo(), St->isVolatile(),
21784                                 St->isNonTemporal(), Alignment);
21785     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21786                                 St->getPointerInfo(), St->isVolatile(),
21787                                 St->isNonTemporal(),
21788                                 std::min(16U, Alignment));
21789     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21790   }
21791
21792   // Optimize trunc store (of multiple scalars) to shuffle and store.
21793   // First, pack all of the elements in one place. Next, store to memory
21794   // in fewer chunks.
21795   if (St->isTruncatingStore() && VT.isVector()) {
21796     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21797     unsigned NumElems = VT.getVectorNumElements();
21798     assert(StVT != VT && "Cannot truncate to the same type");
21799     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21800     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21801
21802     // From, To sizes and ElemCount must be pow of two
21803     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21804     // We are going to use the original vector elt for storing.
21805     // Accumulated smaller vector elements must be a multiple of the store size.
21806     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21807
21808     unsigned SizeRatio  = FromSz / ToSz;
21809
21810     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21811
21812     // Create a type on which we perform the shuffle
21813     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21814             StVT.getScalarType(), NumElems*SizeRatio);
21815
21816     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21817
21818     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21819     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21820     for (unsigned i = 0; i != NumElems; ++i)
21821       ShuffleVec[i] = i * SizeRatio;
21822
21823     // Can't shuffle using an illegal type.
21824     if (!TLI.isTypeLegal(WideVecVT))
21825       return SDValue();
21826
21827     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21828                                          DAG.getUNDEF(WideVecVT),
21829                                          &ShuffleVec[0]);
21830     // At this point all of the data is stored at the bottom of the
21831     // register. We now need to save it to mem.
21832
21833     // Find the largest store unit
21834     MVT StoreType = MVT::i8;
21835     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21836          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21837       MVT Tp = (MVT::SimpleValueType)tp;
21838       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21839         StoreType = Tp;
21840     }
21841
21842     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21843     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21844         (64 <= NumElems * ToSz))
21845       StoreType = MVT::f64;
21846
21847     // Bitcast the original vector into a vector of store-size units
21848     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21849             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21850     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21851     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21852     SmallVector<SDValue, 8> Chains;
21853     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21854                                         TLI.getPointerTy());
21855     SDValue Ptr = St->getBasePtr();
21856
21857     // Perform one or more big stores into memory.
21858     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21859       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21860                                    StoreType, ShuffWide,
21861                                    DAG.getIntPtrConstant(i));
21862       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21863                                 St->getPointerInfo(), St->isVolatile(),
21864                                 St->isNonTemporal(), St->getAlignment());
21865       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21866       Chains.push_back(Ch);
21867     }
21868
21869     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21870   }
21871
21872   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21873   // the FP state in cases where an emms may be missing.
21874   // A preferable solution to the general problem is to figure out the right
21875   // places to insert EMMS.  This qualifies as a quick hack.
21876
21877   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21878   if (VT.getSizeInBits() != 64)
21879     return SDValue();
21880
21881   const Function *F = DAG.getMachineFunction().getFunction();
21882   bool NoImplicitFloatOps = F->getAttributes().
21883     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21884   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21885                      && Subtarget->hasSSE2();
21886   if ((VT.isVector() ||
21887        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21888       isa<LoadSDNode>(St->getValue()) &&
21889       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21890       St->getChain().hasOneUse() && !St->isVolatile()) {
21891     SDNode* LdVal = St->getValue().getNode();
21892     LoadSDNode *Ld = nullptr;
21893     int TokenFactorIndex = -1;
21894     SmallVector<SDValue, 8> Ops;
21895     SDNode* ChainVal = St->getChain().getNode();
21896     // Must be a store of a load.  We currently handle two cases:  the load
21897     // is a direct child, and it's under an intervening TokenFactor.  It is
21898     // possible to dig deeper under nested TokenFactors.
21899     if (ChainVal == LdVal)
21900       Ld = cast<LoadSDNode>(St->getChain());
21901     else if (St->getValue().hasOneUse() &&
21902              ChainVal->getOpcode() == ISD::TokenFactor) {
21903       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21904         if (ChainVal->getOperand(i).getNode() == LdVal) {
21905           TokenFactorIndex = i;
21906           Ld = cast<LoadSDNode>(St->getValue());
21907         } else
21908           Ops.push_back(ChainVal->getOperand(i));
21909       }
21910     }
21911
21912     if (!Ld || !ISD::isNormalLoad(Ld))
21913       return SDValue();
21914
21915     // If this is not the MMX case, i.e. we are just turning i64 load/store
21916     // into f64 load/store, avoid the transformation if there are multiple
21917     // uses of the loaded value.
21918     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21919       return SDValue();
21920
21921     SDLoc LdDL(Ld);
21922     SDLoc StDL(N);
21923     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21924     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21925     // pair instead.
21926     if (Subtarget->is64Bit() || F64IsLegal) {
21927       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21928       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21929                                   Ld->getPointerInfo(), Ld->isVolatile(),
21930                                   Ld->isNonTemporal(), Ld->isInvariant(),
21931                                   Ld->getAlignment());
21932       SDValue NewChain = NewLd.getValue(1);
21933       if (TokenFactorIndex != -1) {
21934         Ops.push_back(NewChain);
21935         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21936       }
21937       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21938                           St->getPointerInfo(),
21939                           St->isVolatile(), St->isNonTemporal(),
21940                           St->getAlignment());
21941     }
21942
21943     // Otherwise, lower to two pairs of 32-bit loads / stores.
21944     SDValue LoAddr = Ld->getBasePtr();
21945     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21946                                  DAG.getConstant(4, MVT::i32));
21947
21948     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21949                                Ld->getPointerInfo(),
21950                                Ld->isVolatile(), Ld->isNonTemporal(),
21951                                Ld->isInvariant(), Ld->getAlignment());
21952     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21953                                Ld->getPointerInfo().getWithOffset(4),
21954                                Ld->isVolatile(), Ld->isNonTemporal(),
21955                                Ld->isInvariant(),
21956                                MinAlign(Ld->getAlignment(), 4));
21957
21958     SDValue NewChain = LoLd.getValue(1);
21959     if (TokenFactorIndex != -1) {
21960       Ops.push_back(LoLd);
21961       Ops.push_back(HiLd);
21962       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21963     }
21964
21965     LoAddr = St->getBasePtr();
21966     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21967                          DAG.getConstant(4, MVT::i32));
21968
21969     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21970                                 St->getPointerInfo(),
21971                                 St->isVolatile(), St->isNonTemporal(),
21972                                 St->getAlignment());
21973     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21974                                 St->getPointerInfo().getWithOffset(4),
21975                                 St->isVolatile(),
21976                                 St->isNonTemporal(),
21977                                 MinAlign(St->getAlignment(), 4));
21978     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21979   }
21980   return SDValue();
21981 }
21982
21983 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21984 /// and return the operands for the horizontal operation in LHS and RHS.  A
21985 /// horizontal operation performs the binary operation on successive elements
21986 /// of its first operand, then on successive elements of its second operand,
21987 /// returning the resulting values in a vector.  For example, if
21988 ///   A = < float a0, float a1, float a2, float a3 >
21989 /// and
21990 ///   B = < float b0, float b1, float b2, float b3 >
21991 /// then the result of doing a horizontal operation on A and B is
21992 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21993 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21994 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21995 /// set to A, RHS to B, and the routine returns 'true'.
21996 /// Note that the binary operation should have the property that if one of the
21997 /// operands is UNDEF then the result is UNDEF.
21998 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21999   // Look for the following pattern: if
22000   //   A = < float a0, float a1, float a2, float a3 >
22001   //   B = < float b0, float b1, float b2, float b3 >
22002   // and
22003   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22004   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22005   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22006   // which is A horizontal-op B.
22007
22008   // At least one of the operands should be a vector shuffle.
22009   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22010       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22011     return false;
22012
22013   MVT VT = LHS.getSimpleValueType();
22014
22015   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22016          "Unsupported vector type for horizontal add/sub");
22017
22018   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22019   // operate independently on 128-bit lanes.
22020   unsigned NumElts = VT.getVectorNumElements();
22021   unsigned NumLanes = VT.getSizeInBits()/128;
22022   unsigned NumLaneElts = NumElts / NumLanes;
22023   assert((NumLaneElts % 2 == 0) &&
22024          "Vector type should have an even number of elements in each lane");
22025   unsigned HalfLaneElts = NumLaneElts/2;
22026
22027   // View LHS in the form
22028   //   LHS = VECTOR_SHUFFLE A, B, LMask
22029   // If LHS is not a shuffle then pretend it is the shuffle
22030   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22031   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22032   // type VT.
22033   SDValue A, B;
22034   SmallVector<int, 16> LMask(NumElts);
22035   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22036     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22037       A = LHS.getOperand(0);
22038     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22039       B = LHS.getOperand(1);
22040     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22041     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22042   } else {
22043     if (LHS.getOpcode() != ISD::UNDEF)
22044       A = LHS;
22045     for (unsigned i = 0; i != NumElts; ++i)
22046       LMask[i] = i;
22047   }
22048
22049   // Likewise, view RHS in the form
22050   //   RHS = VECTOR_SHUFFLE C, D, RMask
22051   SDValue C, D;
22052   SmallVector<int, 16> RMask(NumElts);
22053   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22054     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22055       C = RHS.getOperand(0);
22056     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22057       D = RHS.getOperand(1);
22058     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22059     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22060   } else {
22061     if (RHS.getOpcode() != ISD::UNDEF)
22062       C = RHS;
22063     for (unsigned i = 0; i != NumElts; ++i)
22064       RMask[i] = i;
22065   }
22066
22067   // Check that the shuffles are both shuffling the same vectors.
22068   if (!(A == C && B == D) && !(A == D && B == C))
22069     return false;
22070
22071   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22072   if (!A.getNode() && !B.getNode())
22073     return false;
22074
22075   // If A and B occur in reverse order in RHS, then "swap" them (which means
22076   // rewriting the mask).
22077   if (A != C)
22078     CommuteVectorShuffleMask(RMask, NumElts);
22079
22080   // At this point LHS and RHS are equivalent to
22081   //   LHS = VECTOR_SHUFFLE A, B, LMask
22082   //   RHS = VECTOR_SHUFFLE A, B, RMask
22083   // Check that the masks correspond to performing a horizontal operation.
22084   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22085     for (unsigned i = 0; i != NumLaneElts; ++i) {
22086       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22087
22088       // Ignore any UNDEF components.
22089       if (LIdx < 0 || RIdx < 0 ||
22090           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22091           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22092         continue;
22093
22094       // Check that successive elements are being operated on.  If not, this is
22095       // not a horizontal operation.
22096       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22097       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22098       if (!(LIdx == Index && RIdx == Index + 1) &&
22099           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22100         return false;
22101     }
22102   }
22103
22104   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22105   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22106   return true;
22107 }
22108
22109 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22110 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22111                                   const X86Subtarget *Subtarget) {
22112   EVT VT = N->getValueType(0);
22113   SDValue LHS = N->getOperand(0);
22114   SDValue RHS = N->getOperand(1);
22115
22116   // Try to synthesize horizontal adds from adds of shuffles.
22117   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22118        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22119       isHorizontalBinOp(LHS, RHS, true))
22120     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22121   return SDValue();
22122 }
22123
22124 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22125 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22126                                   const X86Subtarget *Subtarget) {
22127   EVT VT = N->getValueType(0);
22128   SDValue LHS = N->getOperand(0);
22129   SDValue RHS = N->getOperand(1);
22130
22131   // Try to synthesize horizontal subs from subs of shuffles.
22132   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22133        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22134       isHorizontalBinOp(LHS, RHS, false))
22135     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22136   return SDValue();
22137 }
22138
22139 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22140 /// X86ISD::FXOR nodes.
22141 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22142   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22143   // F[X]OR(0.0, x) -> x
22144   // F[X]OR(x, 0.0) -> x
22145   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22146     if (C->getValueAPF().isPosZero())
22147       return N->getOperand(1);
22148   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22149     if (C->getValueAPF().isPosZero())
22150       return N->getOperand(0);
22151   return SDValue();
22152 }
22153
22154 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22155 /// X86ISD::FMAX nodes.
22156 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22157   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22158
22159   // Only perform optimizations if UnsafeMath is used.
22160   if (!DAG.getTarget().Options.UnsafeFPMath)
22161     return SDValue();
22162
22163   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22164   // into FMINC and FMAXC, which are Commutative operations.
22165   unsigned NewOp = 0;
22166   switch (N->getOpcode()) {
22167     default: llvm_unreachable("unknown opcode");
22168     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22169     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22170   }
22171
22172   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22173                      N->getOperand(0), N->getOperand(1));
22174 }
22175
22176 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22177 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22178   // FAND(0.0, x) -> 0.0
22179   // FAND(x, 0.0) -> 0.0
22180   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22181     if (C->getValueAPF().isPosZero())
22182       return N->getOperand(0);
22183   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22184     if (C->getValueAPF().isPosZero())
22185       return N->getOperand(1);
22186   return SDValue();
22187 }
22188
22189 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22190 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22191   // FANDN(x, 0.0) -> 0.0
22192   // FANDN(0.0, x) -> x
22193   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22194     if (C->getValueAPF().isPosZero())
22195       return N->getOperand(1);
22196   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22197     if (C->getValueAPF().isPosZero())
22198       return N->getOperand(1);
22199   return SDValue();
22200 }
22201
22202 static SDValue PerformBTCombine(SDNode *N,
22203                                 SelectionDAG &DAG,
22204                                 TargetLowering::DAGCombinerInfo &DCI) {
22205   // BT ignores high bits in the bit index operand.
22206   SDValue Op1 = N->getOperand(1);
22207   if (Op1.hasOneUse()) {
22208     unsigned BitWidth = Op1.getValueSizeInBits();
22209     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22210     APInt KnownZero, KnownOne;
22211     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22212                                           !DCI.isBeforeLegalizeOps());
22213     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22214     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22215         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22216       DCI.CommitTargetLoweringOpt(TLO);
22217   }
22218   return SDValue();
22219 }
22220
22221 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22222   SDValue Op = N->getOperand(0);
22223   if (Op.getOpcode() == ISD::BITCAST)
22224     Op = Op.getOperand(0);
22225   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22226   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22227       VT.getVectorElementType().getSizeInBits() ==
22228       OpVT.getVectorElementType().getSizeInBits()) {
22229     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22230   }
22231   return SDValue();
22232 }
22233
22234 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22235                                                const X86Subtarget *Subtarget) {
22236   EVT VT = N->getValueType(0);
22237   if (!VT.isVector())
22238     return SDValue();
22239
22240   SDValue N0 = N->getOperand(0);
22241   SDValue N1 = N->getOperand(1);
22242   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22243   SDLoc dl(N);
22244
22245   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22246   // both SSE and AVX2 since there is no sign-extended shift right
22247   // operation on a vector with 64-bit elements.
22248   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22249   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22250   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22251       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22252     SDValue N00 = N0.getOperand(0);
22253
22254     // EXTLOAD has a better solution on AVX2,
22255     // it may be replaced with X86ISD::VSEXT node.
22256     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22257       if (!ISD::isNormalLoad(N00.getNode()))
22258         return SDValue();
22259
22260     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22261         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22262                                   N00, N1);
22263       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22264     }
22265   }
22266   return SDValue();
22267 }
22268
22269 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22270                                   TargetLowering::DAGCombinerInfo &DCI,
22271                                   const X86Subtarget *Subtarget) {
22272   if (!DCI.isBeforeLegalizeOps())
22273     return SDValue();
22274
22275   if (!Subtarget->hasFp256())
22276     return SDValue();
22277
22278   EVT VT = N->getValueType(0);
22279   if (VT.isVector() && VT.getSizeInBits() == 256) {
22280     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22281     if (R.getNode())
22282       return R;
22283   }
22284
22285   return SDValue();
22286 }
22287
22288 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22289                                  const X86Subtarget* Subtarget) {
22290   SDLoc dl(N);
22291   EVT VT = N->getValueType(0);
22292
22293   // Let legalize expand this if it isn't a legal type yet.
22294   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22295     return SDValue();
22296
22297   EVT ScalarVT = VT.getScalarType();
22298   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22299       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22300     return SDValue();
22301
22302   SDValue A = N->getOperand(0);
22303   SDValue B = N->getOperand(1);
22304   SDValue C = N->getOperand(2);
22305
22306   bool NegA = (A.getOpcode() == ISD::FNEG);
22307   bool NegB = (B.getOpcode() == ISD::FNEG);
22308   bool NegC = (C.getOpcode() == ISD::FNEG);
22309
22310   // Negative multiplication when NegA xor NegB
22311   bool NegMul = (NegA != NegB);
22312   if (NegA)
22313     A = A.getOperand(0);
22314   if (NegB)
22315     B = B.getOperand(0);
22316   if (NegC)
22317     C = C.getOperand(0);
22318
22319   unsigned Opcode;
22320   if (!NegMul)
22321     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22322   else
22323     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22324
22325   return DAG.getNode(Opcode, dl, VT, A, B, C);
22326 }
22327
22328 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22329                                   TargetLowering::DAGCombinerInfo &DCI,
22330                                   const X86Subtarget *Subtarget) {
22331   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22332   //           (and (i32 x86isd::setcc_carry), 1)
22333   // This eliminates the zext. This transformation is necessary because
22334   // ISD::SETCC is always legalized to i8.
22335   SDLoc dl(N);
22336   SDValue N0 = N->getOperand(0);
22337   EVT VT = N->getValueType(0);
22338
22339   if (N0.getOpcode() == ISD::AND &&
22340       N0.hasOneUse() &&
22341       N0.getOperand(0).hasOneUse()) {
22342     SDValue N00 = N0.getOperand(0);
22343     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22344       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22345       if (!C || C->getZExtValue() != 1)
22346         return SDValue();
22347       return DAG.getNode(ISD::AND, dl, VT,
22348                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22349                                      N00.getOperand(0), N00.getOperand(1)),
22350                          DAG.getConstant(1, VT));
22351     }
22352   }
22353
22354   if (N0.getOpcode() == ISD::TRUNCATE &&
22355       N0.hasOneUse() &&
22356       N0.getOperand(0).hasOneUse()) {
22357     SDValue N00 = N0.getOperand(0);
22358     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22359       return DAG.getNode(ISD::AND, dl, VT,
22360                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22361                                      N00.getOperand(0), N00.getOperand(1)),
22362                          DAG.getConstant(1, VT));
22363     }
22364   }
22365   if (VT.is256BitVector()) {
22366     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22367     if (R.getNode())
22368       return R;
22369   }
22370
22371   return SDValue();
22372 }
22373
22374 // Optimize x == -y --> x+y == 0
22375 //          x != -y --> x+y != 0
22376 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22377                                       const X86Subtarget* Subtarget) {
22378   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22379   SDValue LHS = N->getOperand(0);
22380   SDValue RHS = N->getOperand(1);
22381   EVT VT = N->getValueType(0);
22382   SDLoc DL(N);
22383
22384   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22385     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22386       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22387         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22388                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22389         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22390                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22391       }
22392   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22393     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22394       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22395         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22396                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22397         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22398                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22399       }
22400
22401   if (VT.getScalarType() == MVT::i1) {
22402     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22403       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22404     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22405     if (!IsSEXT0 && !IsVZero0)
22406       return SDValue();
22407     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22408       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22409     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22410
22411     if (!IsSEXT1 && !IsVZero1)
22412       return SDValue();
22413
22414     if (IsSEXT0 && IsVZero1) {
22415       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22416       if (CC == ISD::SETEQ)
22417         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22418       return LHS.getOperand(0);
22419     }
22420     if (IsSEXT1 && IsVZero0) {
22421       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22422       if (CC == ISD::SETEQ)
22423         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22424       return RHS.getOperand(0);
22425     }
22426   }
22427
22428   return SDValue();
22429 }
22430
22431 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22432                                       const X86Subtarget *Subtarget) {
22433   SDLoc dl(N);
22434   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22435   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22436          "X86insertps is only defined for v4x32");
22437
22438   SDValue Ld = N->getOperand(1);
22439   if (MayFoldLoad(Ld)) {
22440     // Extract the countS bits from the immediate so we can get the proper
22441     // address when narrowing the vector load to a specific element.
22442     // When the second source op is a memory address, interps doesn't use
22443     // countS and just gets an f32 from that address.
22444     unsigned DestIndex =
22445         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22446     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22447   } else
22448     return SDValue();
22449
22450   // Create this as a scalar to vector to match the instruction pattern.
22451   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22452   // countS bits are ignored when loading from memory on insertps, which
22453   // means we don't need to explicitly set them to 0.
22454   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22455                      LoadScalarToVector, N->getOperand(2));
22456 }
22457
22458 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22459 // as "sbb reg,reg", since it can be extended without zext and produces
22460 // an all-ones bit which is more useful than 0/1 in some cases.
22461 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22462                                MVT VT) {
22463   if (VT == MVT::i8)
22464     return DAG.getNode(ISD::AND, DL, VT,
22465                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22466                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22467                        DAG.getConstant(1, VT));
22468   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22469   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22470                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22471                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22472 }
22473
22474 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22475 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22476                                    TargetLowering::DAGCombinerInfo &DCI,
22477                                    const X86Subtarget *Subtarget) {
22478   SDLoc DL(N);
22479   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22480   SDValue EFLAGS = N->getOperand(1);
22481
22482   if (CC == X86::COND_A) {
22483     // Try to convert COND_A into COND_B in an attempt to facilitate
22484     // materializing "setb reg".
22485     //
22486     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22487     // cannot take an immediate as its first operand.
22488     //
22489     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22490         EFLAGS.getValueType().isInteger() &&
22491         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22492       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22493                                    EFLAGS.getNode()->getVTList(),
22494                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22495       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22496       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22497     }
22498   }
22499
22500   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22501   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22502   // cases.
22503   if (CC == X86::COND_B)
22504     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22505
22506   SDValue Flags;
22507
22508   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22509   if (Flags.getNode()) {
22510     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22511     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22512   }
22513
22514   return SDValue();
22515 }
22516
22517 // Optimize branch condition evaluation.
22518 //
22519 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22520                                     TargetLowering::DAGCombinerInfo &DCI,
22521                                     const X86Subtarget *Subtarget) {
22522   SDLoc DL(N);
22523   SDValue Chain = N->getOperand(0);
22524   SDValue Dest = N->getOperand(1);
22525   SDValue EFLAGS = N->getOperand(3);
22526   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22527
22528   SDValue Flags;
22529
22530   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22531   if (Flags.getNode()) {
22532     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22533     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22534                        Flags);
22535   }
22536
22537   return SDValue();
22538 }
22539
22540 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22541                                                          SelectionDAG &DAG) {
22542   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22543   // optimize away operation when it's from a constant.
22544   //
22545   // The general transformation is:
22546   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22547   //       AND(VECTOR_CMP(x,y), constant2)
22548   //    constant2 = UNARYOP(constant)
22549
22550   // Early exit if this isn't a vector operation, the operand of the
22551   // unary operation isn't a bitwise AND, or if the sizes of the operations
22552   // aren't the same.
22553   EVT VT = N->getValueType(0);
22554   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22555       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22556       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22557     return SDValue();
22558
22559   // Now check that the other operand of the AND is a constant. We could
22560   // make the transformation for non-constant splats as well, but it's unclear
22561   // that would be a benefit as it would not eliminate any operations, just
22562   // perform one more step in scalar code before moving to the vector unit.
22563   if (BuildVectorSDNode *BV =
22564           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22565     // Bail out if the vector isn't a constant.
22566     if (!BV->isConstant())
22567       return SDValue();
22568
22569     // Everything checks out. Build up the new and improved node.
22570     SDLoc DL(N);
22571     EVT IntVT = BV->getValueType(0);
22572     // Create a new constant of the appropriate type for the transformed
22573     // DAG.
22574     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22575     // The AND node needs bitcasts to/from an integer vector type around it.
22576     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22577     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22578                                  N->getOperand(0)->getOperand(0), MaskConst);
22579     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22580     return Res;
22581   }
22582
22583   return SDValue();
22584 }
22585
22586 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22587                                         const X86TargetLowering *XTLI) {
22588   // First try to optimize away the conversion entirely when it's
22589   // conditionally from a constant. Vectors only.
22590   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22591   if (Res != SDValue())
22592     return Res;
22593
22594   // Now move on to more general possibilities.
22595   SDValue Op0 = N->getOperand(0);
22596   EVT InVT = Op0->getValueType(0);
22597
22598   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22599   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22600     SDLoc dl(N);
22601     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22602     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22603     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22604   }
22605
22606   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22607   // a 32-bit target where SSE doesn't support i64->FP operations.
22608   if (Op0.getOpcode() == ISD::LOAD) {
22609     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22610     EVT VT = Ld->getValueType(0);
22611     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22612         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22613         !XTLI->getSubtarget()->is64Bit() &&
22614         VT == MVT::i64) {
22615       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22616                                           Ld->getChain(), Op0, DAG);
22617       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22618       return FILDChain;
22619     }
22620   }
22621   return SDValue();
22622 }
22623
22624 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22625 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22626                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22627   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22628   // the result is either zero or one (depending on the input carry bit).
22629   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22630   if (X86::isZeroNode(N->getOperand(0)) &&
22631       X86::isZeroNode(N->getOperand(1)) &&
22632       // We don't have a good way to replace an EFLAGS use, so only do this when
22633       // dead right now.
22634       SDValue(N, 1).use_empty()) {
22635     SDLoc DL(N);
22636     EVT VT = N->getValueType(0);
22637     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22638     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22639                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22640                                            DAG.getConstant(X86::COND_B,MVT::i8),
22641                                            N->getOperand(2)),
22642                                DAG.getConstant(1, VT));
22643     return DCI.CombineTo(N, Res1, CarryOut);
22644   }
22645
22646   return SDValue();
22647 }
22648
22649 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22650 //      (add Y, (setne X, 0)) -> sbb -1, Y
22651 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22652 //      (sub (setne X, 0), Y) -> adc -1, Y
22653 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22654   SDLoc DL(N);
22655
22656   // Look through ZExts.
22657   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22658   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22659     return SDValue();
22660
22661   SDValue SetCC = Ext.getOperand(0);
22662   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22663     return SDValue();
22664
22665   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22666   if (CC != X86::COND_E && CC != X86::COND_NE)
22667     return SDValue();
22668
22669   SDValue Cmp = SetCC.getOperand(1);
22670   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22671       !X86::isZeroNode(Cmp.getOperand(1)) ||
22672       !Cmp.getOperand(0).getValueType().isInteger())
22673     return SDValue();
22674
22675   SDValue CmpOp0 = Cmp.getOperand(0);
22676   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22677                                DAG.getConstant(1, CmpOp0.getValueType()));
22678
22679   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22680   if (CC == X86::COND_NE)
22681     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22682                        DL, OtherVal.getValueType(), OtherVal,
22683                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22684   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22685                      DL, OtherVal.getValueType(), OtherVal,
22686                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22687 }
22688
22689 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22690 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22691                                  const X86Subtarget *Subtarget) {
22692   EVT VT = N->getValueType(0);
22693   SDValue Op0 = N->getOperand(0);
22694   SDValue Op1 = N->getOperand(1);
22695
22696   // Try to synthesize horizontal adds from adds of shuffles.
22697   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22698        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22699       isHorizontalBinOp(Op0, Op1, true))
22700     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22701
22702   return OptimizeConditionalInDecrement(N, DAG);
22703 }
22704
22705 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22706                                  const X86Subtarget *Subtarget) {
22707   SDValue Op0 = N->getOperand(0);
22708   SDValue Op1 = N->getOperand(1);
22709
22710   // X86 can't encode an immediate LHS of a sub. See if we can push the
22711   // negation into a preceding instruction.
22712   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22713     // If the RHS of the sub is a XOR with one use and a constant, invert the
22714     // immediate. Then add one to the LHS of the sub so we can turn
22715     // X-Y -> X+~Y+1, saving one register.
22716     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22717         isa<ConstantSDNode>(Op1.getOperand(1))) {
22718       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22719       EVT VT = Op0.getValueType();
22720       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22721                                    Op1.getOperand(0),
22722                                    DAG.getConstant(~XorC, VT));
22723       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22724                          DAG.getConstant(C->getAPIntValue()+1, VT));
22725     }
22726   }
22727
22728   // Try to synthesize horizontal adds from adds of shuffles.
22729   EVT VT = N->getValueType(0);
22730   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22731        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22732       isHorizontalBinOp(Op0, Op1, true))
22733     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22734
22735   return OptimizeConditionalInDecrement(N, DAG);
22736 }
22737
22738 /// performVZEXTCombine - Performs build vector combines
22739 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22740                                         TargetLowering::DAGCombinerInfo &DCI,
22741                                         const X86Subtarget *Subtarget) {
22742   // (vzext (bitcast (vzext (x)) -> (vzext x)
22743   SDValue In = N->getOperand(0);
22744   while (In.getOpcode() == ISD::BITCAST)
22745     In = In.getOperand(0);
22746
22747   if (In.getOpcode() != X86ISD::VZEXT)
22748     return SDValue();
22749
22750   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22751                      In.getOperand(0));
22752 }
22753
22754 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22755                                              DAGCombinerInfo &DCI) const {
22756   SelectionDAG &DAG = DCI.DAG;
22757   switch (N->getOpcode()) {
22758   default: break;
22759   case ISD::EXTRACT_VECTOR_ELT:
22760     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22761   case ISD::VSELECT:
22762   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22763   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22764   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22765   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22766   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22767   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22768   case ISD::SHL:
22769   case ISD::SRA:
22770   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22771   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22772   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22773   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22774   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22775   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22776   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22777   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22778   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22779   case X86ISD::FXOR:
22780   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22781   case X86ISD::FMIN:
22782   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22783   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22784   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22785   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22786   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22787   case ISD::ANY_EXTEND:
22788   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22789   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22790   case ISD::SIGN_EXTEND_INREG:
22791     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22792   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22793   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22794   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22795   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22796   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22797   case X86ISD::SHUFP:       // Handle all target specific shuffles
22798   case X86ISD::PALIGNR:
22799   case X86ISD::UNPCKH:
22800   case X86ISD::UNPCKL:
22801   case X86ISD::MOVHLPS:
22802   case X86ISD::MOVLHPS:
22803   case X86ISD::PSHUFB:
22804   case X86ISD::PSHUFD:
22805   case X86ISD::PSHUFHW:
22806   case X86ISD::PSHUFLW:
22807   case X86ISD::MOVSS:
22808   case X86ISD::MOVSD:
22809   case X86ISD::VPERMILP:
22810   case X86ISD::VPERM2X128:
22811   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22812   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22813   case ISD::INTRINSIC_WO_CHAIN:
22814     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22815   case X86ISD::INSERTPS:
22816     return PerformINSERTPSCombine(N, DAG, Subtarget);
22817   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22818   }
22819
22820   return SDValue();
22821 }
22822
22823 /// isTypeDesirableForOp - Return true if the target has native support for
22824 /// the specified value type and it is 'desirable' to use the type for the
22825 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22826 /// instruction encodings are longer and some i16 instructions are slow.
22827 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22828   if (!isTypeLegal(VT))
22829     return false;
22830   if (VT != MVT::i16)
22831     return true;
22832
22833   switch (Opc) {
22834   default:
22835     return true;
22836   case ISD::LOAD:
22837   case ISD::SIGN_EXTEND:
22838   case ISD::ZERO_EXTEND:
22839   case ISD::ANY_EXTEND:
22840   case ISD::SHL:
22841   case ISD::SRL:
22842   case ISD::SUB:
22843   case ISD::ADD:
22844   case ISD::MUL:
22845   case ISD::AND:
22846   case ISD::OR:
22847   case ISD::XOR:
22848     return false;
22849   }
22850 }
22851
22852 /// IsDesirableToPromoteOp - This method query the target whether it is
22853 /// beneficial for dag combiner to promote the specified node. If true, it
22854 /// should return the desired promotion type by reference.
22855 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22856   EVT VT = Op.getValueType();
22857   if (VT != MVT::i16)
22858     return false;
22859
22860   bool Promote = false;
22861   bool Commute = false;
22862   switch (Op.getOpcode()) {
22863   default: break;
22864   case ISD::LOAD: {
22865     LoadSDNode *LD = cast<LoadSDNode>(Op);
22866     // If the non-extending load has a single use and it's not live out, then it
22867     // might be folded.
22868     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22869                                                      Op.hasOneUse()*/) {
22870       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22871              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22872         // The only case where we'd want to promote LOAD (rather then it being
22873         // promoted as an operand is when it's only use is liveout.
22874         if (UI->getOpcode() != ISD::CopyToReg)
22875           return false;
22876       }
22877     }
22878     Promote = true;
22879     break;
22880   }
22881   case ISD::SIGN_EXTEND:
22882   case ISD::ZERO_EXTEND:
22883   case ISD::ANY_EXTEND:
22884     Promote = true;
22885     break;
22886   case ISD::SHL:
22887   case ISD::SRL: {
22888     SDValue N0 = Op.getOperand(0);
22889     // Look out for (store (shl (load), x)).
22890     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22891       return false;
22892     Promote = true;
22893     break;
22894   }
22895   case ISD::ADD:
22896   case ISD::MUL:
22897   case ISD::AND:
22898   case ISD::OR:
22899   case ISD::XOR:
22900     Commute = true;
22901     // fallthrough
22902   case ISD::SUB: {
22903     SDValue N0 = Op.getOperand(0);
22904     SDValue N1 = Op.getOperand(1);
22905     if (!Commute && MayFoldLoad(N1))
22906       return false;
22907     // Avoid disabling potential load folding opportunities.
22908     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22909       return false;
22910     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22911       return false;
22912     Promote = true;
22913   }
22914   }
22915
22916   PVT = MVT::i32;
22917   return Promote;
22918 }
22919
22920 //===----------------------------------------------------------------------===//
22921 //                           X86 Inline Assembly Support
22922 //===----------------------------------------------------------------------===//
22923
22924 namespace {
22925   // Helper to match a string separated by whitespace.
22926   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22927     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22928
22929     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22930       StringRef piece(*args[i]);
22931       if (!s.startswith(piece)) // Check if the piece matches.
22932         return false;
22933
22934       s = s.substr(piece.size());
22935       StringRef::size_type pos = s.find_first_not_of(" \t");
22936       if (pos == 0) // We matched a prefix.
22937         return false;
22938
22939       s = s.substr(pos);
22940     }
22941
22942     return s.empty();
22943   }
22944   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22945 }
22946
22947 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22948
22949   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22950     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22951         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22952         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22953
22954       if (AsmPieces.size() == 3)
22955         return true;
22956       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22957         return true;
22958     }
22959   }
22960   return false;
22961 }
22962
22963 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22964   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22965
22966   std::string AsmStr = IA->getAsmString();
22967
22968   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22969   if (!Ty || Ty->getBitWidth() % 16 != 0)
22970     return false;
22971
22972   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22973   SmallVector<StringRef, 4> AsmPieces;
22974   SplitString(AsmStr, AsmPieces, ";\n");
22975
22976   switch (AsmPieces.size()) {
22977   default: return false;
22978   case 1:
22979     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22980     // we will turn this bswap into something that will be lowered to logical
22981     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22982     // lower so don't worry about this.
22983     // bswap $0
22984     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22985         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22986         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22987         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22988         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22989         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22990       // No need to check constraints, nothing other than the equivalent of
22991       // "=r,0" would be valid here.
22992       return IntrinsicLowering::LowerToByteSwap(CI);
22993     }
22994
22995     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22996     if (CI->getType()->isIntegerTy(16) &&
22997         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22998         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22999          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23000       AsmPieces.clear();
23001       const std::string &ConstraintsStr = IA->getConstraintString();
23002       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23003       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23004       if (clobbersFlagRegisters(AsmPieces))
23005         return IntrinsicLowering::LowerToByteSwap(CI);
23006     }
23007     break;
23008   case 3:
23009     if (CI->getType()->isIntegerTy(32) &&
23010         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23011         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23012         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23013         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23014       AsmPieces.clear();
23015       const std::string &ConstraintsStr = IA->getConstraintString();
23016       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23017       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23018       if (clobbersFlagRegisters(AsmPieces))
23019         return IntrinsicLowering::LowerToByteSwap(CI);
23020     }
23021
23022     if (CI->getType()->isIntegerTy(64)) {
23023       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23024       if (Constraints.size() >= 2 &&
23025           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23026           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23027         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23028         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23029             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23030             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23031           return IntrinsicLowering::LowerToByteSwap(CI);
23032       }
23033     }
23034     break;
23035   }
23036   return false;
23037 }
23038
23039 /// getConstraintType - Given a constraint letter, return the type of
23040 /// constraint it is for this target.
23041 X86TargetLowering::ConstraintType
23042 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23043   if (Constraint.size() == 1) {
23044     switch (Constraint[0]) {
23045     case 'R':
23046     case 'q':
23047     case 'Q':
23048     case 'f':
23049     case 't':
23050     case 'u':
23051     case 'y':
23052     case 'x':
23053     case 'Y':
23054     case 'l':
23055       return C_RegisterClass;
23056     case 'a':
23057     case 'b':
23058     case 'c':
23059     case 'd':
23060     case 'S':
23061     case 'D':
23062     case 'A':
23063       return C_Register;
23064     case 'I':
23065     case 'J':
23066     case 'K':
23067     case 'L':
23068     case 'M':
23069     case 'N':
23070     case 'G':
23071     case 'C':
23072     case 'e':
23073     case 'Z':
23074       return C_Other;
23075     default:
23076       break;
23077     }
23078   }
23079   return TargetLowering::getConstraintType(Constraint);
23080 }
23081
23082 /// Examine constraint type and operand type and determine a weight value.
23083 /// This object must already have been set up with the operand type
23084 /// and the current alternative constraint selected.
23085 TargetLowering::ConstraintWeight
23086   X86TargetLowering::getSingleConstraintMatchWeight(
23087     AsmOperandInfo &info, const char *constraint) const {
23088   ConstraintWeight weight = CW_Invalid;
23089   Value *CallOperandVal = info.CallOperandVal;
23090     // If we don't have a value, we can't do a match,
23091     // but allow it at the lowest weight.
23092   if (!CallOperandVal)
23093     return CW_Default;
23094   Type *type = CallOperandVal->getType();
23095   // Look at the constraint type.
23096   switch (*constraint) {
23097   default:
23098     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23099   case 'R':
23100   case 'q':
23101   case 'Q':
23102   case 'a':
23103   case 'b':
23104   case 'c':
23105   case 'd':
23106   case 'S':
23107   case 'D':
23108   case 'A':
23109     if (CallOperandVal->getType()->isIntegerTy())
23110       weight = CW_SpecificReg;
23111     break;
23112   case 'f':
23113   case 't':
23114   case 'u':
23115     if (type->isFloatingPointTy())
23116       weight = CW_SpecificReg;
23117     break;
23118   case 'y':
23119     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23120       weight = CW_SpecificReg;
23121     break;
23122   case 'x':
23123   case 'Y':
23124     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23125         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23126       weight = CW_Register;
23127     break;
23128   case 'I':
23129     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23130       if (C->getZExtValue() <= 31)
23131         weight = CW_Constant;
23132     }
23133     break;
23134   case 'J':
23135     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23136       if (C->getZExtValue() <= 63)
23137         weight = CW_Constant;
23138     }
23139     break;
23140   case 'K':
23141     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23142       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23143         weight = CW_Constant;
23144     }
23145     break;
23146   case 'L':
23147     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23148       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23149         weight = CW_Constant;
23150     }
23151     break;
23152   case 'M':
23153     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23154       if (C->getZExtValue() <= 3)
23155         weight = CW_Constant;
23156     }
23157     break;
23158   case 'N':
23159     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23160       if (C->getZExtValue() <= 0xff)
23161         weight = CW_Constant;
23162     }
23163     break;
23164   case 'G':
23165   case 'C':
23166     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23167       weight = CW_Constant;
23168     }
23169     break;
23170   case 'e':
23171     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23172       if ((C->getSExtValue() >= -0x80000000LL) &&
23173           (C->getSExtValue() <= 0x7fffffffLL))
23174         weight = CW_Constant;
23175     }
23176     break;
23177   case 'Z':
23178     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23179       if (C->getZExtValue() <= 0xffffffff)
23180         weight = CW_Constant;
23181     }
23182     break;
23183   }
23184   return weight;
23185 }
23186
23187 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23188 /// with another that has more specific requirements based on the type of the
23189 /// corresponding operand.
23190 const char *X86TargetLowering::
23191 LowerXConstraint(EVT ConstraintVT) const {
23192   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23193   // 'f' like normal targets.
23194   if (ConstraintVT.isFloatingPoint()) {
23195     if (Subtarget->hasSSE2())
23196       return "Y";
23197     if (Subtarget->hasSSE1())
23198       return "x";
23199   }
23200
23201   return TargetLowering::LowerXConstraint(ConstraintVT);
23202 }
23203
23204 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23205 /// vector.  If it is invalid, don't add anything to Ops.
23206 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23207                                                      std::string &Constraint,
23208                                                      std::vector<SDValue>&Ops,
23209                                                      SelectionDAG &DAG) const {
23210   SDValue Result;
23211
23212   // Only support length 1 constraints for now.
23213   if (Constraint.length() > 1) return;
23214
23215   char ConstraintLetter = Constraint[0];
23216   switch (ConstraintLetter) {
23217   default: break;
23218   case 'I':
23219     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23220       if (C->getZExtValue() <= 31) {
23221         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23222         break;
23223       }
23224     }
23225     return;
23226   case 'J':
23227     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23228       if (C->getZExtValue() <= 63) {
23229         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23230         break;
23231       }
23232     }
23233     return;
23234   case 'K':
23235     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23236       if (isInt<8>(C->getSExtValue())) {
23237         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23238         break;
23239       }
23240     }
23241     return;
23242   case 'N':
23243     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23244       if (C->getZExtValue() <= 255) {
23245         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23246         break;
23247       }
23248     }
23249     return;
23250   case 'e': {
23251     // 32-bit signed value
23252     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23253       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23254                                            C->getSExtValue())) {
23255         // Widen to 64 bits here to get it sign extended.
23256         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23257         break;
23258       }
23259     // FIXME gcc accepts some relocatable values here too, but only in certain
23260     // memory models; it's complicated.
23261     }
23262     return;
23263   }
23264   case 'Z': {
23265     // 32-bit unsigned value
23266     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23267       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23268                                            C->getZExtValue())) {
23269         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23270         break;
23271       }
23272     }
23273     // FIXME gcc accepts some relocatable values here too, but only in certain
23274     // memory models; it's complicated.
23275     return;
23276   }
23277   case 'i': {
23278     // Literal immediates are always ok.
23279     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23280       // Widen to 64 bits here to get it sign extended.
23281       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23282       break;
23283     }
23284
23285     // In any sort of PIC mode addresses need to be computed at runtime by
23286     // adding in a register or some sort of table lookup.  These can't
23287     // be used as immediates.
23288     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23289       return;
23290
23291     // If we are in non-pic codegen mode, we allow the address of a global (with
23292     // an optional displacement) to be used with 'i'.
23293     GlobalAddressSDNode *GA = nullptr;
23294     int64_t Offset = 0;
23295
23296     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23297     while (1) {
23298       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23299         Offset += GA->getOffset();
23300         break;
23301       } else if (Op.getOpcode() == ISD::ADD) {
23302         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23303           Offset += C->getZExtValue();
23304           Op = Op.getOperand(0);
23305           continue;
23306         }
23307       } else if (Op.getOpcode() == ISD::SUB) {
23308         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23309           Offset += -C->getZExtValue();
23310           Op = Op.getOperand(0);
23311           continue;
23312         }
23313       }
23314
23315       // Otherwise, this isn't something we can handle, reject it.
23316       return;
23317     }
23318
23319     const GlobalValue *GV = GA->getGlobal();
23320     // If we require an extra load to get this address, as in PIC mode, we
23321     // can't accept it.
23322     if (isGlobalStubReference(
23323             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23324       return;
23325
23326     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23327                                         GA->getValueType(0), Offset);
23328     break;
23329   }
23330   }
23331
23332   if (Result.getNode()) {
23333     Ops.push_back(Result);
23334     return;
23335   }
23336   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23337 }
23338
23339 std::pair<unsigned, const TargetRegisterClass*>
23340 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23341                                                 MVT VT) const {
23342   // First, see if this is a constraint that directly corresponds to an LLVM
23343   // register class.
23344   if (Constraint.size() == 1) {
23345     // GCC Constraint Letters
23346     switch (Constraint[0]) {
23347     default: break;
23348       // TODO: Slight differences here in allocation order and leaving
23349       // RIP in the class. Do they matter any more here than they do
23350       // in the normal allocation?
23351     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23352       if (Subtarget->is64Bit()) {
23353         if (VT == MVT::i32 || VT == MVT::f32)
23354           return std::make_pair(0U, &X86::GR32RegClass);
23355         if (VT == MVT::i16)
23356           return std::make_pair(0U, &X86::GR16RegClass);
23357         if (VT == MVT::i8 || VT == MVT::i1)
23358           return std::make_pair(0U, &X86::GR8RegClass);
23359         if (VT == MVT::i64 || VT == MVT::f64)
23360           return std::make_pair(0U, &X86::GR64RegClass);
23361         break;
23362       }
23363       // 32-bit fallthrough
23364     case 'Q':   // Q_REGS
23365       if (VT == MVT::i32 || VT == MVT::f32)
23366         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23367       if (VT == MVT::i16)
23368         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23369       if (VT == MVT::i8 || VT == MVT::i1)
23370         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23371       if (VT == MVT::i64)
23372         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23373       break;
23374     case 'r':   // GENERAL_REGS
23375     case 'l':   // INDEX_REGS
23376       if (VT == MVT::i8 || VT == MVT::i1)
23377         return std::make_pair(0U, &X86::GR8RegClass);
23378       if (VT == MVT::i16)
23379         return std::make_pair(0U, &X86::GR16RegClass);
23380       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23381         return std::make_pair(0U, &X86::GR32RegClass);
23382       return std::make_pair(0U, &X86::GR64RegClass);
23383     case 'R':   // LEGACY_REGS
23384       if (VT == MVT::i8 || VT == MVT::i1)
23385         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23386       if (VT == MVT::i16)
23387         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23388       if (VT == MVT::i32 || !Subtarget->is64Bit())
23389         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23390       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23391     case 'f':  // FP Stack registers.
23392       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23393       // value to the correct fpstack register class.
23394       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23395         return std::make_pair(0U, &X86::RFP32RegClass);
23396       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23397         return std::make_pair(0U, &X86::RFP64RegClass);
23398       return std::make_pair(0U, &X86::RFP80RegClass);
23399     case 'y':   // MMX_REGS if MMX allowed.
23400       if (!Subtarget->hasMMX()) break;
23401       return std::make_pair(0U, &X86::VR64RegClass);
23402     case 'Y':   // SSE_REGS if SSE2 allowed
23403       if (!Subtarget->hasSSE2()) break;
23404       // FALL THROUGH.
23405     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23406       if (!Subtarget->hasSSE1()) break;
23407
23408       switch (VT.SimpleTy) {
23409       default: break;
23410       // Scalar SSE types.
23411       case MVT::f32:
23412       case MVT::i32:
23413         return std::make_pair(0U, &X86::FR32RegClass);
23414       case MVT::f64:
23415       case MVT::i64:
23416         return std::make_pair(0U, &X86::FR64RegClass);
23417       // Vector types.
23418       case MVT::v16i8:
23419       case MVT::v8i16:
23420       case MVT::v4i32:
23421       case MVT::v2i64:
23422       case MVT::v4f32:
23423       case MVT::v2f64:
23424         return std::make_pair(0U, &X86::VR128RegClass);
23425       // AVX types.
23426       case MVT::v32i8:
23427       case MVT::v16i16:
23428       case MVT::v8i32:
23429       case MVT::v4i64:
23430       case MVT::v8f32:
23431       case MVT::v4f64:
23432         return std::make_pair(0U, &X86::VR256RegClass);
23433       case MVT::v8f64:
23434       case MVT::v16f32:
23435       case MVT::v16i32:
23436       case MVT::v8i64:
23437         return std::make_pair(0U, &X86::VR512RegClass);
23438       }
23439       break;
23440     }
23441   }
23442
23443   // Use the default implementation in TargetLowering to convert the register
23444   // constraint into a member of a register class.
23445   std::pair<unsigned, const TargetRegisterClass*> Res;
23446   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23447
23448   // Not found as a standard register?
23449   if (!Res.second) {
23450     // Map st(0) -> st(7) -> ST0
23451     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23452         tolower(Constraint[1]) == 's' &&
23453         tolower(Constraint[2]) == 't' &&
23454         Constraint[3] == '(' &&
23455         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23456         Constraint[5] == ')' &&
23457         Constraint[6] == '}') {
23458
23459       Res.first = X86::FP0+Constraint[4]-'0';
23460       Res.second = &X86::RFP80RegClass;
23461       return Res;
23462     }
23463
23464     // GCC allows "st(0)" to be called just plain "st".
23465     if (StringRef("{st}").equals_lower(Constraint)) {
23466       Res.first = X86::FP0;
23467       Res.second = &X86::RFP80RegClass;
23468       return Res;
23469     }
23470
23471     // flags -> EFLAGS
23472     if (StringRef("{flags}").equals_lower(Constraint)) {
23473       Res.first = X86::EFLAGS;
23474       Res.second = &X86::CCRRegClass;
23475       return Res;
23476     }
23477
23478     // 'A' means EAX + EDX.
23479     if (Constraint == "A") {
23480       Res.first = X86::EAX;
23481       Res.second = &X86::GR32_ADRegClass;
23482       return Res;
23483     }
23484     return Res;
23485   }
23486
23487   // Otherwise, check to see if this is a register class of the wrong value
23488   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23489   // turn into {ax},{dx}.
23490   if (Res.second->hasType(VT))
23491     return Res;   // Correct type already, nothing to do.
23492
23493   // All of the single-register GCC register classes map their values onto
23494   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23495   // really want an 8-bit or 32-bit register, map to the appropriate register
23496   // class and return the appropriate register.
23497   if (Res.second == &X86::GR16RegClass) {
23498     if (VT == MVT::i8 || VT == MVT::i1) {
23499       unsigned DestReg = 0;
23500       switch (Res.first) {
23501       default: break;
23502       case X86::AX: DestReg = X86::AL; break;
23503       case X86::DX: DestReg = X86::DL; break;
23504       case X86::CX: DestReg = X86::CL; break;
23505       case X86::BX: DestReg = X86::BL; break;
23506       }
23507       if (DestReg) {
23508         Res.first = DestReg;
23509         Res.second = &X86::GR8RegClass;
23510       }
23511     } else if (VT == MVT::i32 || VT == MVT::f32) {
23512       unsigned DestReg = 0;
23513       switch (Res.first) {
23514       default: break;
23515       case X86::AX: DestReg = X86::EAX; break;
23516       case X86::DX: DestReg = X86::EDX; break;
23517       case X86::CX: DestReg = X86::ECX; break;
23518       case X86::BX: DestReg = X86::EBX; break;
23519       case X86::SI: DestReg = X86::ESI; break;
23520       case X86::DI: DestReg = X86::EDI; break;
23521       case X86::BP: DestReg = X86::EBP; break;
23522       case X86::SP: DestReg = X86::ESP; break;
23523       }
23524       if (DestReg) {
23525         Res.first = DestReg;
23526         Res.second = &X86::GR32RegClass;
23527       }
23528     } else if (VT == MVT::i64 || VT == MVT::f64) {
23529       unsigned DestReg = 0;
23530       switch (Res.first) {
23531       default: break;
23532       case X86::AX: DestReg = X86::RAX; break;
23533       case X86::DX: DestReg = X86::RDX; break;
23534       case X86::CX: DestReg = X86::RCX; break;
23535       case X86::BX: DestReg = X86::RBX; break;
23536       case X86::SI: DestReg = X86::RSI; break;
23537       case X86::DI: DestReg = X86::RDI; break;
23538       case X86::BP: DestReg = X86::RBP; break;
23539       case X86::SP: DestReg = X86::RSP; break;
23540       }
23541       if (DestReg) {
23542         Res.first = DestReg;
23543         Res.second = &X86::GR64RegClass;
23544       }
23545     }
23546   } else if (Res.second == &X86::FR32RegClass ||
23547              Res.second == &X86::FR64RegClass ||
23548              Res.second == &X86::VR128RegClass ||
23549              Res.second == &X86::VR256RegClass ||
23550              Res.second == &X86::FR32XRegClass ||
23551              Res.second == &X86::FR64XRegClass ||
23552              Res.second == &X86::VR128XRegClass ||
23553              Res.second == &X86::VR256XRegClass ||
23554              Res.second == &X86::VR512RegClass) {
23555     // Handle references to XMM physical registers that got mapped into the
23556     // wrong class.  This can happen with constraints like {xmm0} where the
23557     // target independent register mapper will just pick the first match it can
23558     // find, ignoring the required type.
23559
23560     if (VT == MVT::f32 || VT == MVT::i32)
23561       Res.second = &X86::FR32RegClass;
23562     else if (VT == MVT::f64 || VT == MVT::i64)
23563       Res.second = &X86::FR64RegClass;
23564     else if (X86::VR128RegClass.hasType(VT))
23565       Res.second = &X86::VR128RegClass;
23566     else if (X86::VR256RegClass.hasType(VT))
23567       Res.second = &X86::VR256RegClass;
23568     else if (X86::VR512RegClass.hasType(VT))
23569       Res.second = &X86::VR512RegClass;
23570   }
23571
23572   return Res;
23573 }
23574
23575 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23576                                             Type *Ty) const {
23577   // Scaling factors are not free at all.
23578   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23579   // will take 2 allocations in the out of order engine instead of 1
23580   // for plain addressing mode, i.e. inst (reg1).
23581   // E.g.,
23582   // vaddps (%rsi,%drx), %ymm0, %ymm1
23583   // Requires two allocations (one for the load, one for the computation)
23584   // whereas:
23585   // vaddps (%rsi), %ymm0, %ymm1
23586   // Requires just 1 allocation, i.e., freeing allocations for other operations
23587   // and having less micro operations to execute.
23588   //
23589   // For some X86 architectures, this is even worse because for instance for
23590   // stores, the complex addressing mode forces the instruction to use the
23591   // "load" ports instead of the dedicated "store" port.
23592   // E.g., on Haswell:
23593   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23594   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23595   if (isLegalAddressingMode(AM, Ty))
23596     // Scale represents reg2 * scale, thus account for 1
23597     // as soon as we use a second register.
23598     return AM.Scale != 0;
23599   return -1;
23600 }
23601
23602 bool X86TargetLowering::isTargetFTOL() const {
23603   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23604 }