Verifier: Don't reject varargs callee cleanup functions
[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 mean 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     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1027
1028     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1029     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1030     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1031     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1032     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1033     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1034
1035     if (Subtarget->is64Bit()) {
1036       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1037       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1038     }
1039
1040     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1041     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1042       MVT VT = (MVT::SimpleValueType)i;
1043
1044       // Do not attempt to promote non-128-bit vectors
1045       if (!VT.is128BitVector())
1046         continue;
1047
1048       setOperationAction(ISD::AND,    VT, Promote);
1049       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1050       setOperationAction(ISD::OR,     VT, Promote);
1051       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1052       setOperationAction(ISD::XOR,    VT, Promote);
1053       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1054       setOperationAction(ISD::LOAD,   VT, Promote);
1055       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1056       setOperationAction(ISD::SELECT, VT, Promote);
1057       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1058     }
1059
1060     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1061
1062     // Custom lower v2i64 and v2f64 selects.
1063     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1064     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1065     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1066     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1067
1068     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1069     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1070
1071     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1073     // As there is no 64-bit GPR available, we need build a special custom
1074     // sequence to convert from v2i32 to v2f32.
1075     if (!Subtarget->is64Bit())
1076       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1077
1078     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1079     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1080
1081     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1082
1083     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1084     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1086   }
1087
1088   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1089     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1090     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1091     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1094     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1095     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1096     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1099
1100     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1101     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1102     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1105     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1106     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1107     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1110
1111     // FIXME: Do we need to handle scalar-to-vector here?
1112     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1113
1114     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1115     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1119     // There is no BLENDI for byte vectors. We don't need to custom lower
1120     // some vselects for now.
1121     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1122
1123     // SSE41 brings specific instructions for doing vector sign extend even in
1124     // cases where we don't have SRA.
1125     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1128
1129     // i8 and i16 vectors are custom because the source register and source
1130     // source memory operand types are not the same width.  f32 vectors are
1131     // custom since the immediate controlling the insert encodes additional
1132     // information.
1133     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1137
1138     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1142
1143     // FIXME: these should be Legal, but that's only for the case where
1144     // the index is constant.  For now custom expand to deal with that.
1145     if (Subtarget->is64Bit()) {
1146       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1147       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1148     }
1149   }
1150
1151   if (Subtarget->hasSSE2()) {
1152     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1153     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1154
1155     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1156     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1157
1158     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1159     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1160
1161     // In the customized shift lowering, the legal cases in AVX2 will be
1162     // recognized.
1163     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1164     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1165
1166     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1167     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1168
1169     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1170   }
1171
1172   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1173     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1174     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1175     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1179
1180     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1181     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1183
1184     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1185     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1189     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1190     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1195     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1196
1197     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1198     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1202     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1203     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1208     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1209
1210     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1211     // even though v8i16 is a legal type.
1212     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1213     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1215
1216     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1218     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1219
1220     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1222
1223     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1224
1225     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1226     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1227
1228     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1229     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1230
1231     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1232     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1233
1234     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1235     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1238
1239     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1240     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1242
1243     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1244     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1247
1248     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1251     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1254     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1257     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1260
1261     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1262       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1263       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1268     }
1269
1270     if (Subtarget->hasInt256()) {
1271       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1272       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1275
1276       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1277       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1280
1281       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1282       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1283       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1284       // Don't lower v32i8 because there is no 128-bit byte mul
1285
1286       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1287       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1289       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1290
1291       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1292       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1293     } else {
1294       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1295       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1298
1299       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1300       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1303
1304       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1305       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1307       // Don't lower v32i8 because there is no 128-bit byte mul
1308     }
1309
1310     // In the customized shift lowering, the legal cases in AVX2 will be
1311     // recognized.
1312     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1313     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1314
1315     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1316     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1317
1318     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1319
1320     // Custom lower several nodes for 256-bit types.
1321     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1322              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1323       MVT VT = (MVT::SimpleValueType)i;
1324
1325       // Extract subvector is special because the value type
1326       // (result) is 128-bit but the source is 256-bit wide.
1327       if (VT.is128BitVector())
1328         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1329
1330       // Do not attempt to custom lower other non-256-bit vectors
1331       if (!VT.is256BitVector())
1332         continue;
1333
1334       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1335       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1336       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1337       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1338       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1339       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1340       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1341     }
1342
1343     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1344     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1345       MVT VT = (MVT::SimpleValueType)i;
1346
1347       // Do not attempt to promote non-256-bit vectors
1348       if (!VT.is256BitVector())
1349         continue;
1350
1351       setOperationAction(ISD::AND,    VT, Promote);
1352       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1353       setOperationAction(ISD::OR,     VT, Promote);
1354       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1355       setOperationAction(ISD::XOR,    VT, Promote);
1356       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1357       setOperationAction(ISD::LOAD,   VT, Promote);
1358       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1359       setOperationAction(ISD::SELECT, VT, Promote);
1360       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1361     }
1362   }
1363
1364   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1365     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1366     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1369
1370     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1371     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1372     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1373
1374     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1375     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1376     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1377     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1378     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1379     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1380     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1385
1386     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1387     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1391     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1392
1393     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1394     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1398     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1399     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1400     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1401
1402     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1403     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1405     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1406     if (Subtarget->is64Bit()) {
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1408       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1411     }
1412     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1413     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1416     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1417     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1420     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1421     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1422
1423     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1424     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1429     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1431     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1436
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1443
1444     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1445     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1446
1447     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1448
1449     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1451     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1453     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1455     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1458
1459     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1461
1462     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1463     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1464
1465     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1468     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1469
1470     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1474     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1475
1476     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1477     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1478     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1480     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1481     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1482
1483     if (Subtarget->hasCDI()) {
1484       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1485       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1486     }
1487
1488     // Custom lower several nodes.
1489     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1490              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1491       MVT VT = (MVT::SimpleValueType)i;
1492
1493       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1494       // Extract subvector is special because the value type
1495       // (result) is 256/128-bit but the source is 512-bit wide.
1496       if (VT.is128BitVector() || VT.is256BitVector())
1497         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1498
1499       if (VT.getVectorElementType() == MVT::i1)
1500         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1501
1502       // Do not attempt to custom lower other non-512-bit vectors
1503       if (!VT.is512BitVector())
1504         continue;
1505
1506       if ( EltSize >= 32) {
1507         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1508         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1509         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1510         setOperationAction(ISD::VSELECT,             VT, Legal);
1511         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1512         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1513         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1514       }
1515     }
1516     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1517       MVT VT = (MVT::SimpleValueType)i;
1518
1519       // Do not attempt to promote non-256-bit vectors
1520       if (!VT.is512BitVector())
1521         continue;
1522
1523       setOperationAction(ISD::SELECT, VT, Promote);
1524       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1525     }
1526   }// has  AVX-512
1527
1528   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1529     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1530     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1531
1532     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1533     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1534
1535     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1536     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1537     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1538     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1539
1540     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1541       const MVT VT = (MVT::SimpleValueType)i;
1542
1543       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1544
1545       // Do not attempt to promote non-256-bit vectors
1546       if (!VT.is512BitVector())
1547         continue;
1548
1549       if ( EltSize < 32) {
1550         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1551         setOperationAction(ISD::VSELECT,             VT, Legal);
1552       }
1553     }
1554   }
1555
1556   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1557     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1558     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1559
1560     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1561     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1562   }
1563
1564   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1565   // of this type with custom code.
1566   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1567            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1568     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1569                        Custom);
1570   }
1571
1572   // We want to custom lower some of our intrinsics.
1573   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1574   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1575   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1576   if (!Subtarget->is64Bit())
1577     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1578
1579   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1580   // handle type legalization for these operations here.
1581   //
1582   // FIXME: We really should do custom legalization for addition and
1583   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1584   // than generic legalization for 64-bit multiplication-with-overflow, though.
1585   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1586     // Add/Sub/Mul with overflow operations are custom lowered.
1587     MVT VT = IntVTs[i];
1588     setOperationAction(ISD::SADDO, VT, Custom);
1589     setOperationAction(ISD::UADDO, VT, Custom);
1590     setOperationAction(ISD::SSUBO, VT, Custom);
1591     setOperationAction(ISD::USUBO, VT, Custom);
1592     setOperationAction(ISD::SMULO, VT, Custom);
1593     setOperationAction(ISD::UMULO, VT, Custom);
1594   }
1595
1596   // There are no 8-bit 3-address imul/mul instructions
1597   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1598   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1599
1600   if (!Subtarget->is64Bit()) {
1601     // These libcalls are not available in 32-bit.
1602     setLibcallName(RTLIB::SHL_I128, nullptr);
1603     setLibcallName(RTLIB::SRL_I128, nullptr);
1604     setLibcallName(RTLIB::SRA_I128, nullptr);
1605   }
1606
1607   // Combine sin / cos into one node or libcall if possible.
1608   if (Subtarget->hasSinCos()) {
1609     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1610     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1611     if (Subtarget->isTargetDarwin()) {
1612       // For MacOSX, we don't want to the normal expansion of a libcall to
1613       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1614       // traffic.
1615       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1616       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1617     }
1618   }
1619
1620   if (Subtarget->isTargetWin64()) {
1621     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1622     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1623     setOperationAction(ISD::SREM, MVT::i128, Custom);
1624     setOperationAction(ISD::UREM, MVT::i128, Custom);
1625     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1626     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1627   }
1628
1629   // We have target-specific dag combine patterns for the following nodes:
1630   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1631   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1632   setTargetDAGCombine(ISD::VSELECT);
1633   setTargetDAGCombine(ISD::SELECT);
1634   setTargetDAGCombine(ISD::SHL);
1635   setTargetDAGCombine(ISD::SRA);
1636   setTargetDAGCombine(ISD::SRL);
1637   setTargetDAGCombine(ISD::OR);
1638   setTargetDAGCombine(ISD::AND);
1639   setTargetDAGCombine(ISD::ADD);
1640   setTargetDAGCombine(ISD::FADD);
1641   setTargetDAGCombine(ISD::FSUB);
1642   setTargetDAGCombine(ISD::FMA);
1643   setTargetDAGCombine(ISD::SUB);
1644   setTargetDAGCombine(ISD::LOAD);
1645   setTargetDAGCombine(ISD::STORE);
1646   setTargetDAGCombine(ISD::ZERO_EXTEND);
1647   setTargetDAGCombine(ISD::ANY_EXTEND);
1648   setTargetDAGCombine(ISD::SIGN_EXTEND);
1649   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1650   setTargetDAGCombine(ISD::TRUNCATE);
1651   setTargetDAGCombine(ISD::SINT_TO_FP);
1652   setTargetDAGCombine(ISD::SETCC);
1653   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1654   setTargetDAGCombine(ISD::BUILD_VECTOR);
1655   if (Subtarget->is64Bit())
1656     setTargetDAGCombine(ISD::MUL);
1657   setTargetDAGCombine(ISD::XOR);
1658
1659   computeRegisterProperties();
1660
1661   // On Darwin, -Os means optimize for size without hurting performance,
1662   // do not reduce the limit.
1663   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1664   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1665   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1666   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1667   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1668   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1669   setPrefLoopAlignment(4); // 2^4 bytes.
1670
1671   // Predictable cmov don't hurt on atom because it's in-order.
1672   PredictableSelectIsExpensive = !Subtarget->isAtom();
1673
1674   setPrefFunctionAlignment(4); // 2^4 bytes.
1675
1676   InitIntrinsicTables();
1677 }
1678
1679 // This has so far only been implemented for 64-bit MachO.
1680 bool X86TargetLowering::useLoadStackGuardNode() const {
1681   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1682          Subtarget->is64Bit();
1683 }
1684
1685 TargetLoweringBase::LegalizeTypeAction
1686 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1687   if (ExperimentalVectorWideningLegalization &&
1688       VT.getVectorNumElements() != 1 &&
1689       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1690     return TypeWidenVector;
1691
1692   return TargetLoweringBase::getPreferredVectorAction(VT);
1693 }
1694
1695 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1696   if (!VT.isVector())
1697     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1698
1699   const unsigned NumElts = VT.getVectorNumElements();
1700   const EVT EltVT = VT.getVectorElementType();
1701   if (VT.is512BitVector()) {
1702     if (Subtarget->hasAVX512())
1703       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1704           EltVT == MVT::f32 || EltVT == MVT::f64)
1705         switch(NumElts) {
1706         case  8: return MVT::v8i1;
1707         case 16: return MVT::v16i1;
1708       }
1709     if (Subtarget->hasBWI())
1710       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1711         switch(NumElts) {
1712         case 32: return MVT::v32i1;
1713         case 64: return MVT::v64i1;
1714       }
1715   }
1716
1717   if (VT.is256BitVector() || VT.is128BitVector()) {
1718     if (Subtarget->hasVLX())
1719       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1720           EltVT == MVT::f32 || EltVT == MVT::f64)
1721         switch(NumElts) {
1722         case 2: return MVT::v2i1;
1723         case 4: return MVT::v4i1;
1724         case 8: return MVT::v8i1;
1725       }
1726     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1727       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1728         switch(NumElts) {
1729         case  8: return MVT::v8i1;
1730         case 16: return MVT::v16i1;
1731         case 32: return MVT::v32i1;
1732       }
1733   }
1734
1735   return VT.changeVectorElementTypeToInteger();
1736 }
1737
1738 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1739 /// the desired ByVal argument alignment.
1740 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1741   if (MaxAlign == 16)
1742     return;
1743   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1744     if (VTy->getBitWidth() == 128)
1745       MaxAlign = 16;
1746   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1747     unsigned EltAlign = 0;
1748     getMaxByValAlign(ATy->getElementType(), EltAlign);
1749     if (EltAlign > MaxAlign)
1750       MaxAlign = EltAlign;
1751   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1752     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1753       unsigned EltAlign = 0;
1754       getMaxByValAlign(STy->getElementType(i), EltAlign);
1755       if (EltAlign > MaxAlign)
1756         MaxAlign = EltAlign;
1757       if (MaxAlign == 16)
1758         break;
1759     }
1760   }
1761 }
1762
1763 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1764 /// function arguments in the caller parameter area. For X86, aggregates
1765 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1766 /// are at 4-byte boundaries.
1767 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1768   if (Subtarget->is64Bit()) {
1769     // Max of 8 and alignment of type.
1770     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1771     if (TyAlign > 8)
1772       return TyAlign;
1773     return 8;
1774   }
1775
1776   unsigned Align = 4;
1777   if (Subtarget->hasSSE1())
1778     getMaxByValAlign(Ty, Align);
1779   return Align;
1780 }
1781
1782 /// getOptimalMemOpType - Returns the target specific optimal type for load
1783 /// and store operations as a result of memset, memcpy, and memmove
1784 /// lowering. If DstAlign is zero that means it's safe to destination
1785 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1786 /// means there isn't a need to check it against alignment requirement,
1787 /// probably because the source does not need to be loaded. If 'IsMemset' is
1788 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1789 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1790 /// source is constant so it does not need to be loaded.
1791 /// It returns EVT::Other if the type should be determined using generic
1792 /// target-independent logic.
1793 EVT
1794 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1795                                        unsigned DstAlign, unsigned SrcAlign,
1796                                        bool IsMemset, bool ZeroMemset,
1797                                        bool MemcpyStrSrc,
1798                                        MachineFunction &MF) const {
1799   const Function *F = MF.getFunction();
1800   if ((!IsMemset || ZeroMemset) &&
1801       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1802                                        Attribute::NoImplicitFloat)) {
1803     if (Size >= 16 &&
1804         (Subtarget->isUnalignedMemAccessFast() ||
1805          ((DstAlign == 0 || DstAlign >= 16) &&
1806           (SrcAlign == 0 || SrcAlign >= 16)))) {
1807       if (Size >= 32) {
1808         if (Subtarget->hasInt256())
1809           return MVT::v8i32;
1810         if (Subtarget->hasFp256())
1811           return MVT::v8f32;
1812       }
1813       if (Subtarget->hasSSE2())
1814         return MVT::v4i32;
1815       if (Subtarget->hasSSE1())
1816         return MVT::v4f32;
1817     } else if (!MemcpyStrSrc && Size >= 8 &&
1818                !Subtarget->is64Bit() &&
1819                Subtarget->hasSSE2()) {
1820       // Do not use f64 to lower memcpy if source is string constant. It's
1821       // better to use i32 to avoid the loads.
1822       return MVT::f64;
1823     }
1824   }
1825   if (Subtarget->is64Bit() && Size >= 8)
1826     return MVT::i64;
1827   return MVT::i32;
1828 }
1829
1830 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1831   if (VT == MVT::f32)
1832     return X86ScalarSSEf32;
1833   else if (VT == MVT::f64)
1834     return X86ScalarSSEf64;
1835   return true;
1836 }
1837
1838 bool
1839 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1840                                                   unsigned,
1841                                                   unsigned,
1842                                                   bool *Fast) const {
1843   if (Fast)
1844     *Fast = Subtarget->isUnalignedMemAccessFast();
1845   return true;
1846 }
1847
1848 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1849 /// current function.  The returned value is a member of the
1850 /// MachineJumpTableInfo::JTEntryKind enum.
1851 unsigned X86TargetLowering::getJumpTableEncoding() const {
1852   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1853   // symbol.
1854   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1855       Subtarget->isPICStyleGOT())
1856     return MachineJumpTableInfo::EK_Custom32;
1857
1858   // Otherwise, use the normal jump table encoding heuristics.
1859   return TargetLowering::getJumpTableEncoding();
1860 }
1861
1862 const MCExpr *
1863 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1864                                              const MachineBasicBlock *MBB,
1865                                              unsigned uid,MCContext &Ctx) const{
1866   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1867          Subtarget->isPICStyleGOT());
1868   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1869   // entries.
1870   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1871                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1872 }
1873
1874 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1875 /// jumptable.
1876 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1877                                                     SelectionDAG &DAG) const {
1878   if (!Subtarget->is64Bit())
1879     // This doesn't have SDLoc associated with it, but is not really the
1880     // same as a Register.
1881     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1882   return Table;
1883 }
1884
1885 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1886 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1887 /// MCExpr.
1888 const MCExpr *X86TargetLowering::
1889 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1890                              MCContext &Ctx) const {
1891   // X86-64 uses RIP relative addressing based on the jump table label.
1892   if (Subtarget->isPICStyleRIPRel())
1893     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1894
1895   // Otherwise, the reference is relative to the PIC base.
1896   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1897 }
1898
1899 // FIXME: Why this routine is here? Move to RegInfo!
1900 std::pair<const TargetRegisterClass*, uint8_t>
1901 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1902   const TargetRegisterClass *RRC = nullptr;
1903   uint8_t Cost = 1;
1904   switch (VT.SimpleTy) {
1905   default:
1906     return TargetLowering::findRepresentativeClass(VT);
1907   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1908     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1909     break;
1910   case MVT::x86mmx:
1911     RRC = &X86::VR64RegClass;
1912     break;
1913   case MVT::f32: case MVT::f64:
1914   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1915   case MVT::v4f32: case MVT::v2f64:
1916   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1917   case MVT::v4f64:
1918     RRC = &X86::VR128RegClass;
1919     break;
1920   }
1921   return std::make_pair(RRC, Cost);
1922 }
1923
1924 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1925                                                unsigned &Offset) const {
1926   if (!Subtarget->isTargetLinux())
1927     return false;
1928
1929   if (Subtarget->is64Bit()) {
1930     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1931     Offset = 0x28;
1932     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1933       AddressSpace = 256;
1934     else
1935       AddressSpace = 257;
1936   } else {
1937     // %gs:0x14 on i386
1938     Offset = 0x14;
1939     AddressSpace = 256;
1940   }
1941   return true;
1942 }
1943
1944 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1945                                             unsigned DestAS) const {
1946   assert(SrcAS != DestAS && "Expected different address spaces!");
1947
1948   return SrcAS < 256 && DestAS < 256;
1949 }
1950
1951 //===----------------------------------------------------------------------===//
1952 //               Return Value Calling Convention Implementation
1953 //===----------------------------------------------------------------------===//
1954
1955 #include "X86GenCallingConv.inc"
1956
1957 bool
1958 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1959                                   MachineFunction &MF, bool isVarArg,
1960                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1961                         LLVMContext &Context) const {
1962   SmallVector<CCValAssign, 16> RVLocs;
1963   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1964   return CCInfo.CheckReturn(Outs, RetCC_X86);
1965 }
1966
1967 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1968   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1969   return ScratchRegs;
1970 }
1971
1972 SDValue
1973 X86TargetLowering::LowerReturn(SDValue Chain,
1974                                CallingConv::ID CallConv, bool isVarArg,
1975                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1976                                const SmallVectorImpl<SDValue> &OutVals,
1977                                SDLoc dl, SelectionDAG &DAG) const {
1978   MachineFunction &MF = DAG.getMachineFunction();
1979   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1980
1981   SmallVector<CCValAssign, 16> RVLocs;
1982   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1983   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1984
1985   SDValue Flag;
1986   SmallVector<SDValue, 6> RetOps;
1987   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1988   // Operand #1 = Bytes To Pop
1989   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1990                    MVT::i16));
1991
1992   // Copy the result values into the output registers.
1993   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1994     CCValAssign &VA = RVLocs[i];
1995     assert(VA.isRegLoc() && "Can only return in registers!");
1996     SDValue ValToCopy = OutVals[i];
1997     EVT ValVT = ValToCopy.getValueType();
1998
1999     // Promote values to the appropriate types
2000     if (VA.getLocInfo() == CCValAssign::SExt)
2001       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2002     else if (VA.getLocInfo() == CCValAssign::ZExt)
2003       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2004     else if (VA.getLocInfo() == CCValAssign::AExt)
2005       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2006     else if (VA.getLocInfo() == CCValAssign::BCvt)
2007       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2008
2009     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2010            "Unexpected FP-extend for return value.");  
2011
2012     // If this is x86-64, and we disabled SSE, we can't return FP values,
2013     // or SSE or MMX vectors.
2014     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2015          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2016           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2017       report_fatal_error("SSE register return with SSE disabled");
2018     }
2019     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2020     // llvm-gcc has never done it right and no one has noticed, so this
2021     // should be OK for now.
2022     if (ValVT == MVT::f64 &&
2023         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2024       report_fatal_error("SSE2 register return with SSE2 disabled");
2025
2026     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2027     // the RET instruction and handled by the FP Stackifier.
2028     if (VA.getLocReg() == X86::FP0 ||
2029         VA.getLocReg() == X86::FP1) {
2030       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2031       // change the value to the FP stack register class.
2032       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2033         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2034       RetOps.push_back(ValToCopy);
2035       // Don't emit a copytoreg.
2036       continue;
2037     }
2038
2039     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2040     // which is returned in RAX / RDX.
2041     if (Subtarget->is64Bit()) {
2042       if (ValVT == MVT::x86mmx) {
2043         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2044           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2045           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2046                                   ValToCopy);
2047           // If we don't have SSE2 available, convert to v4f32 so the generated
2048           // register is legal.
2049           if (!Subtarget->hasSSE2())
2050             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2051         }
2052       }
2053     }
2054
2055     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2056     Flag = Chain.getValue(1);
2057     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2058   }
2059
2060   // The x86-64 ABIs require that for returning structs by value we copy
2061   // the sret argument into %rax/%eax (depending on ABI) for the return.
2062   // Win32 requires us to put the sret argument to %eax as well.
2063   // We saved the argument into a virtual register in the entry block,
2064   // so now we copy the value out and into %rax/%eax.
2065   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2066       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2067     MachineFunction &MF = DAG.getMachineFunction();
2068     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2069     unsigned Reg = FuncInfo->getSRetReturnReg();
2070     assert(Reg &&
2071            "SRetReturnReg should have been set in LowerFormalArguments().");
2072     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2073
2074     unsigned RetValReg
2075         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2076           X86::RAX : X86::EAX;
2077     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2078     Flag = Chain.getValue(1);
2079
2080     // RAX/EAX now acts like a return value.
2081     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2082   }
2083
2084   RetOps[0] = Chain;  // Update chain.
2085
2086   // Add the flag if we have it.
2087   if (Flag.getNode())
2088     RetOps.push_back(Flag);
2089
2090   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2091 }
2092
2093 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2094   if (N->getNumValues() != 1)
2095     return false;
2096   if (!N->hasNUsesOfValue(1, 0))
2097     return false;
2098
2099   SDValue TCChain = Chain;
2100   SDNode *Copy = *N->use_begin();
2101   if (Copy->getOpcode() == ISD::CopyToReg) {
2102     // If the copy has a glue operand, we conservatively assume it isn't safe to
2103     // perform a tail call.
2104     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2105       return false;
2106     TCChain = Copy->getOperand(0);
2107   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2108     return false;
2109
2110   bool HasRet = false;
2111   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2112        UI != UE; ++UI) {
2113     if (UI->getOpcode() != X86ISD::RET_FLAG)
2114       return false;
2115     // If we are returning more than one value, we can definitely
2116     // not make a tail call see PR19530
2117     if (UI->getNumOperands() > 4)
2118       return false;
2119     if (UI->getNumOperands() == 4 &&
2120         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2121       return false;
2122     HasRet = true;
2123   }
2124
2125   if (!HasRet)
2126     return false;
2127
2128   Chain = TCChain;
2129   return true;
2130 }
2131
2132 EVT
2133 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2134                                             ISD::NodeType ExtendKind) const {
2135   MVT ReturnMVT;
2136   // TODO: Is this also valid on 32-bit?
2137   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2138     ReturnMVT = MVT::i8;
2139   else
2140     ReturnMVT = MVT::i32;
2141
2142   EVT MinVT = getRegisterType(Context, ReturnMVT);
2143   return VT.bitsLT(MinVT) ? MinVT : VT;
2144 }
2145
2146 /// LowerCallResult - Lower the result values of a call into the
2147 /// appropriate copies out of appropriate physical registers.
2148 ///
2149 SDValue
2150 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2151                                    CallingConv::ID CallConv, bool isVarArg,
2152                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2153                                    SDLoc dl, SelectionDAG &DAG,
2154                                    SmallVectorImpl<SDValue> &InVals) const {
2155
2156   // Assign locations to each value returned by this call.
2157   SmallVector<CCValAssign, 16> RVLocs;
2158   bool Is64Bit = Subtarget->is64Bit();
2159   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2160                  *DAG.getContext());
2161   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2162
2163   // Copy all of the result registers out of their specified physreg.
2164   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2165     CCValAssign &VA = RVLocs[i];
2166     EVT CopyVT = VA.getValVT();
2167
2168     // If this is x86-64, and we disabled SSE, we can't return FP values
2169     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2170         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2171       report_fatal_error("SSE register return with SSE disabled");
2172     }
2173
2174     // If we prefer to use the value in xmm registers, copy it out as f80 and
2175     // use a truncate to move it from fp stack reg to xmm reg.
2176     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2177         isScalarFPTypeInSSEReg(VA.getValVT()))
2178       CopyVT = MVT::f80;
2179
2180     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2181                                CopyVT, InFlag).getValue(1);
2182     SDValue Val = Chain.getValue(0);
2183
2184     if (CopyVT != VA.getValVT())
2185       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2186                         // This truncation won't change the value.
2187                         DAG.getIntPtrConstant(1));
2188
2189     InFlag = Chain.getValue(2);
2190     InVals.push_back(Val);
2191   }
2192
2193   return Chain;
2194 }
2195
2196 //===----------------------------------------------------------------------===//
2197 //                C & StdCall & Fast Calling Convention implementation
2198 //===----------------------------------------------------------------------===//
2199 //  StdCall calling convention seems to be standard for many Windows' API
2200 //  routines and around. It differs from C calling convention just a little:
2201 //  callee should clean up the stack, not caller. Symbols should be also
2202 //  decorated in some fancy way :) It doesn't support any vector arguments.
2203 //  For info on fast calling convention see Fast Calling Convention (tail call)
2204 //  implementation LowerX86_32FastCCCallTo.
2205
2206 /// CallIsStructReturn - Determines whether a call uses struct return
2207 /// semantics.
2208 enum StructReturnType {
2209   NotStructReturn,
2210   RegStructReturn,
2211   StackStructReturn
2212 };
2213 static StructReturnType
2214 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2215   if (Outs.empty())
2216     return NotStructReturn;
2217
2218   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2219   if (!Flags.isSRet())
2220     return NotStructReturn;
2221   if (Flags.isInReg())
2222     return RegStructReturn;
2223   return StackStructReturn;
2224 }
2225
2226 /// ArgsAreStructReturn - Determines whether a function uses struct
2227 /// return semantics.
2228 static StructReturnType
2229 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2230   if (Ins.empty())
2231     return NotStructReturn;
2232
2233   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2234   if (!Flags.isSRet())
2235     return NotStructReturn;
2236   if (Flags.isInReg())
2237     return RegStructReturn;
2238   return StackStructReturn;
2239 }
2240
2241 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2242 /// by "Src" to address "Dst" with size and alignment information specified by
2243 /// the specific parameter attribute. The copy will be passed as a byval
2244 /// function parameter.
2245 static SDValue
2246 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2247                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2248                           SDLoc dl) {
2249   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2250
2251   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2252                        /*isVolatile*/false, /*AlwaysInline=*/true,
2253                        MachinePointerInfo(), MachinePointerInfo());
2254 }
2255
2256 /// IsTailCallConvention - Return true if the calling convention is one that
2257 /// supports tail call optimization.
2258 static bool IsTailCallConvention(CallingConv::ID CC) {
2259   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2260           CC == CallingConv::HiPE);
2261 }
2262
2263 /// \brief Return true if the calling convention is a C calling convention.
2264 static bool IsCCallConvention(CallingConv::ID CC) {
2265   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2266           CC == CallingConv::X86_64_SysV);
2267 }
2268
2269 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2270   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2271     return false;
2272
2273   CallSite CS(CI);
2274   CallingConv::ID CalleeCC = CS.getCallingConv();
2275   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2276     return false;
2277
2278   return true;
2279 }
2280
2281 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2282 /// a tailcall target by changing its ABI.
2283 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2284                                    bool GuaranteedTailCallOpt) {
2285   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2286 }
2287
2288 SDValue
2289 X86TargetLowering::LowerMemArgument(SDValue Chain,
2290                                     CallingConv::ID CallConv,
2291                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2292                                     SDLoc dl, SelectionDAG &DAG,
2293                                     const CCValAssign &VA,
2294                                     MachineFrameInfo *MFI,
2295                                     unsigned i) const {
2296   // Create the nodes corresponding to a load from this parameter slot.
2297   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2298   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2299       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2300   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2301   EVT ValVT;
2302
2303   // If value is passed by pointer we have address passed instead of the value
2304   // itself.
2305   if (VA.getLocInfo() == CCValAssign::Indirect)
2306     ValVT = VA.getLocVT();
2307   else
2308     ValVT = VA.getValVT();
2309
2310   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2311   // changed with more analysis.
2312   // In case of tail call optimization mark all arguments mutable. Since they
2313   // could be overwritten by lowering of arguments in case of a tail call.
2314   if (Flags.isByVal()) {
2315     unsigned Bytes = Flags.getByValSize();
2316     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2317     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2318     return DAG.getFrameIndex(FI, getPointerTy());
2319   } else {
2320     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2321                                     VA.getLocMemOffset(), isImmutable);
2322     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2323     return DAG.getLoad(ValVT, dl, Chain, FIN,
2324                        MachinePointerInfo::getFixedStack(FI),
2325                        false, false, false, 0);
2326   }
2327 }
2328
2329 SDValue
2330 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2331                                         CallingConv::ID CallConv,
2332                                         bool isVarArg,
2333                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2334                                         SDLoc dl,
2335                                         SelectionDAG &DAG,
2336                                         SmallVectorImpl<SDValue> &InVals)
2337                                           const {
2338   MachineFunction &MF = DAG.getMachineFunction();
2339   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2340
2341   const Function* Fn = MF.getFunction();
2342   if (Fn->hasExternalLinkage() &&
2343       Subtarget->isTargetCygMing() &&
2344       Fn->getName() == "main")
2345     FuncInfo->setForceFramePointer(true);
2346
2347   MachineFrameInfo *MFI = MF.getFrameInfo();
2348   bool Is64Bit = Subtarget->is64Bit();
2349   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2350
2351   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2352          "Var args not supported with calling convention fastcc, ghc or hipe");
2353
2354   // Assign locations to all of the incoming arguments.
2355   SmallVector<CCValAssign, 16> ArgLocs;
2356   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2357
2358   // Allocate shadow area for Win64
2359   if (IsWin64)
2360     CCInfo.AllocateStack(32, 8);
2361
2362   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2363
2364   unsigned LastVal = ~0U;
2365   SDValue ArgValue;
2366   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2367     CCValAssign &VA = ArgLocs[i];
2368     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2369     // places.
2370     assert(VA.getValNo() != LastVal &&
2371            "Don't support value assigned to multiple locs yet");
2372     (void)LastVal;
2373     LastVal = VA.getValNo();
2374
2375     if (VA.isRegLoc()) {
2376       EVT RegVT = VA.getLocVT();
2377       const TargetRegisterClass *RC;
2378       if (RegVT == MVT::i32)
2379         RC = &X86::GR32RegClass;
2380       else if (Is64Bit && RegVT == MVT::i64)
2381         RC = &X86::GR64RegClass;
2382       else if (RegVT == MVT::f32)
2383         RC = &X86::FR32RegClass;
2384       else if (RegVT == MVT::f64)
2385         RC = &X86::FR64RegClass;
2386       else if (RegVT.is512BitVector())
2387         RC = &X86::VR512RegClass;
2388       else if (RegVT.is256BitVector())
2389         RC = &X86::VR256RegClass;
2390       else if (RegVT.is128BitVector())
2391         RC = &X86::VR128RegClass;
2392       else if (RegVT == MVT::x86mmx)
2393         RC = &X86::VR64RegClass;
2394       else if (RegVT == MVT::i1)
2395         RC = &X86::VK1RegClass;
2396       else if (RegVT == MVT::v8i1)
2397         RC = &X86::VK8RegClass;
2398       else if (RegVT == MVT::v16i1)
2399         RC = &X86::VK16RegClass;
2400       else if (RegVT == MVT::v32i1)
2401         RC = &X86::VK32RegClass;
2402       else if (RegVT == MVT::v64i1)
2403         RC = &X86::VK64RegClass;
2404       else
2405         llvm_unreachable("Unknown argument type!");
2406
2407       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2408       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2409
2410       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2411       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2412       // right size.
2413       if (VA.getLocInfo() == CCValAssign::SExt)
2414         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2415                                DAG.getValueType(VA.getValVT()));
2416       else if (VA.getLocInfo() == CCValAssign::ZExt)
2417         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2418                                DAG.getValueType(VA.getValVT()));
2419       else if (VA.getLocInfo() == CCValAssign::BCvt)
2420         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2421
2422       if (VA.isExtInLoc()) {
2423         // Handle MMX values passed in XMM regs.
2424         if (RegVT.isVector())
2425           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2426         else
2427           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2428       }
2429     } else {
2430       assert(VA.isMemLoc());
2431       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2432     }
2433
2434     // If value is passed via pointer - do a load.
2435     if (VA.getLocInfo() == CCValAssign::Indirect)
2436       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2437                              MachinePointerInfo(), false, false, false, 0);
2438
2439     InVals.push_back(ArgValue);
2440   }
2441
2442   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2443     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2444       // The x86-64 ABIs require that for returning structs by value we copy
2445       // the sret argument into %rax/%eax (depending on ABI) for the return.
2446       // Win32 requires us to put the sret argument to %eax as well.
2447       // Save the argument into a virtual register so that we can access it
2448       // from the return points.
2449       if (Ins[i].Flags.isSRet()) {
2450         unsigned Reg = FuncInfo->getSRetReturnReg();
2451         if (!Reg) {
2452           MVT PtrTy = getPointerTy();
2453           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2454           FuncInfo->setSRetReturnReg(Reg);
2455         }
2456         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2457         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2458         break;
2459       }
2460     }
2461   }
2462
2463   unsigned StackSize = CCInfo.getNextStackOffset();
2464   // Align stack specially for tail calls.
2465   if (FuncIsMadeTailCallSafe(CallConv,
2466                              MF.getTarget().Options.GuaranteedTailCallOpt))
2467     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2468
2469   // If the function takes variable number of arguments, make a frame index for
2470   // the start of the first vararg value... for expansion of llvm.va_start. We
2471   // can skip this if there are no va_start calls.
2472   if (isVarArg && MFI->hasVAStart()) {
2473     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2474                     CallConv != CallingConv::X86_ThisCall)) {
2475       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2476     }
2477     if (Is64Bit) {
2478       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2479
2480       // FIXME: We should really autogenerate these arrays
2481       static const MCPhysReg GPR64ArgRegsWin64[] = {
2482         X86::RCX, X86::RDX, X86::R8,  X86::R9
2483       };
2484       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2485         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2486       };
2487       static const MCPhysReg XMMArgRegs64Bit[] = {
2488         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2489         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2490       };
2491       const MCPhysReg *GPR64ArgRegs;
2492       unsigned NumXMMRegs = 0;
2493
2494       if (IsWin64) {
2495         // The XMM registers which might contain var arg parameters are shadowed
2496         // in their paired GPR.  So we only need to save the GPR to their home
2497         // slots.
2498         TotalNumIntRegs = 4;
2499         GPR64ArgRegs = GPR64ArgRegsWin64;
2500       } else {
2501         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2502         GPR64ArgRegs = GPR64ArgRegs64Bit;
2503
2504         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2505                                                 TotalNumXMMRegs);
2506       }
2507       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2508                                                        TotalNumIntRegs);
2509
2510       bool NoImplicitFloatOps = Fn->getAttributes().
2511         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2512       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2513              "SSE register cannot be used when SSE is disabled!");
2514       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2515                NoImplicitFloatOps) &&
2516              "SSE register cannot be used when SSE is disabled!");
2517       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2518           !Subtarget->hasSSE1())
2519         // Kernel mode asks for SSE to be disabled, so don't push them
2520         // on the stack.
2521         TotalNumXMMRegs = 0;
2522
2523       if (IsWin64) {
2524         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2525         // Get to the caller-allocated home save location.  Add 8 to account
2526         // for the return address.
2527         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2528         FuncInfo->setRegSaveFrameIndex(
2529           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2530         // Fixup to set vararg frame on shadow area (4 x i64).
2531         if (NumIntRegs < 4)
2532           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2533       } else {
2534         // For X86-64, if there are vararg parameters that are passed via
2535         // registers, then we must store them to their spots on the stack so
2536         // they may be loaded by deferencing the result of va_next.
2537         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2538         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2539         FuncInfo->setRegSaveFrameIndex(
2540           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2541                                false));
2542       }
2543
2544       // Store the integer parameter registers.
2545       SmallVector<SDValue, 8> MemOps;
2546       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2547                                         getPointerTy());
2548       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2549       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2550         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2551                                   DAG.getIntPtrConstant(Offset));
2552         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2553                                      &X86::GR64RegClass);
2554         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2555         SDValue Store =
2556           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2557                        MachinePointerInfo::getFixedStack(
2558                          FuncInfo->getRegSaveFrameIndex(), Offset),
2559                        false, false, 0);
2560         MemOps.push_back(Store);
2561         Offset += 8;
2562       }
2563
2564       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2565         // Now store the XMM (fp + vector) parameter registers.
2566         SmallVector<SDValue, 12> SaveXMMOps;
2567         SaveXMMOps.push_back(Chain);
2568
2569         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2570         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2571         SaveXMMOps.push_back(ALVal);
2572
2573         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2574                                FuncInfo->getRegSaveFrameIndex()));
2575         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2576                                FuncInfo->getVarArgsFPOffset()));
2577
2578         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2579           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2580                                        &X86::VR128RegClass);
2581           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2582           SaveXMMOps.push_back(Val);
2583         }
2584         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2585                                      MVT::Other, SaveXMMOps));
2586       }
2587
2588       if (!MemOps.empty())
2589         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2590     }
2591   }
2592
2593   // Some CCs need callee pop.
2594   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2595                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2596     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2597   } else {
2598     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2599     // If this is an sret function, the return should pop the hidden pointer.
2600     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2601         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2602         argsAreStructReturn(Ins) == StackStructReturn)
2603       FuncInfo->setBytesToPopOnReturn(4);
2604   }
2605
2606   if (!Is64Bit) {
2607     // RegSaveFrameIndex is X86-64 only.
2608     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2609     if (CallConv == CallingConv::X86_FastCall ||
2610         CallConv == CallingConv::X86_ThisCall)
2611       // fastcc functions can't have varargs.
2612       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2613   }
2614
2615   FuncInfo->setArgumentStackSize(StackSize);
2616
2617   return Chain;
2618 }
2619
2620 SDValue
2621 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2622                                     SDValue StackPtr, SDValue Arg,
2623                                     SDLoc dl, SelectionDAG &DAG,
2624                                     const CCValAssign &VA,
2625                                     ISD::ArgFlagsTy Flags) const {
2626   unsigned LocMemOffset = VA.getLocMemOffset();
2627   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2628   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2629   if (Flags.isByVal())
2630     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2631
2632   return DAG.getStore(Chain, dl, Arg, PtrOff,
2633                       MachinePointerInfo::getStack(LocMemOffset),
2634                       false, false, 0);
2635 }
2636
2637 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2638 /// optimization is performed and it is required.
2639 SDValue
2640 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2641                                            SDValue &OutRetAddr, SDValue Chain,
2642                                            bool IsTailCall, bool Is64Bit,
2643                                            int FPDiff, SDLoc dl) const {
2644   // Adjust the Return address stack slot.
2645   EVT VT = getPointerTy();
2646   OutRetAddr = getReturnAddressFrameIndex(DAG);
2647
2648   // Load the "old" Return address.
2649   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2650                            false, false, false, 0);
2651   return SDValue(OutRetAddr.getNode(), 1);
2652 }
2653
2654 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2655 /// optimization is performed and it is required (FPDiff!=0).
2656 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2657                                         SDValue Chain, SDValue RetAddrFrIdx,
2658                                         EVT PtrVT, unsigned SlotSize,
2659                                         int FPDiff, SDLoc dl) {
2660   // Store the return address to the appropriate stack slot.
2661   if (!FPDiff) return Chain;
2662   // Calculate the new stack slot for the return address.
2663   int NewReturnAddrFI =
2664     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2665                                          false);
2666   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2667   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2668                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2669                        false, false, 0);
2670   return Chain;
2671 }
2672
2673 SDValue
2674 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2675                              SmallVectorImpl<SDValue> &InVals) const {
2676   SelectionDAG &DAG                     = CLI.DAG;
2677   SDLoc &dl                             = CLI.DL;
2678   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2679   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2680   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2681   SDValue Chain                         = CLI.Chain;
2682   SDValue Callee                        = CLI.Callee;
2683   CallingConv::ID CallConv              = CLI.CallConv;
2684   bool &isTailCall                      = CLI.IsTailCall;
2685   bool isVarArg                         = CLI.IsVarArg;
2686
2687   MachineFunction &MF = DAG.getMachineFunction();
2688   bool Is64Bit        = Subtarget->is64Bit();
2689   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2690   StructReturnType SR = callIsStructReturn(Outs);
2691   bool IsSibcall      = false;
2692
2693   if (MF.getTarget().Options.DisableTailCalls)
2694     isTailCall = false;
2695
2696   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2697   if (IsMustTail) {
2698     // Force this to be a tail call.  The verifier rules are enough to ensure
2699     // that we can lower this successfully without moving the return address
2700     // around.
2701     isTailCall = true;
2702   } else if (isTailCall) {
2703     // Check if it's really possible to do a tail call.
2704     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2705                     isVarArg, SR != NotStructReturn,
2706                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2707                     Outs, OutVals, Ins, DAG);
2708
2709     // Sibcalls are automatically detected tailcalls which do not require
2710     // ABI changes.
2711     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2712       IsSibcall = true;
2713
2714     if (isTailCall)
2715       ++NumTailCalls;
2716   }
2717
2718   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2719          "Var args not supported with calling convention fastcc, ghc or hipe");
2720
2721   // Analyze operands of the call, assigning locations to each operand.
2722   SmallVector<CCValAssign, 16> ArgLocs;
2723   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2724
2725   // Allocate shadow area for Win64
2726   if (IsWin64)
2727     CCInfo.AllocateStack(32, 8);
2728
2729   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2730
2731   // Get a count of how many bytes are to be pushed on the stack.
2732   unsigned NumBytes = CCInfo.getNextStackOffset();
2733   if (IsSibcall)
2734     // This is a sibcall. The memory operands are available in caller's
2735     // own caller's stack.
2736     NumBytes = 0;
2737   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2738            IsTailCallConvention(CallConv))
2739     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2740
2741   int FPDiff = 0;
2742   if (isTailCall && !IsSibcall && !IsMustTail) {
2743     // Lower arguments at fp - stackoffset + fpdiff.
2744     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2745     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2746
2747     FPDiff = NumBytesCallerPushed - NumBytes;
2748
2749     // Set the delta of movement of the returnaddr stackslot.
2750     // But only set if delta is greater than previous delta.
2751     if (FPDiff < X86Info->getTCReturnAddrDelta())
2752       X86Info->setTCReturnAddrDelta(FPDiff);
2753   }
2754
2755   unsigned NumBytesToPush = NumBytes;
2756   unsigned NumBytesToPop = NumBytes;
2757
2758   // If we have an inalloca argument, all stack space has already been allocated
2759   // for us and be right at the top of the stack.  We don't support multiple
2760   // arguments passed in memory when using inalloca.
2761   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2762     NumBytesToPush = 0;
2763     if (!ArgLocs.back().isMemLoc())
2764       report_fatal_error("cannot use inalloca attribute on a register "
2765                          "parameter");
2766     if (ArgLocs.back().getLocMemOffset() != 0)
2767       report_fatal_error("any parameter with the inalloca attribute must be "
2768                          "the only memory argument");
2769   }
2770
2771   if (!IsSibcall)
2772     Chain = DAG.getCALLSEQ_START(
2773         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2774
2775   SDValue RetAddrFrIdx;
2776   // Load return address for tail calls.
2777   if (isTailCall && FPDiff)
2778     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2779                                     Is64Bit, FPDiff, dl);
2780
2781   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2782   SmallVector<SDValue, 8> MemOpChains;
2783   SDValue StackPtr;
2784
2785   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2786   // of tail call optimization arguments are handle later.
2787   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2788       DAG.getSubtarget().getRegisterInfo());
2789   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2790     // Skip inalloca arguments, they have already been written.
2791     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2792     if (Flags.isInAlloca())
2793       continue;
2794
2795     CCValAssign &VA = ArgLocs[i];
2796     EVT RegVT = VA.getLocVT();
2797     SDValue Arg = OutVals[i];
2798     bool isByVal = Flags.isByVal();
2799
2800     // Promote the value if needed.
2801     switch (VA.getLocInfo()) {
2802     default: llvm_unreachable("Unknown loc info!");
2803     case CCValAssign::Full: break;
2804     case CCValAssign::SExt:
2805       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2806       break;
2807     case CCValAssign::ZExt:
2808       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2809       break;
2810     case CCValAssign::AExt:
2811       if (RegVT.is128BitVector()) {
2812         // Special case: passing MMX values in XMM registers.
2813         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2814         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2815         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2816       } else
2817         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2818       break;
2819     case CCValAssign::BCvt:
2820       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2821       break;
2822     case CCValAssign::Indirect: {
2823       // Store the argument.
2824       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2825       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2826       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2827                            MachinePointerInfo::getFixedStack(FI),
2828                            false, false, 0);
2829       Arg = SpillSlot;
2830       break;
2831     }
2832     }
2833
2834     if (VA.isRegLoc()) {
2835       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2836       if (isVarArg && IsWin64) {
2837         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2838         // shadow reg if callee is a varargs function.
2839         unsigned ShadowReg = 0;
2840         switch (VA.getLocReg()) {
2841         case X86::XMM0: ShadowReg = X86::RCX; break;
2842         case X86::XMM1: ShadowReg = X86::RDX; break;
2843         case X86::XMM2: ShadowReg = X86::R8; break;
2844         case X86::XMM3: ShadowReg = X86::R9; break;
2845         }
2846         if (ShadowReg)
2847           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2848       }
2849     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2850       assert(VA.isMemLoc());
2851       if (!StackPtr.getNode())
2852         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2853                                       getPointerTy());
2854       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2855                                              dl, DAG, VA, Flags));
2856     }
2857   }
2858
2859   if (!MemOpChains.empty())
2860     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2861
2862   if (Subtarget->isPICStyleGOT()) {
2863     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2864     // GOT pointer.
2865     if (!isTailCall) {
2866       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2867                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2868     } else {
2869       // If we are tail calling and generating PIC/GOT style code load the
2870       // address of the callee into ECX. The value in ecx is used as target of
2871       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2872       // for tail calls on PIC/GOT architectures. Normally we would just put the
2873       // address of GOT into ebx and then call target@PLT. But for tail calls
2874       // ebx would be restored (since ebx is callee saved) before jumping to the
2875       // target@PLT.
2876
2877       // Note: The actual moving to ECX is done further down.
2878       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2879       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2880           !G->getGlobal()->hasProtectedVisibility())
2881         Callee = LowerGlobalAddress(Callee, DAG);
2882       else if (isa<ExternalSymbolSDNode>(Callee))
2883         Callee = LowerExternalSymbol(Callee, DAG);
2884     }
2885   }
2886
2887   if (Is64Bit && isVarArg && !IsWin64) {
2888     // From AMD64 ABI document:
2889     // For calls that may call functions that use varargs or stdargs
2890     // (prototype-less calls or calls to functions containing ellipsis (...) in
2891     // the declaration) %al is used as hidden argument to specify the number
2892     // of SSE registers used. The contents of %al do not need to match exactly
2893     // the number of registers, but must be an ubound on the number of SSE
2894     // registers used and is in the range 0 - 8 inclusive.
2895
2896     // Count the number of XMM registers allocated.
2897     static const MCPhysReg XMMArgRegs[] = {
2898       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2899       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2900     };
2901     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2902     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2903            && "SSE registers cannot be used when SSE is disabled");
2904
2905     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2906                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2907   }
2908
2909   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2910   // don't need this because the eligibility check rejects calls that require
2911   // shuffling arguments passed in memory.
2912   if (!IsSibcall && isTailCall) {
2913     // Force all the incoming stack arguments to be loaded from the stack
2914     // before any new outgoing arguments are stored to the stack, because the
2915     // outgoing stack slots may alias the incoming argument stack slots, and
2916     // the alias isn't otherwise explicit. This is slightly more conservative
2917     // than necessary, because it means that each store effectively depends
2918     // on every argument instead of just those arguments it would clobber.
2919     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2920
2921     SmallVector<SDValue, 8> MemOpChains2;
2922     SDValue FIN;
2923     int FI = 0;
2924     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2925       CCValAssign &VA = ArgLocs[i];
2926       if (VA.isRegLoc())
2927         continue;
2928       assert(VA.isMemLoc());
2929       SDValue Arg = OutVals[i];
2930       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2931       // Skip inalloca arguments.  They don't require any work.
2932       if (Flags.isInAlloca())
2933         continue;
2934       // Create frame index.
2935       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2936       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2937       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2938       FIN = DAG.getFrameIndex(FI, getPointerTy());
2939
2940       if (Flags.isByVal()) {
2941         // Copy relative to framepointer.
2942         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2943         if (!StackPtr.getNode())
2944           StackPtr = DAG.getCopyFromReg(Chain, dl,
2945                                         RegInfo->getStackRegister(),
2946                                         getPointerTy());
2947         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2948
2949         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2950                                                          ArgChain,
2951                                                          Flags, DAG, dl));
2952       } else {
2953         // Store relative to framepointer.
2954         MemOpChains2.push_back(
2955           DAG.getStore(ArgChain, dl, Arg, FIN,
2956                        MachinePointerInfo::getFixedStack(FI),
2957                        false, false, 0));
2958       }
2959     }
2960
2961     if (!MemOpChains2.empty())
2962       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2963
2964     // Store the return address to the appropriate stack slot.
2965     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2966                                      getPointerTy(), RegInfo->getSlotSize(),
2967                                      FPDiff, dl);
2968   }
2969
2970   // Build a sequence of copy-to-reg nodes chained together with token chain
2971   // and flag operands which copy the outgoing args into registers.
2972   SDValue InFlag;
2973   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2974     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2975                              RegsToPass[i].second, InFlag);
2976     InFlag = Chain.getValue(1);
2977   }
2978
2979   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2980     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2981     // In the 64-bit large code model, we have to make all calls
2982     // through a register, since the call instruction's 32-bit
2983     // pc-relative offset may not be large enough to hold the whole
2984     // address.
2985   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2986     // If the callee is a GlobalAddress node (quite common, every direct call
2987     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2988     // it.
2989
2990     // We should use extra load for direct calls to dllimported functions in
2991     // non-JIT mode.
2992     const GlobalValue *GV = G->getGlobal();
2993     if (!GV->hasDLLImportStorageClass()) {
2994       unsigned char OpFlags = 0;
2995       bool ExtraLoad = false;
2996       unsigned WrapperKind = ISD::DELETED_NODE;
2997
2998       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2999       // external symbols most go through the PLT in PIC mode.  If the symbol
3000       // has hidden or protected visibility, or if it is static or local, then
3001       // we don't need to use the PLT - we can directly call it.
3002       if (Subtarget->isTargetELF() &&
3003           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3004           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3005         OpFlags = X86II::MO_PLT;
3006       } else if (Subtarget->isPICStyleStubAny() &&
3007                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3008                  (!Subtarget->getTargetTriple().isMacOSX() ||
3009                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3010         // PC-relative references to external symbols should go through $stub,
3011         // unless we're building with the leopard linker or later, which
3012         // automatically synthesizes these stubs.
3013         OpFlags = X86II::MO_DARWIN_STUB;
3014       } else if (Subtarget->isPICStyleRIPRel() &&
3015                  isa<Function>(GV) &&
3016                  cast<Function>(GV)->getAttributes().
3017                    hasAttribute(AttributeSet::FunctionIndex,
3018                                 Attribute::NonLazyBind)) {
3019         // If the function is marked as non-lazy, generate an indirect call
3020         // which loads from the GOT directly. This avoids runtime overhead
3021         // at the cost of eager binding (and one extra byte of encoding).
3022         OpFlags = X86II::MO_GOTPCREL;
3023         WrapperKind = X86ISD::WrapperRIP;
3024         ExtraLoad = true;
3025       }
3026
3027       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3028                                           G->getOffset(), OpFlags);
3029
3030       // Add a wrapper if needed.
3031       if (WrapperKind != ISD::DELETED_NODE)
3032         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3033       // Add extra indirection if needed.
3034       if (ExtraLoad)
3035         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3036                              MachinePointerInfo::getGOT(),
3037                              false, false, false, 0);
3038     }
3039   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3040     unsigned char OpFlags = 0;
3041
3042     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3043     // external symbols should go through the PLT.
3044     if (Subtarget->isTargetELF() &&
3045         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3046       OpFlags = X86II::MO_PLT;
3047     } else if (Subtarget->isPICStyleStubAny() &&
3048                (!Subtarget->getTargetTriple().isMacOSX() ||
3049                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3050       // PC-relative references to external symbols should go through $stub,
3051       // unless we're building with the leopard linker or later, which
3052       // automatically synthesizes these stubs.
3053       OpFlags = X86II::MO_DARWIN_STUB;
3054     }
3055
3056     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3057                                          OpFlags);
3058   }
3059
3060   // Returns a chain & a flag for retval copy to use.
3061   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3062   SmallVector<SDValue, 8> Ops;
3063
3064   if (!IsSibcall && isTailCall) {
3065     Chain = DAG.getCALLSEQ_END(Chain,
3066                                DAG.getIntPtrConstant(NumBytesToPop, true),
3067                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3068     InFlag = Chain.getValue(1);
3069   }
3070
3071   Ops.push_back(Chain);
3072   Ops.push_back(Callee);
3073
3074   if (isTailCall)
3075     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3076
3077   // Add argument registers to the end of the list so that they are known live
3078   // into the call.
3079   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3080     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3081                                   RegsToPass[i].second.getValueType()));
3082
3083   // Add a register mask operand representing the call-preserved registers.
3084   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3085   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3086   assert(Mask && "Missing call preserved mask for calling convention");
3087   Ops.push_back(DAG.getRegisterMask(Mask));
3088
3089   if (InFlag.getNode())
3090     Ops.push_back(InFlag);
3091
3092   if (isTailCall) {
3093     // We used to do:
3094     //// If this is the first return lowered for this function, add the regs
3095     //// to the liveout set for the function.
3096     // This isn't right, although it's probably harmless on x86; liveouts
3097     // should be computed from returns not tail calls.  Consider a void
3098     // function making a tail call to a function returning int.
3099     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3100   }
3101
3102   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3103   InFlag = Chain.getValue(1);
3104
3105   // Create the CALLSEQ_END node.
3106   unsigned NumBytesForCalleeToPop;
3107   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3108                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3109     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3110   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3111            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3112            SR == StackStructReturn)
3113     // If this is a call to a struct-return function, the callee
3114     // pops the hidden struct pointer, so we have to push it back.
3115     // This is common for Darwin/X86, Linux & Mingw32 targets.
3116     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3117     NumBytesForCalleeToPop = 4;
3118   else
3119     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3120
3121   // Returns a flag for retval copy to use.
3122   if (!IsSibcall) {
3123     Chain = DAG.getCALLSEQ_END(Chain,
3124                                DAG.getIntPtrConstant(NumBytesToPop, true),
3125                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3126                                                      true),
3127                                InFlag, dl);
3128     InFlag = Chain.getValue(1);
3129   }
3130
3131   // Handle result values, copying them out of physregs into vregs that we
3132   // return.
3133   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3134                          Ins, dl, DAG, InVals);
3135 }
3136
3137 //===----------------------------------------------------------------------===//
3138 //                Fast Calling Convention (tail call) implementation
3139 //===----------------------------------------------------------------------===//
3140
3141 //  Like std call, callee cleans arguments, convention except that ECX is
3142 //  reserved for storing the tail called function address. Only 2 registers are
3143 //  free for argument passing (inreg). Tail call optimization is performed
3144 //  provided:
3145 //                * tailcallopt is enabled
3146 //                * caller/callee are fastcc
3147 //  On X86_64 architecture with GOT-style position independent code only local
3148 //  (within module) calls are supported at the moment.
3149 //  To keep the stack aligned according to platform abi the function
3150 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3151 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3152 //  If a tail called function callee has more arguments than the caller the
3153 //  caller needs to make sure that there is room to move the RETADDR to. This is
3154 //  achieved by reserving an area the size of the argument delta right after the
3155 //  original RETADDR, but before the saved framepointer or the spilled registers
3156 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3157 //  stack layout:
3158 //    arg1
3159 //    arg2
3160 //    RETADDR
3161 //    [ new RETADDR
3162 //      move area ]
3163 //    (possible EBP)
3164 //    ESI
3165 //    EDI
3166 //    local1 ..
3167
3168 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3169 /// for a 16 byte align requirement.
3170 unsigned
3171 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3172                                                SelectionDAG& DAG) const {
3173   MachineFunction &MF = DAG.getMachineFunction();
3174   const TargetMachine &TM = MF.getTarget();
3175   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3176       TM.getSubtargetImpl()->getRegisterInfo());
3177   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3178   unsigned StackAlignment = TFI.getStackAlignment();
3179   uint64_t AlignMask = StackAlignment - 1;
3180   int64_t Offset = StackSize;
3181   unsigned SlotSize = RegInfo->getSlotSize();
3182   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3183     // Number smaller than 12 so just add the difference.
3184     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3185   } else {
3186     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3187     Offset = ((~AlignMask) & Offset) + StackAlignment +
3188       (StackAlignment-SlotSize);
3189   }
3190   return Offset;
3191 }
3192
3193 /// MatchingStackOffset - Return true if the given stack call argument is
3194 /// already available in the same position (relatively) of the caller's
3195 /// incoming argument stack.
3196 static
3197 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3198                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3199                          const X86InstrInfo *TII) {
3200   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3201   int FI = INT_MAX;
3202   if (Arg.getOpcode() == ISD::CopyFromReg) {
3203     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3204     if (!TargetRegisterInfo::isVirtualRegister(VR))
3205       return false;
3206     MachineInstr *Def = MRI->getVRegDef(VR);
3207     if (!Def)
3208       return false;
3209     if (!Flags.isByVal()) {
3210       if (!TII->isLoadFromStackSlot(Def, FI))
3211         return false;
3212     } else {
3213       unsigned Opcode = Def->getOpcode();
3214       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3215           Def->getOperand(1).isFI()) {
3216         FI = Def->getOperand(1).getIndex();
3217         Bytes = Flags.getByValSize();
3218       } else
3219         return false;
3220     }
3221   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3222     if (Flags.isByVal())
3223       // ByVal argument is passed in as a pointer but it's now being
3224       // dereferenced. e.g.
3225       // define @foo(%struct.X* %A) {
3226       //   tail call @bar(%struct.X* byval %A)
3227       // }
3228       return false;
3229     SDValue Ptr = Ld->getBasePtr();
3230     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3231     if (!FINode)
3232       return false;
3233     FI = FINode->getIndex();
3234   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3235     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3236     FI = FINode->getIndex();
3237     Bytes = Flags.getByValSize();
3238   } else
3239     return false;
3240
3241   assert(FI != INT_MAX);
3242   if (!MFI->isFixedObjectIndex(FI))
3243     return false;
3244   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3245 }
3246
3247 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3248 /// for tail call optimization. Targets which want to do tail call
3249 /// optimization should implement this function.
3250 bool
3251 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3252                                                      CallingConv::ID CalleeCC,
3253                                                      bool isVarArg,
3254                                                      bool isCalleeStructRet,
3255                                                      bool isCallerStructRet,
3256                                                      Type *RetTy,
3257                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3258                                     const SmallVectorImpl<SDValue> &OutVals,
3259                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3260                                                      SelectionDAG &DAG) const {
3261   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3262     return false;
3263
3264   // If -tailcallopt is specified, make fastcc functions tail-callable.
3265   const MachineFunction &MF = DAG.getMachineFunction();
3266   const Function *CallerF = MF.getFunction();
3267
3268   // If the function return type is x86_fp80 and the callee return type is not,
3269   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3270   // perform a tailcall optimization here.
3271   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3272     return false;
3273
3274   CallingConv::ID CallerCC = CallerF->getCallingConv();
3275   bool CCMatch = CallerCC == CalleeCC;
3276   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3277   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3278
3279   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3280     if (IsTailCallConvention(CalleeCC) && CCMatch)
3281       return true;
3282     return false;
3283   }
3284
3285   // Look for obvious safe cases to perform tail call optimization that do not
3286   // require ABI changes. This is what gcc calls sibcall.
3287
3288   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3289   // emit a special epilogue.
3290   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3291       DAG.getSubtarget().getRegisterInfo());
3292   if (RegInfo->needsStackRealignment(MF))
3293     return false;
3294
3295   // Also avoid sibcall optimization if either caller or callee uses struct
3296   // return semantics.
3297   if (isCalleeStructRet || isCallerStructRet)
3298     return false;
3299
3300   // An stdcall/thiscall caller is expected to clean up its arguments; the
3301   // callee isn't going to do that.
3302   // FIXME: this is more restrictive than needed. We could produce a tailcall
3303   // when the stack adjustment matches. For example, with a thiscall that takes
3304   // only one argument.
3305   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3306                    CallerCC == CallingConv::X86_ThisCall))
3307     return false;
3308
3309   // Do not sibcall optimize vararg calls unless all arguments are passed via
3310   // registers.
3311   if (isVarArg && !Outs.empty()) {
3312
3313     // Optimizing for varargs on Win64 is unlikely to be safe without
3314     // additional testing.
3315     if (IsCalleeWin64 || IsCallerWin64)
3316       return false;
3317
3318     SmallVector<CCValAssign, 16> ArgLocs;
3319     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3320                    *DAG.getContext());
3321
3322     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3323     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3324       if (!ArgLocs[i].isRegLoc())
3325         return false;
3326   }
3327
3328   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3329   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3330   // this into a sibcall.
3331   bool Unused = false;
3332   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3333     if (!Ins[i].Used) {
3334       Unused = true;
3335       break;
3336     }
3337   }
3338   if (Unused) {
3339     SmallVector<CCValAssign, 16> RVLocs;
3340     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3341                    *DAG.getContext());
3342     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3343     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3344       CCValAssign &VA = RVLocs[i];
3345       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3346         return false;
3347     }
3348   }
3349
3350   // If the calling conventions do not match, then we'd better make sure the
3351   // results are returned in the same way as what the caller expects.
3352   if (!CCMatch) {
3353     SmallVector<CCValAssign, 16> RVLocs1;
3354     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3355                     *DAG.getContext());
3356     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3357
3358     SmallVector<CCValAssign, 16> RVLocs2;
3359     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3360                     *DAG.getContext());
3361     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3362
3363     if (RVLocs1.size() != RVLocs2.size())
3364       return false;
3365     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3366       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3367         return false;
3368       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3369         return false;
3370       if (RVLocs1[i].isRegLoc()) {
3371         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3372           return false;
3373       } else {
3374         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3375           return false;
3376       }
3377     }
3378   }
3379
3380   // If the callee takes no arguments then go on to check the results of the
3381   // call.
3382   if (!Outs.empty()) {
3383     // Check if stack adjustment is needed. For now, do not do this if any
3384     // argument is passed on the stack.
3385     SmallVector<CCValAssign, 16> ArgLocs;
3386     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3387                    *DAG.getContext());
3388
3389     // Allocate shadow area for Win64
3390     if (IsCalleeWin64)
3391       CCInfo.AllocateStack(32, 8);
3392
3393     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3394     if (CCInfo.getNextStackOffset()) {
3395       MachineFunction &MF = DAG.getMachineFunction();
3396       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3397         return false;
3398
3399       // Check if the arguments are already laid out in the right way as
3400       // the caller's fixed stack objects.
3401       MachineFrameInfo *MFI = MF.getFrameInfo();
3402       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3403       const X86InstrInfo *TII =
3404           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3405       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3406         CCValAssign &VA = ArgLocs[i];
3407         SDValue Arg = OutVals[i];
3408         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3409         if (VA.getLocInfo() == CCValAssign::Indirect)
3410           return false;
3411         if (!VA.isRegLoc()) {
3412           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3413                                    MFI, MRI, TII))
3414             return false;
3415         }
3416       }
3417     }
3418
3419     // If the tailcall address may be in a register, then make sure it's
3420     // possible to register allocate for it. In 32-bit, the call address can
3421     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3422     // callee-saved registers are restored. These happen to be the same
3423     // registers used to pass 'inreg' arguments so watch out for those.
3424     if (!Subtarget->is64Bit() &&
3425         ((!isa<GlobalAddressSDNode>(Callee) &&
3426           !isa<ExternalSymbolSDNode>(Callee)) ||
3427          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3428       unsigned NumInRegs = 0;
3429       // In PIC we need an extra register to formulate the address computation
3430       // for the callee.
3431       unsigned MaxInRegs =
3432         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3433
3434       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3435         CCValAssign &VA = ArgLocs[i];
3436         if (!VA.isRegLoc())
3437           continue;
3438         unsigned Reg = VA.getLocReg();
3439         switch (Reg) {
3440         default: break;
3441         case X86::EAX: case X86::EDX: case X86::ECX:
3442           if (++NumInRegs == MaxInRegs)
3443             return false;
3444           break;
3445         }
3446       }
3447     }
3448   }
3449
3450   return true;
3451 }
3452
3453 FastISel *
3454 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3455                                   const TargetLibraryInfo *libInfo) const {
3456   return X86::createFastISel(funcInfo, libInfo);
3457 }
3458
3459 //===----------------------------------------------------------------------===//
3460 //                           Other Lowering Hooks
3461 //===----------------------------------------------------------------------===//
3462
3463 static bool MayFoldLoad(SDValue Op) {
3464   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3465 }
3466
3467 static bool MayFoldIntoStore(SDValue Op) {
3468   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3469 }
3470
3471 static bool isTargetShuffle(unsigned Opcode) {
3472   switch(Opcode) {
3473   default: return false;
3474   case X86ISD::PSHUFB:
3475   case X86ISD::PSHUFD:
3476   case X86ISD::PSHUFHW:
3477   case X86ISD::PSHUFLW:
3478   case X86ISD::SHUFP:
3479   case X86ISD::PALIGNR:
3480   case X86ISD::MOVLHPS:
3481   case X86ISD::MOVLHPD:
3482   case X86ISD::MOVHLPS:
3483   case X86ISD::MOVLPS:
3484   case X86ISD::MOVLPD:
3485   case X86ISD::MOVSHDUP:
3486   case X86ISD::MOVSLDUP:
3487   case X86ISD::MOVDDUP:
3488   case X86ISD::MOVSS:
3489   case X86ISD::MOVSD:
3490   case X86ISD::UNPCKL:
3491   case X86ISD::UNPCKH:
3492   case X86ISD::VPERMILP:
3493   case X86ISD::VPERM2X128:
3494   case X86ISD::VPERMI:
3495     return true;
3496   }
3497 }
3498
3499 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3500                                     SDValue V1, SelectionDAG &DAG) {
3501   switch(Opc) {
3502   default: llvm_unreachable("Unknown x86 shuffle node");
3503   case X86ISD::MOVSHDUP:
3504   case X86ISD::MOVSLDUP:
3505   case X86ISD::MOVDDUP:
3506     return DAG.getNode(Opc, dl, VT, V1);
3507   }
3508 }
3509
3510 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3511                                     SDValue V1, unsigned TargetMask,
3512                                     SelectionDAG &DAG) {
3513   switch(Opc) {
3514   default: llvm_unreachable("Unknown x86 shuffle node");
3515   case X86ISD::PSHUFD:
3516   case X86ISD::PSHUFHW:
3517   case X86ISD::PSHUFLW:
3518   case X86ISD::VPERMILP:
3519   case X86ISD::VPERMI:
3520     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3521   }
3522 }
3523
3524 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3525                                     SDValue V1, SDValue V2, unsigned TargetMask,
3526                                     SelectionDAG &DAG) {
3527   switch(Opc) {
3528   default: llvm_unreachable("Unknown x86 shuffle node");
3529   case X86ISD::PALIGNR:
3530   case X86ISD::VALIGN:
3531   case X86ISD::SHUFP:
3532   case X86ISD::VPERM2X128:
3533     return DAG.getNode(Opc, dl, VT, V1, V2,
3534                        DAG.getConstant(TargetMask, MVT::i8));
3535   }
3536 }
3537
3538 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3539                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3540   switch(Opc) {
3541   default: llvm_unreachable("Unknown x86 shuffle node");
3542   case X86ISD::MOVLHPS:
3543   case X86ISD::MOVLHPD:
3544   case X86ISD::MOVHLPS:
3545   case X86ISD::MOVLPS:
3546   case X86ISD::MOVLPD:
3547   case X86ISD::MOVSS:
3548   case X86ISD::MOVSD:
3549   case X86ISD::UNPCKL:
3550   case X86ISD::UNPCKH:
3551     return DAG.getNode(Opc, dl, VT, V1, V2);
3552   }
3553 }
3554
3555 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3556   MachineFunction &MF = DAG.getMachineFunction();
3557   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3558       DAG.getSubtarget().getRegisterInfo());
3559   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3560   int ReturnAddrIndex = FuncInfo->getRAIndex();
3561
3562   if (ReturnAddrIndex == 0) {
3563     // Set up a frame object for the return address.
3564     unsigned SlotSize = RegInfo->getSlotSize();
3565     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3566                                                            -(int64_t)SlotSize,
3567                                                            false);
3568     FuncInfo->setRAIndex(ReturnAddrIndex);
3569   }
3570
3571   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3572 }
3573
3574 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3575                                        bool hasSymbolicDisplacement) {
3576   // Offset should fit into 32 bit immediate field.
3577   if (!isInt<32>(Offset))
3578     return false;
3579
3580   // If we don't have a symbolic displacement - we don't have any extra
3581   // restrictions.
3582   if (!hasSymbolicDisplacement)
3583     return true;
3584
3585   // FIXME: Some tweaks might be needed for medium code model.
3586   if (M != CodeModel::Small && M != CodeModel::Kernel)
3587     return false;
3588
3589   // For small code model we assume that latest object is 16MB before end of 31
3590   // bits boundary. We may also accept pretty large negative constants knowing
3591   // that all objects are in the positive half of address space.
3592   if (M == CodeModel::Small && Offset < 16*1024*1024)
3593     return true;
3594
3595   // For kernel code model we know that all object resist in the negative half
3596   // of 32bits address space. We may not accept negative offsets, since they may
3597   // be just off and we may accept pretty large positive ones.
3598   if (M == CodeModel::Kernel && Offset > 0)
3599     return true;
3600
3601   return false;
3602 }
3603
3604 /// isCalleePop - Determines whether the callee is required to pop its
3605 /// own arguments. Callee pop is necessary to support tail calls.
3606 bool X86::isCalleePop(CallingConv::ID CallingConv,
3607                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3608   switch (CallingConv) {
3609   default:
3610     return false;
3611   case CallingConv::X86_StdCall:
3612   case CallingConv::X86_FastCall:
3613   case CallingConv::X86_ThisCall:
3614     return !is64Bit;
3615   case CallingConv::Fast:
3616   case CallingConv::GHC:
3617   case CallingConv::HiPE:
3618     if (IsVarArg)
3619       return false;
3620     return TailCallOpt;
3621   }
3622 }
3623
3624 /// \brief Return true if the condition is an unsigned comparison operation.
3625 static bool isX86CCUnsigned(unsigned X86CC) {
3626   switch (X86CC) {
3627   default: llvm_unreachable("Invalid integer condition!");
3628   case X86::COND_E:     return true;
3629   case X86::COND_G:     return false;
3630   case X86::COND_GE:    return false;
3631   case X86::COND_L:     return false;
3632   case X86::COND_LE:    return false;
3633   case X86::COND_NE:    return true;
3634   case X86::COND_B:     return true;
3635   case X86::COND_A:     return true;
3636   case X86::COND_BE:    return true;
3637   case X86::COND_AE:    return true;
3638   }
3639   llvm_unreachable("covered switch fell through?!");
3640 }
3641
3642 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3643 /// specific condition code, returning the condition code and the LHS/RHS of the
3644 /// comparison to make.
3645 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3646                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3647   if (!isFP) {
3648     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3649       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3650         // X > -1   -> X == 0, jump !sign.
3651         RHS = DAG.getConstant(0, RHS.getValueType());
3652         return X86::COND_NS;
3653       }
3654       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3655         // X < 0   -> X == 0, jump on sign.
3656         return X86::COND_S;
3657       }
3658       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3659         // X < 1   -> X <= 0
3660         RHS = DAG.getConstant(0, RHS.getValueType());
3661         return X86::COND_LE;
3662       }
3663     }
3664
3665     switch (SetCCOpcode) {
3666     default: llvm_unreachable("Invalid integer condition!");
3667     case ISD::SETEQ:  return X86::COND_E;
3668     case ISD::SETGT:  return X86::COND_G;
3669     case ISD::SETGE:  return X86::COND_GE;
3670     case ISD::SETLT:  return X86::COND_L;
3671     case ISD::SETLE:  return X86::COND_LE;
3672     case ISD::SETNE:  return X86::COND_NE;
3673     case ISD::SETULT: return X86::COND_B;
3674     case ISD::SETUGT: return X86::COND_A;
3675     case ISD::SETULE: return X86::COND_BE;
3676     case ISD::SETUGE: return X86::COND_AE;
3677     }
3678   }
3679
3680   // First determine if it is required or is profitable to flip the operands.
3681
3682   // If LHS is a foldable load, but RHS is not, flip the condition.
3683   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3684       !ISD::isNON_EXTLoad(RHS.getNode())) {
3685     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3686     std::swap(LHS, RHS);
3687   }
3688
3689   switch (SetCCOpcode) {
3690   default: break;
3691   case ISD::SETOLT:
3692   case ISD::SETOLE:
3693   case ISD::SETUGT:
3694   case ISD::SETUGE:
3695     std::swap(LHS, RHS);
3696     break;
3697   }
3698
3699   // On a floating point condition, the flags are set as follows:
3700   // ZF  PF  CF   op
3701   //  0 | 0 | 0 | X > Y
3702   //  0 | 0 | 1 | X < Y
3703   //  1 | 0 | 0 | X == Y
3704   //  1 | 1 | 1 | unordered
3705   switch (SetCCOpcode) {
3706   default: llvm_unreachable("Condcode should be pre-legalized away");
3707   case ISD::SETUEQ:
3708   case ISD::SETEQ:   return X86::COND_E;
3709   case ISD::SETOLT:              // flipped
3710   case ISD::SETOGT:
3711   case ISD::SETGT:   return X86::COND_A;
3712   case ISD::SETOLE:              // flipped
3713   case ISD::SETOGE:
3714   case ISD::SETGE:   return X86::COND_AE;
3715   case ISD::SETUGT:              // flipped
3716   case ISD::SETULT:
3717   case ISD::SETLT:   return X86::COND_B;
3718   case ISD::SETUGE:              // flipped
3719   case ISD::SETULE:
3720   case ISD::SETLE:   return X86::COND_BE;
3721   case ISD::SETONE:
3722   case ISD::SETNE:   return X86::COND_NE;
3723   case ISD::SETUO:   return X86::COND_P;
3724   case ISD::SETO:    return X86::COND_NP;
3725   case ISD::SETOEQ:
3726   case ISD::SETUNE:  return X86::COND_INVALID;
3727   }
3728 }
3729
3730 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3731 /// code. Current x86 isa includes the following FP cmov instructions:
3732 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3733 static bool hasFPCMov(unsigned X86CC) {
3734   switch (X86CC) {
3735   default:
3736     return false;
3737   case X86::COND_B:
3738   case X86::COND_BE:
3739   case X86::COND_E:
3740   case X86::COND_P:
3741   case X86::COND_A:
3742   case X86::COND_AE:
3743   case X86::COND_NE:
3744   case X86::COND_NP:
3745     return true;
3746   }
3747 }
3748
3749 /// isFPImmLegal - Returns true if the target can instruction select the
3750 /// specified FP immediate natively. If false, the legalizer will
3751 /// materialize the FP immediate as a load from a constant pool.
3752 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3753   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3754     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3755       return true;
3756   }
3757   return false;
3758 }
3759
3760 /// \brief Returns true if it is beneficial to convert a load of a constant
3761 /// to just the constant itself.
3762 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3763                                                           Type *Ty) const {
3764   assert(Ty->isIntegerTy());
3765
3766   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3767   if (BitSize == 0 || BitSize > 64)
3768     return false;
3769   return true;
3770 }
3771
3772 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3773 /// the specified range (L, H].
3774 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3775   return (Val < 0) || (Val >= Low && Val < Hi);
3776 }
3777
3778 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3779 /// specified value.
3780 static bool isUndefOrEqual(int Val, int CmpVal) {
3781   return (Val < 0 || Val == CmpVal);
3782 }
3783
3784 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3785 /// from position Pos and ending in Pos+Size, falls within the specified
3786 /// sequential range (L, L+Pos]. or is undef.
3787 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3788                                        unsigned Pos, unsigned Size, int Low) {
3789   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3790     if (!isUndefOrEqual(Mask[i], Low))
3791       return false;
3792   return true;
3793 }
3794
3795 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3796 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3797 /// the second operand.
3798 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3799   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3800     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3801   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3802     return (Mask[0] < 2 && Mask[1] < 2);
3803   return false;
3804 }
3805
3806 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3807 /// is suitable for input to PSHUFHW.
3808 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3809   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3810     return false;
3811
3812   // Lower quadword copied in order or undef.
3813   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3814     return false;
3815
3816   // Upper quadword shuffled.
3817   for (unsigned i = 4; i != 8; ++i)
3818     if (!isUndefOrInRange(Mask[i], 4, 8))
3819       return false;
3820
3821   if (VT == MVT::v16i16) {
3822     // Lower quadword copied in order or undef.
3823     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3824       return false;
3825
3826     // Upper quadword shuffled.
3827     for (unsigned i = 12; i != 16; ++i)
3828       if (!isUndefOrInRange(Mask[i], 12, 16))
3829         return false;
3830   }
3831
3832   return true;
3833 }
3834
3835 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3836 /// is suitable for input to PSHUFLW.
3837 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3838   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3839     return false;
3840
3841   // Upper quadword copied in order.
3842   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3843     return false;
3844
3845   // Lower quadword shuffled.
3846   for (unsigned i = 0; i != 4; ++i)
3847     if (!isUndefOrInRange(Mask[i], 0, 4))
3848       return false;
3849
3850   if (VT == MVT::v16i16) {
3851     // Upper quadword copied in order.
3852     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3853       return false;
3854
3855     // Lower quadword shuffled.
3856     for (unsigned i = 8; i != 12; ++i)
3857       if (!isUndefOrInRange(Mask[i], 8, 12))
3858         return false;
3859   }
3860
3861   return true;
3862 }
3863
3864 /// \brief Return true if the mask specifies a shuffle of elements that is
3865 /// suitable for input to intralane (palignr) or interlane (valign) vector
3866 /// right-shift.
3867 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3868   unsigned NumElts = VT.getVectorNumElements();
3869   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3870   unsigned NumLaneElts = NumElts/NumLanes;
3871
3872   // Do not handle 64-bit element shuffles with palignr.
3873   if (NumLaneElts == 2)
3874     return false;
3875
3876   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3877     unsigned i;
3878     for (i = 0; i != NumLaneElts; ++i) {
3879       if (Mask[i+l] >= 0)
3880         break;
3881     }
3882
3883     // Lane is all undef, go to next lane
3884     if (i == NumLaneElts)
3885       continue;
3886
3887     int Start = Mask[i+l];
3888
3889     // Make sure its in this lane in one of the sources
3890     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3891         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3892       return false;
3893
3894     // If not lane 0, then we must match lane 0
3895     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3896       return false;
3897
3898     // Correct second source to be contiguous with first source
3899     if (Start >= (int)NumElts)
3900       Start -= NumElts - NumLaneElts;
3901
3902     // Make sure we're shifting in the right direction.
3903     if (Start <= (int)(i+l))
3904       return false;
3905
3906     Start -= i;
3907
3908     // Check the rest of the elements to see if they are consecutive.
3909     for (++i; i != NumLaneElts; ++i) {
3910       int Idx = Mask[i+l];
3911
3912       // Make sure its in this lane
3913       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3914           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3915         return false;
3916
3917       // If not lane 0, then we must match lane 0
3918       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3919         return false;
3920
3921       if (Idx >= (int)NumElts)
3922         Idx -= NumElts - NumLaneElts;
3923
3924       if (!isUndefOrEqual(Idx, Start+i))
3925         return false;
3926
3927     }
3928   }
3929
3930   return true;
3931 }
3932
3933 /// \brief Return true if the node specifies a shuffle of elements that is
3934 /// suitable for input to PALIGNR.
3935 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3936                           const X86Subtarget *Subtarget) {
3937   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3938       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
3939       VT.is512BitVector())
3940     // FIXME: Add AVX512BW.
3941     return false;
3942
3943   return isAlignrMask(Mask, VT, false);
3944 }
3945
3946 /// \brief Return true if the node specifies a shuffle of elements that is
3947 /// suitable for input to VALIGN.
3948 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3949                           const X86Subtarget *Subtarget) {
3950   // FIXME: Add AVX512VL.
3951   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3952     return false;
3953   return isAlignrMask(Mask, VT, true);
3954 }
3955
3956 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3957 /// the two vector operands have swapped position.
3958 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3959                                      unsigned NumElems) {
3960   for (unsigned i = 0; i != NumElems; ++i) {
3961     int idx = Mask[i];
3962     if (idx < 0)
3963       continue;
3964     else if (idx < (int)NumElems)
3965       Mask[i] = idx + NumElems;
3966     else
3967       Mask[i] = idx - NumElems;
3968   }
3969 }
3970
3971 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3973 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3974 /// reverse of what x86 shuffles want.
3975 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3976
3977   unsigned NumElems = VT.getVectorNumElements();
3978   unsigned NumLanes = VT.getSizeInBits()/128;
3979   unsigned NumLaneElems = NumElems/NumLanes;
3980
3981   if (NumLaneElems != 2 && NumLaneElems != 4)
3982     return false;
3983
3984   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3985   bool symetricMaskRequired =
3986     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3987
3988   // VSHUFPSY divides the resulting vector into 4 chunks.
3989   // The sources are also splitted into 4 chunks, and each destination
3990   // chunk must come from a different source chunk.
3991   //
3992   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3993   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3994   //
3995   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3996   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3997   //
3998   // VSHUFPDY divides the resulting vector into 4 chunks.
3999   // The sources are also splitted into 4 chunks, and each destination
4000   // chunk must come from a different source chunk.
4001   //
4002   //  SRC1 =>      X3       X2       X1       X0
4003   //  SRC2 =>      Y3       Y2       Y1       Y0
4004   //
4005   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4006   //
4007   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4008   unsigned HalfLaneElems = NumLaneElems/2;
4009   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4010     for (unsigned i = 0; i != NumLaneElems; ++i) {
4011       int Idx = Mask[i+l];
4012       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4013       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4014         return false;
4015       // For VSHUFPSY, the mask of the second half must be the same as the
4016       // first but with the appropriate offsets. This works in the same way as
4017       // VPERMILPS works with masks.
4018       if (!symetricMaskRequired || Idx < 0)
4019         continue;
4020       if (MaskVal[i] < 0) {
4021         MaskVal[i] = Idx - l;
4022         continue;
4023       }
4024       if ((signed)(Idx - l) != MaskVal[i])
4025         return false;
4026     }
4027   }
4028
4029   return true;
4030 }
4031
4032 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4033 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4034 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4035   if (!VT.is128BitVector())
4036     return false;
4037
4038   unsigned NumElems = VT.getVectorNumElements();
4039
4040   if (NumElems != 4)
4041     return false;
4042
4043   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4044   return isUndefOrEqual(Mask[0], 6) &&
4045          isUndefOrEqual(Mask[1], 7) &&
4046          isUndefOrEqual(Mask[2], 2) &&
4047          isUndefOrEqual(Mask[3], 3);
4048 }
4049
4050 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4051 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4052 /// <2, 3, 2, 3>
4053 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4054   if (!VT.is128BitVector())
4055     return false;
4056
4057   unsigned NumElems = VT.getVectorNumElements();
4058
4059   if (NumElems != 4)
4060     return false;
4061
4062   return isUndefOrEqual(Mask[0], 2) &&
4063          isUndefOrEqual(Mask[1], 3) &&
4064          isUndefOrEqual(Mask[2], 2) &&
4065          isUndefOrEqual(Mask[3], 3);
4066 }
4067
4068 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4069 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4070 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4071   if (!VT.is128BitVector())
4072     return false;
4073
4074   unsigned NumElems = VT.getVectorNumElements();
4075
4076   if (NumElems != 2 && NumElems != 4)
4077     return false;
4078
4079   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4080     if (!isUndefOrEqual(Mask[i], i + NumElems))
4081       return false;
4082
4083   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4084     if (!isUndefOrEqual(Mask[i], i))
4085       return false;
4086
4087   return true;
4088 }
4089
4090 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4091 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4092 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4093   if (!VT.is128BitVector())
4094     return false;
4095
4096   unsigned NumElems = VT.getVectorNumElements();
4097
4098   if (NumElems != 2 && NumElems != 4)
4099     return false;
4100
4101   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4102     if (!isUndefOrEqual(Mask[i], i))
4103       return false;
4104
4105   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4106     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4107       return false;
4108
4109   return true;
4110 }
4111
4112 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4113 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4114 /// i. e: If all but one element come from the same vector.
4115 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4116   // TODO: Deal with AVX's VINSERTPS
4117   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4118     return false;
4119
4120   unsigned CorrectPosV1 = 0;
4121   unsigned CorrectPosV2 = 0;
4122   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4123     if (Mask[i] == -1) {
4124       ++CorrectPosV1;
4125       ++CorrectPosV2;
4126       continue;
4127     }
4128
4129     if (Mask[i] == i)
4130       ++CorrectPosV1;
4131     else if (Mask[i] == i + 4)
4132       ++CorrectPosV2;
4133   }
4134
4135   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4136     // We have 3 elements (undefs count as elements from any vector) from one
4137     // vector, and one from another.
4138     return true;
4139
4140   return false;
4141 }
4142
4143 //
4144 // Some special combinations that can be optimized.
4145 //
4146 static
4147 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4148                                SelectionDAG &DAG) {
4149   MVT VT = SVOp->getSimpleValueType(0);
4150   SDLoc dl(SVOp);
4151
4152   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4153     return SDValue();
4154
4155   ArrayRef<int> Mask = SVOp->getMask();
4156
4157   // These are the special masks that may be optimized.
4158   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4159   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4160   bool MatchEvenMask = true;
4161   bool MatchOddMask  = true;
4162   for (int i=0; i<8; ++i) {
4163     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4164       MatchEvenMask = false;
4165     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4166       MatchOddMask = false;
4167   }
4168
4169   if (!MatchEvenMask && !MatchOddMask)
4170     return SDValue();
4171
4172   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4173
4174   SDValue Op0 = SVOp->getOperand(0);
4175   SDValue Op1 = SVOp->getOperand(1);
4176
4177   if (MatchEvenMask) {
4178     // Shift the second operand right to 32 bits.
4179     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4180     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4181   } else {
4182     // Shift the first operand left to 32 bits.
4183     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4184     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4185   }
4186   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4187   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4188 }
4189
4190 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4191 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4192 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4193                          bool HasInt256, bool V2IsSplat = false) {
4194
4195   assert(VT.getSizeInBits() >= 128 &&
4196          "Unsupported vector type for unpckl");
4197
4198   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4199   unsigned NumLanes;
4200   unsigned NumOf256BitLanes;
4201   unsigned NumElts = VT.getVectorNumElements();
4202   if (VT.is256BitVector()) {
4203     if (NumElts != 4 && NumElts != 8 &&
4204         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4205     return false;
4206     NumLanes = 2;
4207     NumOf256BitLanes = 1;
4208   } else if (VT.is512BitVector()) {
4209     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4210            "Unsupported vector type for unpckh");
4211     NumLanes = 2;
4212     NumOf256BitLanes = 2;
4213   } else {
4214     NumLanes = 1;
4215     NumOf256BitLanes = 1;
4216   }
4217
4218   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4219   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4220
4221   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4222     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4223       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4224         int BitI  = Mask[l256*NumEltsInStride+l+i];
4225         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4226         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4227           return false;
4228         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4229           return false;
4230         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4231           return false;
4232       }
4233     }
4234   }
4235   return true;
4236 }
4237
4238 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4239 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4240 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4241                          bool HasInt256, bool V2IsSplat = false) {
4242   assert(VT.getSizeInBits() >= 128 &&
4243          "Unsupported vector type for unpckh");
4244
4245   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4246   unsigned NumLanes;
4247   unsigned NumOf256BitLanes;
4248   unsigned NumElts = VT.getVectorNumElements();
4249   if (VT.is256BitVector()) {
4250     if (NumElts != 4 && NumElts != 8 &&
4251         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4252     return false;
4253     NumLanes = 2;
4254     NumOf256BitLanes = 1;
4255   } else if (VT.is512BitVector()) {
4256     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4257            "Unsupported vector type for unpckh");
4258     NumLanes = 2;
4259     NumOf256BitLanes = 2;
4260   } else {
4261     NumLanes = 1;
4262     NumOf256BitLanes = 1;
4263   }
4264
4265   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4266   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4267
4268   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4269     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4270       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4271         int BitI  = Mask[l256*NumEltsInStride+l+i];
4272         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4273         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4274           return false;
4275         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4276           return false;
4277         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4278           return false;
4279       }
4280     }
4281   }
4282   return true;
4283 }
4284
4285 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4286 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4287 /// <0, 0, 1, 1>
4288 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4289   unsigned NumElts = VT.getVectorNumElements();
4290   bool Is256BitVec = VT.is256BitVector();
4291
4292   if (VT.is512BitVector())
4293     return false;
4294   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4295          "Unsupported vector type for unpckh");
4296
4297   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4298       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4299     return false;
4300
4301   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4302   // FIXME: Need a better way to get rid of this, there's no latency difference
4303   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4304   // the former later. We should also remove the "_undef" special mask.
4305   if (NumElts == 4 && Is256BitVec)
4306     return false;
4307
4308   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4309   // independently on 128-bit lanes.
4310   unsigned NumLanes = VT.getSizeInBits()/128;
4311   unsigned NumLaneElts = NumElts/NumLanes;
4312
4313   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4314     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4315       int BitI  = Mask[l+i];
4316       int BitI1 = Mask[l+i+1];
4317
4318       if (!isUndefOrEqual(BitI, j))
4319         return false;
4320       if (!isUndefOrEqual(BitI1, j))
4321         return false;
4322     }
4323   }
4324
4325   return true;
4326 }
4327
4328 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4329 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4330 /// <2, 2, 3, 3>
4331 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4332   unsigned NumElts = VT.getVectorNumElements();
4333
4334   if (VT.is512BitVector())
4335     return false;
4336
4337   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4338          "Unsupported vector type for unpckh");
4339
4340   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4341       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4342     return false;
4343
4344   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4345   // independently on 128-bit lanes.
4346   unsigned NumLanes = VT.getSizeInBits()/128;
4347   unsigned NumLaneElts = NumElts/NumLanes;
4348
4349   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4350     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4351       int BitI  = Mask[l+i];
4352       int BitI1 = Mask[l+i+1];
4353       if (!isUndefOrEqual(BitI, j))
4354         return false;
4355       if (!isUndefOrEqual(BitI1, j))
4356         return false;
4357     }
4358   }
4359   return true;
4360 }
4361
4362 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4363 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4364 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4365   if (!VT.is512BitVector())
4366     return false;
4367
4368   unsigned NumElts = VT.getVectorNumElements();
4369   unsigned HalfSize = NumElts/2;
4370   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4371     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4372       *Imm = 1;
4373       return true;
4374     }
4375   }
4376   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4377     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4378       *Imm = 0;
4379       return true;
4380     }
4381   }
4382   return false;
4383 }
4384
4385 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4386 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4387 /// MOVSD, and MOVD, i.e. setting the lowest element.
4388 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4389   if (VT.getVectorElementType().getSizeInBits() < 32)
4390     return false;
4391   if (!VT.is128BitVector())
4392     return false;
4393
4394   unsigned NumElts = VT.getVectorNumElements();
4395
4396   if (!isUndefOrEqual(Mask[0], NumElts))
4397     return false;
4398
4399   for (unsigned i = 1; i != NumElts; ++i)
4400     if (!isUndefOrEqual(Mask[i], i))
4401       return false;
4402
4403   return true;
4404 }
4405
4406 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4407 /// as permutations between 128-bit chunks or halves. As an example: this
4408 /// shuffle bellow:
4409 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4410 /// The first half comes from the second half of V1 and the second half from the
4411 /// the second half of V2.
4412 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4413   if (!HasFp256 || !VT.is256BitVector())
4414     return false;
4415
4416   // The shuffle result is divided into half A and half B. In total the two
4417   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4418   // B must come from C, D, E or F.
4419   unsigned HalfSize = VT.getVectorNumElements()/2;
4420   bool MatchA = false, MatchB = false;
4421
4422   // Check if A comes from one of C, D, E, F.
4423   for (unsigned Half = 0; Half != 4; ++Half) {
4424     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4425       MatchA = true;
4426       break;
4427     }
4428   }
4429
4430   // Check if B comes from one of C, D, E, F.
4431   for (unsigned Half = 0; Half != 4; ++Half) {
4432     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4433       MatchB = true;
4434       break;
4435     }
4436   }
4437
4438   return MatchA && MatchB;
4439 }
4440
4441 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4442 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4443 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4444   MVT VT = SVOp->getSimpleValueType(0);
4445
4446   unsigned HalfSize = VT.getVectorNumElements()/2;
4447
4448   unsigned FstHalf = 0, SndHalf = 0;
4449   for (unsigned i = 0; i < HalfSize; ++i) {
4450     if (SVOp->getMaskElt(i) > 0) {
4451       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4452       break;
4453     }
4454   }
4455   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4456     if (SVOp->getMaskElt(i) > 0) {
4457       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4458       break;
4459     }
4460   }
4461
4462   return (FstHalf | (SndHalf << 4));
4463 }
4464
4465 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4466 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4467   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4468   if (EltSize < 32)
4469     return false;
4470
4471   unsigned NumElts = VT.getVectorNumElements();
4472   Imm8 = 0;
4473   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4474     for (unsigned i = 0; i != NumElts; ++i) {
4475       if (Mask[i] < 0)
4476         continue;
4477       Imm8 |= Mask[i] << (i*2);
4478     }
4479     return true;
4480   }
4481
4482   unsigned LaneSize = 4;
4483   SmallVector<int, 4> MaskVal(LaneSize, -1);
4484
4485   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4486     for (unsigned i = 0; i != LaneSize; ++i) {
4487       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4488         return false;
4489       if (Mask[i+l] < 0)
4490         continue;
4491       if (MaskVal[i] < 0) {
4492         MaskVal[i] = Mask[i+l] - l;
4493         Imm8 |= MaskVal[i] << (i*2);
4494         continue;
4495       }
4496       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4497         return false;
4498     }
4499   }
4500   return true;
4501 }
4502
4503 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4504 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4505 /// Note that VPERMIL mask matching is different depending whether theunderlying
4506 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4507 /// to the same elements of the low, but to the higher half of the source.
4508 /// In VPERMILPD the two lanes could be shuffled independently of each other
4509 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4510 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4511   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4512   if (VT.getSizeInBits() < 256 || EltSize < 32)
4513     return false;
4514   bool symetricMaskRequired = (EltSize == 32);
4515   unsigned NumElts = VT.getVectorNumElements();
4516
4517   unsigned NumLanes = VT.getSizeInBits()/128;
4518   unsigned LaneSize = NumElts/NumLanes;
4519   // 2 or 4 elements in one lane
4520
4521   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4522   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4523     for (unsigned i = 0; i != LaneSize; ++i) {
4524       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4525         return false;
4526       if (symetricMaskRequired) {
4527         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4528           ExpectedMaskVal[i] = Mask[i+l] - l;
4529           continue;
4530         }
4531         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4532           return false;
4533       }
4534     }
4535   }
4536   return true;
4537 }
4538
4539 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4540 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4541 /// element of vector 2 and the other elements to come from vector 1 in order.
4542 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4543                                bool V2IsSplat = false, bool V2IsUndef = false) {
4544   if (!VT.is128BitVector())
4545     return false;
4546
4547   unsigned NumOps = VT.getVectorNumElements();
4548   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4549     return false;
4550
4551   if (!isUndefOrEqual(Mask[0], 0))
4552     return false;
4553
4554   for (unsigned i = 1; i != NumOps; ++i)
4555     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4556           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4557           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4558       return false;
4559
4560   return true;
4561 }
4562
4563 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4564 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4565 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4566 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4567                            const X86Subtarget *Subtarget) {
4568   if (!Subtarget->hasSSE3())
4569     return false;
4570
4571   unsigned NumElems = VT.getVectorNumElements();
4572
4573   if ((VT.is128BitVector() && NumElems != 4) ||
4574       (VT.is256BitVector() && NumElems != 8) ||
4575       (VT.is512BitVector() && NumElems != 16))
4576     return false;
4577
4578   // "i+1" is the value the indexed mask element must have
4579   for (unsigned i = 0; i != NumElems; i += 2)
4580     if (!isUndefOrEqual(Mask[i], i+1) ||
4581         !isUndefOrEqual(Mask[i+1], i+1))
4582       return false;
4583
4584   return true;
4585 }
4586
4587 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4588 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4589 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4590 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4591                            const X86Subtarget *Subtarget) {
4592   if (!Subtarget->hasSSE3())
4593     return false;
4594
4595   unsigned NumElems = VT.getVectorNumElements();
4596
4597   if ((VT.is128BitVector() && NumElems != 4) ||
4598       (VT.is256BitVector() && NumElems != 8) ||
4599       (VT.is512BitVector() && NumElems != 16))
4600     return false;
4601
4602   // "i" is the value the indexed mask element must have
4603   for (unsigned i = 0; i != NumElems; i += 2)
4604     if (!isUndefOrEqual(Mask[i], i) ||
4605         !isUndefOrEqual(Mask[i+1], i))
4606       return false;
4607
4608   return true;
4609 }
4610
4611 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4612 /// specifies a shuffle of elements that is suitable for input to 256-bit
4613 /// version of MOVDDUP.
4614 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4615   if (!HasFp256 || !VT.is256BitVector())
4616     return false;
4617
4618   unsigned NumElts = VT.getVectorNumElements();
4619   if (NumElts != 4)
4620     return false;
4621
4622   for (unsigned i = 0; i != NumElts/2; ++i)
4623     if (!isUndefOrEqual(Mask[i], 0))
4624       return false;
4625   for (unsigned i = NumElts/2; i != NumElts; ++i)
4626     if (!isUndefOrEqual(Mask[i], NumElts/2))
4627       return false;
4628   return true;
4629 }
4630
4631 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4632 /// specifies a shuffle of elements that is suitable for input to 128-bit
4633 /// version of MOVDDUP.
4634 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4635   if (!VT.is128BitVector())
4636     return false;
4637
4638   unsigned e = VT.getVectorNumElements() / 2;
4639   for (unsigned i = 0; i != e; ++i)
4640     if (!isUndefOrEqual(Mask[i], i))
4641       return false;
4642   for (unsigned i = 0; i != e; ++i)
4643     if (!isUndefOrEqual(Mask[e+i], i))
4644       return false;
4645   return true;
4646 }
4647
4648 /// isVEXTRACTIndex - Return true if the specified
4649 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4650 /// suitable for instruction that extract 128 or 256 bit vectors
4651 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4652   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4653   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4654     return false;
4655
4656   // The index should be aligned on a vecWidth-bit boundary.
4657   uint64_t Index =
4658     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4659
4660   MVT VT = N->getSimpleValueType(0);
4661   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4662   bool Result = (Index * ElSize) % vecWidth == 0;
4663
4664   return Result;
4665 }
4666
4667 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4668 /// operand specifies a subvector insert that is suitable for input to
4669 /// insertion of 128 or 256-bit subvectors
4670 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4671   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4672   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4673     return false;
4674   // The index should be aligned on a vecWidth-bit boundary.
4675   uint64_t Index =
4676     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4677
4678   MVT VT = N->getSimpleValueType(0);
4679   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4680   bool Result = (Index * ElSize) % vecWidth == 0;
4681
4682   return Result;
4683 }
4684
4685 bool X86::isVINSERT128Index(SDNode *N) {
4686   return isVINSERTIndex(N, 128);
4687 }
4688
4689 bool X86::isVINSERT256Index(SDNode *N) {
4690   return isVINSERTIndex(N, 256);
4691 }
4692
4693 bool X86::isVEXTRACT128Index(SDNode *N) {
4694   return isVEXTRACTIndex(N, 128);
4695 }
4696
4697 bool X86::isVEXTRACT256Index(SDNode *N) {
4698   return isVEXTRACTIndex(N, 256);
4699 }
4700
4701 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4702 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4703 /// Handles 128-bit and 256-bit.
4704 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4705   MVT VT = N->getSimpleValueType(0);
4706
4707   assert((VT.getSizeInBits() >= 128) &&
4708          "Unsupported vector type for PSHUF/SHUFP");
4709
4710   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4711   // independently on 128-bit lanes.
4712   unsigned NumElts = VT.getVectorNumElements();
4713   unsigned NumLanes = VT.getSizeInBits()/128;
4714   unsigned NumLaneElts = NumElts/NumLanes;
4715
4716   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4717          "Only supports 2, 4 or 8 elements per lane");
4718
4719   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4720   unsigned Mask = 0;
4721   for (unsigned i = 0; i != NumElts; ++i) {
4722     int Elt = N->getMaskElt(i);
4723     if (Elt < 0) continue;
4724     Elt &= NumLaneElts - 1;
4725     unsigned ShAmt = (i << Shift) % 8;
4726     Mask |= Elt << ShAmt;
4727   }
4728
4729   return Mask;
4730 }
4731
4732 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4733 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4734 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4735   MVT VT = N->getSimpleValueType(0);
4736
4737   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4738          "Unsupported vector type for PSHUFHW");
4739
4740   unsigned NumElts = VT.getVectorNumElements();
4741
4742   unsigned Mask = 0;
4743   for (unsigned l = 0; l != NumElts; l += 8) {
4744     // 8 nodes per lane, but we only care about the last 4.
4745     for (unsigned i = 0; i < 4; ++i) {
4746       int Elt = N->getMaskElt(l+i+4);
4747       if (Elt < 0) continue;
4748       Elt &= 0x3; // only 2-bits.
4749       Mask |= Elt << (i * 2);
4750     }
4751   }
4752
4753   return Mask;
4754 }
4755
4756 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4757 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4758 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4759   MVT VT = N->getSimpleValueType(0);
4760
4761   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4762          "Unsupported vector type for PSHUFHW");
4763
4764   unsigned NumElts = VT.getVectorNumElements();
4765
4766   unsigned Mask = 0;
4767   for (unsigned l = 0; l != NumElts; l += 8) {
4768     // 8 nodes per lane, but we only care about the first 4.
4769     for (unsigned i = 0; i < 4; ++i) {
4770       int Elt = N->getMaskElt(l+i);
4771       if (Elt < 0) continue;
4772       Elt &= 0x3; // only 2-bits
4773       Mask |= Elt << (i * 2);
4774     }
4775   }
4776
4777   return Mask;
4778 }
4779
4780 /// \brief Return the appropriate immediate to shuffle the specified
4781 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4782 /// VALIGN (if Interlane is true) instructions.
4783 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4784                                            bool InterLane) {
4785   MVT VT = SVOp->getSimpleValueType(0);
4786   unsigned EltSize = InterLane ? 1 :
4787     VT.getVectorElementType().getSizeInBits() >> 3;
4788
4789   unsigned NumElts = VT.getVectorNumElements();
4790   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4791   unsigned NumLaneElts = NumElts/NumLanes;
4792
4793   int Val = 0;
4794   unsigned i;
4795   for (i = 0; i != NumElts; ++i) {
4796     Val = SVOp->getMaskElt(i);
4797     if (Val >= 0)
4798       break;
4799   }
4800   if (Val >= (int)NumElts)
4801     Val -= NumElts - NumLaneElts;
4802
4803   assert(Val - i > 0 && "PALIGNR imm should be positive");
4804   return (Val - i) * EltSize;
4805 }
4806
4807 /// \brief Return the appropriate immediate to shuffle the specified
4808 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4809 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4810   return getShuffleAlignrImmediate(SVOp, false);
4811 }
4812
4813 /// \brief Return the appropriate immediate to shuffle the specified
4814 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4815 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4816   return getShuffleAlignrImmediate(SVOp, true);
4817 }
4818
4819
4820 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4821   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4822   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4823     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4824
4825   uint64_t Index =
4826     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4827
4828   MVT VecVT = N->getOperand(0).getSimpleValueType();
4829   MVT ElVT = VecVT.getVectorElementType();
4830
4831   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4832   return Index / NumElemsPerChunk;
4833 }
4834
4835 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4836   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4837   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4838     llvm_unreachable("Illegal insert subvector for VINSERT");
4839
4840   uint64_t Index =
4841     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4842
4843   MVT VecVT = N->getSimpleValueType(0);
4844   MVT ElVT = VecVT.getVectorElementType();
4845
4846   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4847   return Index / NumElemsPerChunk;
4848 }
4849
4850 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4851 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4852 /// and VINSERTI128 instructions.
4853 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4854   return getExtractVEXTRACTImmediate(N, 128);
4855 }
4856
4857 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4858 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4859 /// and VINSERTI64x4 instructions.
4860 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4861   return getExtractVEXTRACTImmediate(N, 256);
4862 }
4863
4864 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4865 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4866 /// and VINSERTI128 instructions.
4867 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4868   return getInsertVINSERTImmediate(N, 128);
4869 }
4870
4871 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4872 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4873 /// and VINSERTI64x4 instructions.
4874 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4875   return getInsertVINSERTImmediate(N, 256);
4876 }
4877
4878 /// isZero - Returns true if Elt is a constant integer zero
4879 static bool isZero(SDValue V) {
4880   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4881   return C && C->isNullValue();
4882 }
4883
4884 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4885 /// constant +0.0.
4886 bool X86::isZeroNode(SDValue Elt) {
4887   if (isZero(Elt))
4888     return true;
4889   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4890     return CFP->getValueAPF().isPosZero();
4891   return false;
4892 }
4893
4894 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4895 /// match movhlps. The lower half elements should come from upper half of
4896 /// V1 (and in order), and the upper half elements should come from the upper
4897 /// half of V2 (and in order).
4898 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4899   if (!VT.is128BitVector())
4900     return false;
4901   if (VT.getVectorNumElements() != 4)
4902     return false;
4903   for (unsigned i = 0, e = 2; i != e; ++i)
4904     if (!isUndefOrEqual(Mask[i], i+2))
4905       return false;
4906   for (unsigned i = 2; i != 4; ++i)
4907     if (!isUndefOrEqual(Mask[i], i+4))
4908       return false;
4909   return true;
4910 }
4911
4912 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4913 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4914 /// required.
4915 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4916   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4917     return false;
4918   N = N->getOperand(0).getNode();
4919   if (!ISD::isNON_EXTLoad(N))
4920     return false;
4921   if (LD)
4922     *LD = cast<LoadSDNode>(N);
4923   return true;
4924 }
4925
4926 // Test whether the given value is a vector value which will be legalized
4927 // into a load.
4928 static bool WillBeConstantPoolLoad(SDNode *N) {
4929   if (N->getOpcode() != ISD::BUILD_VECTOR)
4930     return false;
4931
4932   // Check for any non-constant elements.
4933   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4934     switch (N->getOperand(i).getNode()->getOpcode()) {
4935     case ISD::UNDEF:
4936     case ISD::ConstantFP:
4937     case ISD::Constant:
4938       break;
4939     default:
4940       return false;
4941     }
4942
4943   // Vectors of all-zeros and all-ones are materialized with special
4944   // instructions rather than being loaded.
4945   return !ISD::isBuildVectorAllZeros(N) &&
4946          !ISD::isBuildVectorAllOnes(N);
4947 }
4948
4949 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4950 /// match movlp{s|d}. The lower half elements should come from lower half of
4951 /// V1 (and in order), and the upper half elements should come from the upper
4952 /// half of V2 (and in order). And since V1 will become the source of the
4953 /// MOVLP, it must be either a vector load or a scalar load to vector.
4954 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4955                                ArrayRef<int> Mask, MVT VT) {
4956   if (!VT.is128BitVector())
4957     return false;
4958
4959   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4960     return false;
4961   // Is V2 is a vector load, don't do this transformation. We will try to use
4962   // load folding shufps op.
4963   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4964     return false;
4965
4966   unsigned NumElems = VT.getVectorNumElements();
4967
4968   if (NumElems != 2 && NumElems != 4)
4969     return false;
4970   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4971     if (!isUndefOrEqual(Mask[i], i))
4972       return false;
4973   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4974     if (!isUndefOrEqual(Mask[i], i+NumElems))
4975       return false;
4976   return true;
4977 }
4978
4979 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4980 /// to an zero vector.
4981 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4982 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4983   SDValue V1 = N->getOperand(0);
4984   SDValue V2 = N->getOperand(1);
4985   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4986   for (unsigned i = 0; i != NumElems; ++i) {
4987     int Idx = N->getMaskElt(i);
4988     if (Idx >= (int)NumElems) {
4989       unsigned Opc = V2.getOpcode();
4990       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4991         continue;
4992       if (Opc != ISD::BUILD_VECTOR ||
4993           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4994         return false;
4995     } else if (Idx >= 0) {
4996       unsigned Opc = V1.getOpcode();
4997       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4998         continue;
4999       if (Opc != ISD::BUILD_VECTOR ||
5000           !X86::isZeroNode(V1.getOperand(Idx)))
5001         return false;
5002     }
5003   }
5004   return true;
5005 }
5006
5007 /// getZeroVector - Returns a vector of specified type with all zero elements.
5008 ///
5009 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5010                              SelectionDAG &DAG, SDLoc dl) {
5011   assert(VT.isVector() && "Expected a vector type");
5012
5013   // Always build SSE zero vectors as <4 x i32> bitcasted
5014   // to their dest type. This ensures they get CSE'd.
5015   SDValue Vec;
5016   if (VT.is128BitVector()) {  // SSE
5017     if (Subtarget->hasSSE2()) {  // SSE2
5018       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5019       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5020     } else { // SSE1
5021       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5022       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5023     }
5024   } else if (VT.is256BitVector()) { // AVX
5025     if (Subtarget->hasInt256()) { // AVX2
5026       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5027       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5028       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5029     } else {
5030       // 256-bit logic and arithmetic instructions in AVX are all
5031       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5032       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5033       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5034       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5035     }
5036   } else if (VT.is512BitVector()) { // AVX-512
5037       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5038       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5039                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5040       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5041   } else if (VT.getScalarType() == MVT::i1) {
5042     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5043     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5044     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5045     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5046   } else
5047     llvm_unreachable("Unexpected vector type");
5048
5049   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5050 }
5051
5052 /// getOnesVector - Returns a vector of specified type with all bits set.
5053 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5054 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5055 /// Then bitcast to their original type, ensuring they get CSE'd.
5056 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5057                              SDLoc dl) {
5058   assert(VT.isVector() && "Expected a vector type");
5059
5060   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5061   SDValue Vec;
5062   if (VT.is256BitVector()) {
5063     if (HasInt256) { // AVX2
5064       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5065       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5066     } else { // AVX
5067       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5068       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5069     }
5070   } else if (VT.is128BitVector()) {
5071     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5072   } else
5073     llvm_unreachable("Unexpected vector type");
5074
5075   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5076 }
5077
5078 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5079 /// that point to V2 points to its first element.
5080 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5081   for (unsigned i = 0; i != NumElems; ++i) {
5082     if (Mask[i] > (int)NumElems) {
5083       Mask[i] = NumElems;
5084     }
5085   }
5086 }
5087
5088 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5089 /// operation of specified width.
5090 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5091                        SDValue V2) {
5092   unsigned NumElems = VT.getVectorNumElements();
5093   SmallVector<int, 8> Mask;
5094   Mask.push_back(NumElems);
5095   for (unsigned i = 1; i != NumElems; ++i)
5096     Mask.push_back(i);
5097   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5098 }
5099
5100 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5101 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5102                           SDValue V2) {
5103   unsigned NumElems = VT.getVectorNumElements();
5104   SmallVector<int, 8> Mask;
5105   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5106     Mask.push_back(i);
5107     Mask.push_back(i + NumElems);
5108   }
5109   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5110 }
5111
5112 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5113 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5114                           SDValue V2) {
5115   unsigned NumElems = VT.getVectorNumElements();
5116   SmallVector<int, 8> Mask;
5117   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5118     Mask.push_back(i + Half);
5119     Mask.push_back(i + NumElems + Half);
5120   }
5121   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5122 }
5123
5124 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5125 // a generic shuffle instruction because the target has no such instructions.
5126 // Generate shuffles which repeat i16 and i8 several times until they can be
5127 // represented by v4f32 and then be manipulated by target suported shuffles.
5128 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5129   MVT VT = V.getSimpleValueType();
5130   int NumElems = VT.getVectorNumElements();
5131   SDLoc dl(V);
5132
5133   while (NumElems > 4) {
5134     if (EltNo < NumElems/2) {
5135       V = getUnpackl(DAG, dl, VT, V, V);
5136     } else {
5137       V = getUnpackh(DAG, dl, VT, V, V);
5138       EltNo -= NumElems/2;
5139     }
5140     NumElems >>= 1;
5141   }
5142   return V;
5143 }
5144
5145 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5146 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5147   MVT VT = V.getSimpleValueType();
5148   SDLoc dl(V);
5149
5150   if (VT.is128BitVector()) {
5151     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5152     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5153     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5154                              &SplatMask[0]);
5155   } else if (VT.is256BitVector()) {
5156     // To use VPERMILPS to splat scalars, the second half of indicies must
5157     // refer to the higher part, which is a duplication of the lower one,
5158     // because VPERMILPS can only handle in-lane permutations.
5159     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5160                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5161
5162     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5163     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5164                              &SplatMask[0]);
5165   } else
5166     llvm_unreachable("Vector size not supported");
5167
5168   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5169 }
5170
5171 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5172 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5173   MVT SrcVT = SV->getSimpleValueType(0);
5174   SDValue V1 = SV->getOperand(0);
5175   SDLoc dl(SV);
5176
5177   int EltNo = SV->getSplatIndex();
5178   int NumElems = SrcVT.getVectorNumElements();
5179   bool Is256BitVec = SrcVT.is256BitVector();
5180
5181   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5182          "Unknown how to promote splat for type");
5183
5184   // Extract the 128-bit part containing the splat element and update
5185   // the splat element index when it refers to the higher register.
5186   if (Is256BitVec) {
5187     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5188     if (EltNo >= NumElems/2)
5189       EltNo -= NumElems/2;
5190   }
5191
5192   // All i16 and i8 vector types can't be used directly by a generic shuffle
5193   // instruction because the target has no such instruction. Generate shuffles
5194   // which repeat i16 and i8 several times until they fit in i32, and then can
5195   // be manipulated by target suported shuffles.
5196   MVT EltVT = SrcVT.getVectorElementType();
5197   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5198     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5199
5200   // Recreate the 256-bit vector and place the same 128-bit vector
5201   // into the low and high part. This is necessary because we want
5202   // to use VPERM* to shuffle the vectors
5203   if (Is256BitVec) {
5204     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5205   }
5206
5207   return getLegalSplat(DAG, V1, EltNo);
5208 }
5209
5210 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5211 /// vector of zero or undef vector.  This produces a shuffle where the low
5212 /// element of V2 is swizzled into the zero/undef vector, landing at element
5213 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5214 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5215                                            bool IsZero,
5216                                            const X86Subtarget *Subtarget,
5217                                            SelectionDAG &DAG) {
5218   MVT VT = V2.getSimpleValueType();
5219   SDValue V1 = IsZero
5220     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5221   unsigned NumElems = VT.getVectorNumElements();
5222   SmallVector<int, 16> MaskVec;
5223   for (unsigned i = 0; i != NumElems; ++i)
5224     // If this is the insertion idx, put the low elt of V2 here.
5225     MaskVec.push_back(i == Idx ? NumElems : i);
5226   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5227 }
5228
5229 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5230 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5231 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5232 /// shuffles which use a single input multiple times, and in those cases it will
5233 /// adjust the mask to only have indices within that single input.
5234 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5235                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5236   unsigned NumElems = VT.getVectorNumElements();
5237   SDValue ImmN;
5238
5239   IsUnary = false;
5240   bool IsFakeUnary = false;
5241   switch(N->getOpcode()) {
5242   case X86ISD::SHUFP:
5243     ImmN = N->getOperand(N->getNumOperands()-1);
5244     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5245     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5246     break;
5247   case X86ISD::UNPCKH:
5248     DecodeUNPCKHMask(VT, Mask);
5249     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5250     break;
5251   case X86ISD::UNPCKL:
5252     DecodeUNPCKLMask(VT, Mask);
5253     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5254     break;
5255   case X86ISD::MOVHLPS:
5256     DecodeMOVHLPSMask(NumElems, Mask);
5257     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5258     break;
5259   case X86ISD::MOVLHPS:
5260     DecodeMOVLHPSMask(NumElems, Mask);
5261     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5262     break;
5263   case X86ISD::PALIGNR:
5264     ImmN = N->getOperand(N->getNumOperands()-1);
5265     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5266     break;
5267   case X86ISD::PSHUFD:
5268   case X86ISD::VPERMILP:
5269     ImmN = N->getOperand(N->getNumOperands()-1);
5270     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5271     IsUnary = true;
5272     break;
5273   case X86ISD::PSHUFHW:
5274     ImmN = N->getOperand(N->getNumOperands()-1);
5275     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5276     IsUnary = true;
5277     break;
5278   case X86ISD::PSHUFLW:
5279     ImmN = N->getOperand(N->getNumOperands()-1);
5280     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5281     IsUnary = true;
5282     break;
5283   case X86ISD::PSHUFB: {
5284     IsUnary = true;
5285     SDValue MaskNode = N->getOperand(1);
5286     while (MaskNode->getOpcode() == ISD::BITCAST)
5287       MaskNode = MaskNode->getOperand(0);
5288
5289     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5290       // If we have a build-vector, then things are easy.
5291       EVT VT = MaskNode.getValueType();
5292       assert(VT.isVector() &&
5293              "Can't produce a non-vector with a build_vector!");
5294       if (!VT.isInteger())
5295         return false;
5296
5297       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5298
5299       SmallVector<uint64_t, 32> RawMask;
5300       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5301         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5302         if (!CN)
5303           return false;
5304         APInt MaskElement = CN->getAPIntValue();
5305
5306         // We now have to decode the element which could be any integer size and
5307         // extract each byte of it.
5308         for (int j = 0; j < NumBytesPerElement; ++j) {
5309           // Note that this is x86 and so always little endian: the low byte is
5310           // the first byte of the mask.
5311           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5312           MaskElement = MaskElement.lshr(8);
5313         }
5314       }
5315       DecodePSHUFBMask(RawMask, Mask);
5316       break;
5317     }
5318
5319     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5320     if (!MaskLoad)
5321       return false;
5322
5323     SDValue Ptr = MaskLoad->getBasePtr();
5324     if (Ptr->getOpcode() == X86ISD::Wrapper)
5325       Ptr = Ptr->getOperand(0);
5326
5327     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5328     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5329       return false;
5330
5331     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5332       // FIXME: Support AVX-512 here.
5333       if (!C->getType()->isVectorTy() ||
5334           (C->getNumElements() != 16 && C->getNumElements() != 32))
5335         return false;
5336
5337       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5338       DecodePSHUFBMask(C, Mask);
5339       break;
5340     }
5341
5342     return false;
5343   }
5344   case X86ISD::VPERMI:
5345     ImmN = N->getOperand(N->getNumOperands()-1);
5346     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5347     IsUnary = true;
5348     break;
5349   case X86ISD::MOVSS:
5350   case X86ISD::MOVSD: {
5351     // The index 0 always comes from the first element of the second source,
5352     // this is why MOVSS and MOVSD are used in the first place. The other
5353     // elements come from the other positions of the first source vector
5354     Mask.push_back(NumElems);
5355     for (unsigned i = 1; i != NumElems; ++i) {
5356       Mask.push_back(i);
5357     }
5358     break;
5359   }
5360   case X86ISD::VPERM2X128:
5361     ImmN = N->getOperand(N->getNumOperands()-1);
5362     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5363     if (Mask.empty()) return false;
5364     break;
5365   case X86ISD::MOVDDUP:
5366   case X86ISD::MOVLHPD:
5367   case X86ISD::MOVLPD:
5368   case X86ISD::MOVLPS:
5369   case X86ISD::MOVSHDUP:
5370   case X86ISD::MOVSLDUP:
5371     // Not yet implemented
5372     return false;
5373   default: llvm_unreachable("unknown target shuffle node");
5374   }
5375
5376   // If we have a fake unary shuffle, the shuffle mask is spread across two
5377   // inputs that are actually the same node. Re-map the mask to always point
5378   // into the first input.
5379   if (IsFakeUnary)
5380     for (int &M : Mask)
5381       if (M >= (int)Mask.size())
5382         M -= Mask.size();
5383
5384   return true;
5385 }
5386
5387 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5388 /// element of the result of the vector shuffle.
5389 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5390                                    unsigned Depth) {
5391   if (Depth == 6)
5392     return SDValue();  // Limit search depth.
5393
5394   SDValue V = SDValue(N, 0);
5395   EVT VT = V.getValueType();
5396   unsigned Opcode = V.getOpcode();
5397
5398   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5399   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5400     int Elt = SV->getMaskElt(Index);
5401
5402     if (Elt < 0)
5403       return DAG.getUNDEF(VT.getVectorElementType());
5404
5405     unsigned NumElems = VT.getVectorNumElements();
5406     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5407                                          : SV->getOperand(1);
5408     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5409   }
5410
5411   // Recurse into target specific vector shuffles to find scalars.
5412   if (isTargetShuffle(Opcode)) {
5413     MVT ShufVT = V.getSimpleValueType();
5414     unsigned NumElems = ShufVT.getVectorNumElements();
5415     SmallVector<int, 16> ShuffleMask;
5416     bool IsUnary;
5417
5418     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5419       return SDValue();
5420
5421     int Elt = ShuffleMask[Index];
5422     if (Elt < 0)
5423       return DAG.getUNDEF(ShufVT.getVectorElementType());
5424
5425     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5426                                          : N->getOperand(1);
5427     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5428                                Depth+1);
5429   }
5430
5431   // Actual nodes that may contain scalar elements
5432   if (Opcode == ISD::BITCAST) {
5433     V = V.getOperand(0);
5434     EVT SrcVT = V.getValueType();
5435     unsigned NumElems = VT.getVectorNumElements();
5436
5437     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5438       return SDValue();
5439   }
5440
5441   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5442     return (Index == 0) ? V.getOperand(0)
5443                         : DAG.getUNDEF(VT.getVectorElementType());
5444
5445   if (V.getOpcode() == ISD::BUILD_VECTOR)
5446     return V.getOperand(Index);
5447
5448   return SDValue();
5449 }
5450
5451 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5452 /// shuffle operation which come from a consecutively from a zero. The
5453 /// search can start in two different directions, from left or right.
5454 /// We count undefs as zeros until PreferredNum is reached.
5455 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5456                                          unsigned NumElems, bool ZerosFromLeft,
5457                                          SelectionDAG &DAG,
5458                                          unsigned PreferredNum = -1U) {
5459   unsigned NumZeros = 0;
5460   for (unsigned i = 0; i != NumElems; ++i) {
5461     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5462     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5463     if (!Elt.getNode())
5464       break;
5465
5466     if (X86::isZeroNode(Elt))
5467       ++NumZeros;
5468     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5469       NumZeros = std::min(NumZeros + 1, PreferredNum);
5470     else
5471       break;
5472   }
5473
5474   return NumZeros;
5475 }
5476
5477 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5478 /// correspond consecutively to elements from one of the vector operands,
5479 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5480 static
5481 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5482                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5483                               unsigned NumElems, unsigned &OpNum) {
5484   bool SeenV1 = false;
5485   bool SeenV2 = false;
5486
5487   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5488     int Idx = SVOp->getMaskElt(i);
5489     // Ignore undef indicies
5490     if (Idx < 0)
5491       continue;
5492
5493     if (Idx < (int)NumElems)
5494       SeenV1 = true;
5495     else
5496       SeenV2 = true;
5497
5498     // Only accept consecutive elements from the same vector
5499     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5500       return false;
5501   }
5502
5503   OpNum = SeenV1 ? 0 : 1;
5504   return true;
5505 }
5506
5507 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5508 /// logical left shift of a vector.
5509 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5510                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5511   unsigned NumElems =
5512     SVOp->getSimpleValueType(0).getVectorNumElements();
5513   unsigned NumZeros = getNumOfConsecutiveZeros(
5514       SVOp, NumElems, false /* check zeros from right */, DAG,
5515       SVOp->getMaskElt(0));
5516   unsigned OpSrc;
5517
5518   if (!NumZeros)
5519     return false;
5520
5521   // Considering the elements in the mask that are not consecutive zeros,
5522   // check if they consecutively come from only one of the source vectors.
5523   //
5524   //               V1 = {X, A, B, C}     0
5525   //                         \  \  \    /
5526   //   vector_shuffle V1, V2 <1, 2, 3, X>
5527   //
5528   if (!isShuffleMaskConsecutive(SVOp,
5529             0,                   // Mask Start Index
5530             NumElems-NumZeros,   // Mask End Index(exclusive)
5531             NumZeros,            // Where to start looking in the src vector
5532             NumElems,            // Number of elements in vector
5533             OpSrc))              // Which source operand ?
5534     return false;
5535
5536   isLeft = false;
5537   ShAmt = NumZeros;
5538   ShVal = SVOp->getOperand(OpSrc);
5539   return true;
5540 }
5541
5542 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5543 /// logical left shift of a vector.
5544 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5545                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5546   unsigned NumElems =
5547     SVOp->getSimpleValueType(0).getVectorNumElements();
5548   unsigned NumZeros = getNumOfConsecutiveZeros(
5549       SVOp, NumElems, true /* check zeros from left */, DAG,
5550       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5551   unsigned OpSrc;
5552
5553   if (!NumZeros)
5554     return false;
5555
5556   // Considering the elements in the mask that are not consecutive zeros,
5557   // check if they consecutively come from only one of the source vectors.
5558   //
5559   //                           0    { A, B, X, X } = V2
5560   //                          / \    /  /
5561   //   vector_shuffle V1, V2 <X, X, 4, 5>
5562   //
5563   if (!isShuffleMaskConsecutive(SVOp,
5564             NumZeros,     // Mask Start Index
5565             NumElems,     // Mask End Index(exclusive)
5566             0,            // Where to start looking in the src vector
5567             NumElems,     // Number of elements in vector
5568             OpSrc))       // Which source operand ?
5569     return false;
5570
5571   isLeft = true;
5572   ShAmt = NumZeros;
5573   ShVal = SVOp->getOperand(OpSrc);
5574   return true;
5575 }
5576
5577 /// isVectorShift - Returns true if the shuffle can be implemented as a
5578 /// logical left or right shift of a vector.
5579 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5580                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5581   // Although the logic below support any bitwidth size, there are no
5582   // shift instructions which handle more than 128-bit vectors.
5583   if (!SVOp->getSimpleValueType(0).is128BitVector())
5584     return false;
5585
5586   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5587       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5588     return true;
5589
5590   return false;
5591 }
5592
5593 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5594 ///
5595 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5596                                        unsigned NumNonZero, unsigned NumZero,
5597                                        SelectionDAG &DAG,
5598                                        const X86Subtarget* Subtarget,
5599                                        const TargetLowering &TLI) {
5600   if (NumNonZero > 8)
5601     return SDValue();
5602
5603   SDLoc dl(Op);
5604   SDValue V;
5605   bool First = true;
5606   for (unsigned i = 0; i < 16; ++i) {
5607     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5608     if (ThisIsNonZero && First) {
5609       if (NumZero)
5610         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5611       else
5612         V = DAG.getUNDEF(MVT::v8i16);
5613       First = false;
5614     }
5615
5616     if ((i & 1) != 0) {
5617       SDValue ThisElt, LastElt;
5618       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5619       if (LastIsNonZero) {
5620         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5621                               MVT::i16, Op.getOperand(i-1));
5622       }
5623       if (ThisIsNonZero) {
5624         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5625         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5626                               ThisElt, DAG.getConstant(8, MVT::i8));
5627         if (LastIsNonZero)
5628           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5629       } else
5630         ThisElt = LastElt;
5631
5632       if (ThisElt.getNode())
5633         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5634                         DAG.getIntPtrConstant(i/2));
5635     }
5636   }
5637
5638   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5639 }
5640
5641 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5642 ///
5643 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5644                                      unsigned NumNonZero, unsigned NumZero,
5645                                      SelectionDAG &DAG,
5646                                      const X86Subtarget* Subtarget,
5647                                      const TargetLowering &TLI) {
5648   if (NumNonZero > 4)
5649     return SDValue();
5650
5651   SDLoc dl(Op);
5652   SDValue V;
5653   bool First = true;
5654   for (unsigned i = 0; i < 8; ++i) {
5655     bool isNonZero = (NonZeros & (1 << i)) != 0;
5656     if (isNonZero) {
5657       if (First) {
5658         if (NumZero)
5659           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5660         else
5661           V = DAG.getUNDEF(MVT::v8i16);
5662         First = false;
5663       }
5664       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5665                       MVT::v8i16, V, Op.getOperand(i),
5666                       DAG.getIntPtrConstant(i));
5667     }
5668   }
5669
5670   return V;
5671 }
5672
5673 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5674 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5675                                      unsigned NonZeros, unsigned NumNonZero,
5676                                      unsigned NumZero, SelectionDAG &DAG,
5677                                      const X86Subtarget *Subtarget,
5678                                      const TargetLowering &TLI) {
5679   // We know there's at least one non-zero element
5680   unsigned FirstNonZeroIdx = 0;
5681   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5682   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5683          X86::isZeroNode(FirstNonZero)) {
5684     ++FirstNonZeroIdx;
5685     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5686   }
5687
5688   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5689       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5690     return SDValue();
5691
5692   SDValue V = FirstNonZero.getOperand(0);
5693   MVT VVT = V.getSimpleValueType();
5694   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5695     return SDValue();
5696
5697   unsigned FirstNonZeroDst =
5698       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5699   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5700   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5701   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5702
5703   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5704     SDValue Elem = Op.getOperand(Idx);
5705     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5706       continue;
5707
5708     // TODO: What else can be here? Deal with it.
5709     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5710       return SDValue();
5711
5712     // TODO: Some optimizations are still possible here
5713     // ex: Getting one element from a vector, and the rest from another.
5714     if (Elem.getOperand(0) != V)
5715       return SDValue();
5716
5717     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5718     if (Dst == Idx)
5719       ++CorrectIdx;
5720     else if (IncorrectIdx == -1U) {
5721       IncorrectIdx = Idx;
5722       IncorrectDst = Dst;
5723     } else
5724       // There was already one element with an incorrect index.
5725       // We can't optimize this case to an insertps.
5726       return SDValue();
5727   }
5728
5729   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5730     SDLoc dl(Op);
5731     EVT VT = Op.getSimpleValueType();
5732     unsigned ElementMoveMask = 0;
5733     if (IncorrectIdx == -1U)
5734       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5735     else
5736       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5737
5738     SDValue InsertpsMask =
5739         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5740     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5741   }
5742
5743   return SDValue();
5744 }
5745
5746 /// getVShift - Return a vector logical shift node.
5747 ///
5748 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5749                          unsigned NumBits, SelectionDAG &DAG,
5750                          const TargetLowering &TLI, SDLoc dl) {
5751   assert(VT.is128BitVector() && "Unknown type for VShift");
5752   EVT ShVT = MVT::v2i64;
5753   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5754   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5755   return DAG.getNode(ISD::BITCAST, dl, VT,
5756                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5757                              DAG.getConstant(NumBits,
5758                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5759 }
5760
5761 static SDValue
5762 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5763
5764   // Check if the scalar load can be widened into a vector load. And if
5765   // the address is "base + cst" see if the cst can be "absorbed" into
5766   // the shuffle mask.
5767   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5768     SDValue Ptr = LD->getBasePtr();
5769     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5770       return SDValue();
5771     EVT PVT = LD->getValueType(0);
5772     if (PVT != MVT::i32 && PVT != MVT::f32)
5773       return SDValue();
5774
5775     int FI = -1;
5776     int64_t Offset = 0;
5777     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5778       FI = FINode->getIndex();
5779       Offset = 0;
5780     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5781                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5782       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5783       Offset = Ptr.getConstantOperandVal(1);
5784       Ptr = Ptr.getOperand(0);
5785     } else {
5786       return SDValue();
5787     }
5788
5789     // FIXME: 256-bit vector instructions don't require a strict alignment,
5790     // improve this code to support it better.
5791     unsigned RequiredAlign = VT.getSizeInBits()/8;
5792     SDValue Chain = LD->getChain();
5793     // Make sure the stack object alignment is at least 16 or 32.
5794     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5795     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5796       if (MFI->isFixedObjectIndex(FI)) {
5797         // Can't change the alignment. FIXME: It's possible to compute
5798         // the exact stack offset and reference FI + adjust offset instead.
5799         // If someone *really* cares about this. That's the way to implement it.
5800         return SDValue();
5801       } else {
5802         MFI->setObjectAlignment(FI, RequiredAlign);
5803       }
5804     }
5805
5806     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5807     // Ptr + (Offset & ~15).
5808     if (Offset < 0)
5809       return SDValue();
5810     if ((Offset % RequiredAlign) & 3)
5811       return SDValue();
5812     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5813     if (StartOffset)
5814       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5815                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5816
5817     int EltNo = (Offset - StartOffset) >> 2;
5818     unsigned NumElems = VT.getVectorNumElements();
5819
5820     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5821     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5822                              LD->getPointerInfo().getWithOffset(StartOffset),
5823                              false, false, false, 0);
5824
5825     SmallVector<int, 8> Mask;
5826     for (unsigned i = 0; i != NumElems; ++i)
5827       Mask.push_back(EltNo);
5828
5829     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5830   }
5831
5832   return SDValue();
5833 }
5834
5835 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5836 /// vector of type 'VT', see if the elements can be replaced by a single large
5837 /// load which has the same value as a build_vector whose operands are 'elts'.
5838 ///
5839 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5840 ///
5841 /// FIXME: we'd also like to handle the case where the last elements are zero
5842 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5843 /// There's even a handy isZeroNode for that purpose.
5844 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5845                                         SDLoc &DL, SelectionDAG &DAG,
5846                                         bool isAfterLegalize) {
5847   EVT EltVT = VT.getVectorElementType();
5848   unsigned NumElems = Elts.size();
5849
5850   LoadSDNode *LDBase = nullptr;
5851   unsigned LastLoadedElt = -1U;
5852
5853   // For each element in the initializer, see if we've found a load or an undef.
5854   // If we don't find an initial load element, or later load elements are
5855   // non-consecutive, bail out.
5856   for (unsigned i = 0; i < NumElems; ++i) {
5857     SDValue Elt = Elts[i];
5858
5859     if (!Elt.getNode() ||
5860         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5861       return SDValue();
5862     if (!LDBase) {
5863       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5864         return SDValue();
5865       LDBase = cast<LoadSDNode>(Elt.getNode());
5866       LastLoadedElt = i;
5867       continue;
5868     }
5869     if (Elt.getOpcode() == ISD::UNDEF)
5870       continue;
5871
5872     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5873     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5874       return SDValue();
5875     LastLoadedElt = i;
5876   }
5877
5878   // If we have found an entire vector of loads and undefs, then return a large
5879   // load of the entire vector width starting at the base pointer.  If we found
5880   // consecutive loads for the low half, generate a vzext_load node.
5881   if (LastLoadedElt == NumElems - 1) {
5882
5883     if (isAfterLegalize &&
5884         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5885       return SDValue();
5886
5887     SDValue NewLd = SDValue();
5888
5889     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5890       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5891                           LDBase->getPointerInfo(),
5892                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5893                           LDBase->isInvariant(), 0);
5894     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5895                         LDBase->getPointerInfo(),
5896                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5897                         LDBase->isInvariant(), LDBase->getAlignment());
5898
5899     if (LDBase->hasAnyUseOfValue(1)) {
5900       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5901                                      SDValue(LDBase, 1),
5902                                      SDValue(NewLd.getNode(), 1));
5903       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5904       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5905                              SDValue(NewLd.getNode(), 1));
5906     }
5907
5908     return NewLd;
5909   }
5910   if (NumElems == 4 && LastLoadedElt == 1 &&
5911       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5912     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5913     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5914     SDValue ResNode =
5915         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5916                                 LDBase->getPointerInfo(),
5917                                 LDBase->getAlignment(),
5918                                 false/*isVolatile*/, true/*ReadMem*/,
5919                                 false/*WriteMem*/);
5920
5921     // Make sure the newly-created LOAD is in the same position as LDBase in
5922     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5923     // update uses of LDBase's output chain to use the TokenFactor.
5924     if (LDBase->hasAnyUseOfValue(1)) {
5925       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5926                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5927       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5928       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5929                              SDValue(ResNode.getNode(), 1));
5930     }
5931
5932     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5933   }
5934   return SDValue();
5935 }
5936
5937 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5938 /// to generate a splat value for the following cases:
5939 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5940 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5941 /// a scalar load, or a constant.
5942 /// The VBROADCAST node is returned when a pattern is found,
5943 /// or SDValue() otherwise.
5944 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5945                                     SelectionDAG &DAG) {
5946   if (!Subtarget->hasFp256())
5947     return SDValue();
5948
5949   MVT VT = Op.getSimpleValueType();
5950   SDLoc dl(Op);
5951
5952   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5953          "Unsupported vector type for broadcast.");
5954
5955   SDValue Ld;
5956   bool ConstSplatVal;
5957
5958   switch (Op.getOpcode()) {
5959     default:
5960       // Unknown pattern found.
5961       return SDValue();
5962
5963     case ISD::BUILD_VECTOR: {
5964       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5965       BitVector UndefElements;
5966       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5967
5968       // We need a splat of a single value to use broadcast, and it doesn't
5969       // make any sense if the value is only in one element of the vector.
5970       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5971         return SDValue();
5972
5973       Ld = Splat;
5974       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5975                        Ld.getOpcode() == ISD::ConstantFP);
5976
5977       // Make sure that all of the users of a non-constant load are from the
5978       // BUILD_VECTOR node.
5979       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5980         return SDValue();
5981       break;
5982     }
5983
5984     case ISD::VECTOR_SHUFFLE: {
5985       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5986
5987       // Shuffles must have a splat mask where the first element is
5988       // broadcasted.
5989       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5990         return SDValue();
5991
5992       SDValue Sc = Op.getOperand(0);
5993       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5994           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5995
5996         if (!Subtarget->hasInt256())
5997           return SDValue();
5998
5999         // Use the register form of the broadcast instruction available on AVX2.
6000         if (VT.getSizeInBits() >= 256)
6001           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6002         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6003       }
6004
6005       Ld = Sc.getOperand(0);
6006       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6007                        Ld.getOpcode() == ISD::ConstantFP);
6008
6009       // The scalar_to_vector node and the suspected
6010       // load node must have exactly one user.
6011       // Constants may have multiple users.
6012
6013       // AVX-512 has register version of the broadcast
6014       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6015         Ld.getValueType().getSizeInBits() >= 32;
6016       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6017           !hasRegVer))
6018         return SDValue();
6019       break;
6020     }
6021   }
6022
6023   bool IsGE256 = (VT.getSizeInBits() >= 256);
6024
6025   // Handle the broadcasting a single constant scalar from the constant pool
6026   // into a vector. On Sandybridge it is still better to load a constant vector
6027   // from the constant pool and not to broadcast it from a scalar.
6028   if (ConstSplatVal && Subtarget->hasInt256()) {
6029     EVT CVT = Ld.getValueType();
6030     assert(!CVT.isVector() && "Must not broadcast a vector type");
6031     unsigned ScalarSize = CVT.getSizeInBits();
6032
6033     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
6034       const Constant *C = nullptr;
6035       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6036         C = CI->getConstantIntValue();
6037       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6038         C = CF->getConstantFPValue();
6039
6040       assert(C && "Invalid constant type");
6041
6042       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6043       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6044       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6045       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6046                        MachinePointerInfo::getConstantPool(),
6047                        false, false, false, Alignment);
6048
6049       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6050     }
6051   }
6052
6053   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6054   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6055
6056   // Handle AVX2 in-register broadcasts.
6057   if (!IsLoad && Subtarget->hasInt256() &&
6058       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6059     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6060
6061   // The scalar source must be a normal load.
6062   if (!IsLoad)
6063     return SDValue();
6064
6065   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6066     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6067
6068   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6069   // double since there is no vbroadcastsd xmm
6070   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6071     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6072       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6073   }
6074
6075   // Unsupported broadcast.
6076   return SDValue();
6077 }
6078
6079 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6080 /// underlying vector and index.
6081 ///
6082 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6083 /// index.
6084 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6085                                          SDValue ExtIdx) {
6086   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6087   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6088     return Idx;
6089
6090   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6091   // lowered this:
6092   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6093   // to:
6094   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6095   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6096   //                           undef)
6097   //                       Constant<0>)
6098   // In this case the vector is the extract_subvector expression and the index
6099   // is 2, as specified by the shuffle.
6100   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6101   SDValue ShuffleVec = SVOp->getOperand(0);
6102   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6103   assert(ShuffleVecVT.getVectorElementType() ==
6104          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6105
6106   int ShuffleIdx = SVOp->getMaskElt(Idx);
6107   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6108     ExtractedFromVec = ShuffleVec;
6109     return ShuffleIdx;
6110   }
6111   return Idx;
6112 }
6113
6114 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6115   MVT VT = Op.getSimpleValueType();
6116
6117   // Skip if insert_vec_elt is not supported.
6118   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6119   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6120     return SDValue();
6121
6122   SDLoc DL(Op);
6123   unsigned NumElems = Op.getNumOperands();
6124
6125   SDValue VecIn1;
6126   SDValue VecIn2;
6127   SmallVector<unsigned, 4> InsertIndices;
6128   SmallVector<int, 8> Mask(NumElems, -1);
6129
6130   for (unsigned i = 0; i != NumElems; ++i) {
6131     unsigned Opc = Op.getOperand(i).getOpcode();
6132
6133     if (Opc == ISD::UNDEF)
6134       continue;
6135
6136     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6137       // Quit if more than 1 elements need inserting.
6138       if (InsertIndices.size() > 1)
6139         return SDValue();
6140
6141       InsertIndices.push_back(i);
6142       continue;
6143     }
6144
6145     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6146     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6147     // Quit if non-constant index.
6148     if (!isa<ConstantSDNode>(ExtIdx))
6149       return SDValue();
6150     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6151
6152     // Quit if extracted from vector of different type.
6153     if (ExtractedFromVec.getValueType() != VT)
6154       return SDValue();
6155
6156     if (!VecIn1.getNode())
6157       VecIn1 = ExtractedFromVec;
6158     else if (VecIn1 != ExtractedFromVec) {
6159       if (!VecIn2.getNode())
6160         VecIn2 = ExtractedFromVec;
6161       else if (VecIn2 != ExtractedFromVec)
6162         // Quit if more than 2 vectors to shuffle
6163         return SDValue();
6164     }
6165
6166     if (ExtractedFromVec == VecIn1)
6167       Mask[i] = Idx;
6168     else if (ExtractedFromVec == VecIn2)
6169       Mask[i] = Idx + NumElems;
6170   }
6171
6172   if (!VecIn1.getNode())
6173     return SDValue();
6174
6175   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6176   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6177   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6178     unsigned Idx = InsertIndices[i];
6179     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6180                      DAG.getIntPtrConstant(Idx));
6181   }
6182
6183   return NV;
6184 }
6185
6186 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6187 SDValue
6188 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6189
6190   MVT VT = Op.getSimpleValueType();
6191   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6192          "Unexpected type in LowerBUILD_VECTORvXi1!");
6193
6194   SDLoc dl(Op);
6195   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6196     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6197     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6198     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6199   }
6200
6201   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6202     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6203     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6204     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6205   }
6206
6207   bool AllContants = true;
6208   uint64_t Immediate = 0;
6209   int NonConstIdx = -1;
6210   bool IsSplat = true;
6211   unsigned NumNonConsts = 0;
6212   unsigned NumConsts = 0;
6213   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6214     SDValue In = Op.getOperand(idx);
6215     if (In.getOpcode() == ISD::UNDEF)
6216       continue;
6217     if (!isa<ConstantSDNode>(In)) {
6218       AllContants = false;
6219       NonConstIdx = idx;
6220       NumNonConsts++;
6221     }
6222     else {
6223       NumConsts++;
6224       if (cast<ConstantSDNode>(In)->getZExtValue())
6225       Immediate |= (1ULL << idx);
6226     }
6227     if (In != Op.getOperand(0))
6228       IsSplat = false;
6229   }
6230
6231   if (AllContants) {
6232     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6233       DAG.getConstant(Immediate, MVT::i16));
6234     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6235                        DAG.getIntPtrConstant(0));
6236   }
6237
6238   if (NumNonConsts == 1 && NonConstIdx != 0) {
6239     SDValue DstVec;
6240     if (NumConsts) {
6241       SDValue VecAsImm = DAG.getConstant(Immediate,
6242                                          MVT::getIntegerVT(VT.getSizeInBits()));
6243       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6244     }
6245     else 
6246       DstVec = DAG.getUNDEF(VT);
6247     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6248                        Op.getOperand(NonConstIdx),
6249                        DAG.getIntPtrConstant(NonConstIdx));
6250   }
6251   if (!IsSplat && (NonConstIdx != 0))
6252     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6253   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6254   SDValue Select;
6255   if (IsSplat)
6256     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6257                           DAG.getConstant(-1, SelectVT),
6258                           DAG.getConstant(0, SelectVT));
6259   else
6260     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6261                          DAG.getConstant((Immediate | 1), SelectVT),
6262                          DAG.getConstant(Immediate, SelectVT));
6263   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6264 }
6265
6266 /// \brief Return true if \p N implements a horizontal binop and return the
6267 /// operands for the horizontal binop into V0 and V1.
6268 /// 
6269 /// This is a helper function of PerformBUILD_VECTORCombine.
6270 /// This function checks that the build_vector \p N in input implements a
6271 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6272 /// operation to match.
6273 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6274 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6275 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6276 /// arithmetic sub.
6277 ///
6278 /// This function only analyzes elements of \p N whose indices are
6279 /// in range [BaseIdx, LastIdx).
6280 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6281                               SelectionDAG &DAG,
6282                               unsigned BaseIdx, unsigned LastIdx,
6283                               SDValue &V0, SDValue &V1) {
6284   EVT VT = N->getValueType(0);
6285
6286   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6287   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6288          "Invalid Vector in input!");
6289   
6290   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6291   bool CanFold = true;
6292   unsigned ExpectedVExtractIdx = BaseIdx;
6293   unsigned NumElts = LastIdx - BaseIdx;
6294   V0 = DAG.getUNDEF(VT);
6295   V1 = DAG.getUNDEF(VT);
6296
6297   // Check if N implements a horizontal binop.
6298   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6299     SDValue Op = N->getOperand(i + BaseIdx);
6300
6301     // Skip UNDEFs.
6302     if (Op->getOpcode() == ISD::UNDEF) {
6303       // Update the expected vector extract index.
6304       if (i * 2 == NumElts)
6305         ExpectedVExtractIdx = BaseIdx;
6306       ExpectedVExtractIdx += 2;
6307       continue;
6308     }
6309
6310     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6311
6312     if (!CanFold)
6313       break;
6314
6315     SDValue Op0 = Op.getOperand(0);
6316     SDValue Op1 = Op.getOperand(1);
6317
6318     // Try to match the following pattern:
6319     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6320     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6321         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6322         Op0.getOperand(0) == Op1.getOperand(0) &&
6323         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6324         isa<ConstantSDNode>(Op1.getOperand(1)));
6325     if (!CanFold)
6326       break;
6327
6328     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6329     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6330
6331     if (i * 2 < NumElts) {
6332       if (V0.getOpcode() == ISD::UNDEF)
6333         V0 = Op0.getOperand(0);
6334     } else {
6335       if (V1.getOpcode() == ISD::UNDEF)
6336         V1 = Op0.getOperand(0);
6337       if (i * 2 == NumElts)
6338         ExpectedVExtractIdx = BaseIdx;
6339     }
6340
6341     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6342     if (I0 == ExpectedVExtractIdx)
6343       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6344     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6345       // Try to match the following dag sequence:
6346       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6347       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6348     } else
6349       CanFold = false;
6350
6351     ExpectedVExtractIdx += 2;
6352   }
6353
6354   return CanFold;
6355 }
6356
6357 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6358 /// a concat_vector. 
6359 ///
6360 /// This is a helper function of PerformBUILD_VECTORCombine.
6361 /// This function expects two 256-bit vectors called V0 and V1.
6362 /// At first, each vector is split into two separate 128-bit vectors.
6363 /// Then, the resulting 128-bit vectors are used to implement two
6364 /// horizontal binary operations. 
6365 ///
6366 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6367 ///
6368 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6369 /// the two new horizontal binop.
6370 /// When Mode is set, the first horizontal binop dag node would take as input
6371 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6372 /// horizontal binop dag node would take as input the lower 128-bit of V1
6373 /// and the upper 128-bit of V1.
6374 ///   Example:
6375 ///     HADD V0_LO, V0_HI
6376 ///     HADD V1_LO, V1_HI
6377 ///
6378 /// Otherwise, the first horizontal binop dag node takes as input the lower
6379 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6380 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6381 ///   Example:
6382 ///     HADD V0_LO, V1_LO
6383 ///     HADD V0_HI, V1_HI
6384 ///
6385 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6386 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6387 /// the upper 128-bits of the result.
6388 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6389                                      SDLoc DL, SelectionDAG &DAG,
6390                                      unsigned X86Opcode, bool Mode,
6391                                      bool isUndefLO, bool isUndefHI) {
6392   EVT VT = V0.getValueType();
6393   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6394          "Invalid nodes in input!");
6395
6396   unsigned NumElts = VT.getVectorNumElements();
6397   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6398   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6399   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6400   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6401   EVT NewVT = V0_LO.getValueType();
6402
6403   SDValue LO = DAG.getUNDEF(NewVT);
6404   SDValue HI = DAG.getUNDEF(NewVT);
6405
6406   if (Mode) {
6407     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6408     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6409       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6410     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6411       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6412   } else {
6413     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6414     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6415                        V1_LO->getOpcode() != ISD::UNDEF))
6416       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6417
6418     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6419                        V1_HI->getOpcode() != ISD::UNDEF))
6420       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6421   }
6422
6423   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6424 }
6425
6426 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6427 /// sequence of 'vadd + vsub + blendi'.
6428 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6429                            const X86Subtarget *Subtarget) {
6430   SDLoc DL(BV);
6431   EVT VT = BV->getValueType(0);
6432   unsigned NumElts = VT.getVectorNumElements();
6433   SDValue InVec0 = DAG.getUNDEF(VT);
6434   SDValue InVec1 = DAG.getUNDEF(VT);
6435
6436   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6437           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6438
6439   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6441   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6442     return SDValue();
6443
6444   // Odd-numbered elements in the input build vector are obtained from
6445   // adding two integer/float elements.
6446   // Even-numbered elements in the input build vector are obtained from
6447   // subtracting two integer/float elements.
6448   unsigned ExpectedOpcode = ISD::FSUB;
6449   unsigned NextExpectedOpcode = ISD::FADD;
6450   bool AddFound = false;
6451   bool SubFound = false;
6452
6453   for (unsigned i = 0, e = NumElts; i != e; i++) {
6454     SDValue Op = BV->getOperand(i);
6455       
6456     // Skip 'undef' values.
6457     unsigned Opcode = Op.getOpcode();
6458     if (Opcode == ISD::UNDEF) {
6459       std::swap(ExpectedOpcode, NextExpectedOpcode);
6460       continue;
6461     }
6462       
6463     // Early exit if we found an unexpected opcode.
6464     if (Opcode != ExpectedOpcode)
6465       return SDValue();
6466
6467     SDValue Op0 = Op.getOperand(0);
6468     SDValue Op1 = Op.getOperand(1);
6469
6470     // Try to match the following pattern:
6471     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6472     // Early exit if we cannot match that sequence.
6473     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6474         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6475         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6476         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6477         Op0.getOperand(1) != Op1.getOperand(1))
6478       return SDValue();
6479
6480     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6481     if (I0 != i)
6482       return SDValue();
6483
6484     // We found a valid add/sub node. Update the information accordingly.
6485     if (i & 1)
6486       AddFound = true;
6487     else
6488       SubFound = true;
6489
6490     // Update InVec0 and InVec1.
6491     if (InVec0.getOpcode() == ISD::UNDEF)
6492       InVec0 = Op0.getOperand(0);
6493     if (InVec1.getOpcode() == ISD::UNDEF)
6494       InVec1 = Op1.getOperand(0);
6495
6496     // Make sure that operands in input to each add/sub node always
6497     // come from a same pair of vectors.
6498     if (InVec0 != Op0.getOperand(0)) {
6499       if (ExpectedOpcode == ISD::FSUB)
6500         return SDValue();
6501
6502       // FADD is commutable. Try to commute the operands
6503       // and then test again.
6504       std::swap(Op0, Op1);
6505       if (InVec0 != Op0.getOperand(0))
6506         return SDValue();
6507     }
6508
6509     if (InVec1 != Op1.getOperand(0))
6510       return SDValue();
6511
6512     // Update the pair of expected opcodes.
6513     std::swap(ExpectedOpcode, NextExpectedOpcode);
6514   }
6515
6516   // Don't try to fold this build_vector into a VSELECT if it has
6517   // too many UNDEF operands.
6518   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6519       InVec1.getOpcode() != ISD::UNDEF) {
6520     // Emit a sequence of vector add and sub followed by a VSELECT.
6521     // The new VSELECT will be lowered into a BLENDI.
6522     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6523     // and emit a single ADDSUB instruction.
6524     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6525     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6526
6527     // Construct the VSELECT mask.
6528     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6529     EVT SVT = MaskVT.getVectorElementType();
6530     unsigned SVTBits = SVT.getSizeInBits();
6531     SmallVector<SDValue, 8> Ops;
6532
6533     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6534       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6535                             APInt::getAllOnesValue(SVTBits);
6536       SDValue Constant = DAG.getConstant(Value, SVT);
6537       Ops.push_back(Constant);
6538     }
6539
6540     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6541     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6542   }
6543   
6544   return SDValue();
6545 }
6546
6547 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6548                                           const X86Subtarget *Subtarget) {
6549   SDLoc DL(N);
6550   EVT VT = N->getValueType(0);
6551   unsigned NumElts = VT.getVectorNumElements();
6552   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6553   SDValue InVec0, InVec1;
6554
6555   // Try to match an ADDSUB.
6556   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6557       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6558     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6559     if (Value.getNode())
6560       return Value;
6561   }
6562
6563   // Try to match horizontal ADD/SUB.
6564   unsigned NumUndefsLO = 0;
6565   unsigned NumUndefsHI = 0;
6566   unsigned Half = NumElts/2;
6567
6568   // Count the number of UNDEF operands in the build_vector in input.
6569   for (unsigned i = 0, e = Half; i != e; ++i)
6570     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6571       NumUndefsLO++;
6572
6573   for (unsigned i = Half, e = NumElts; i != e; ++i)
6574     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6575       NumUndefsHI++;
6576
6577   // Early exit if this is either a build_vector of all UNDEFs or all the
6578   // operands but one are UNDEF.
6579   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6580     return SDValue();
6581
6582   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6583     // Try to match an SSE3 float HADD/HSUB.
6584     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6585       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6586     
6587     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6588       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6589   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6590     // Try to match an SSSE3 integer HADD/HSUB.
6591     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6592       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6593     
6594     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6595       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6596   }
6597   
6598   if (!Subtarget->hasAVX())
6599     return SDValue();
6600
6601   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6602     // Try to match an AVX horizontal add/sub of packed single/double
6603     // precision floating point values from 256-bit vectors.
6604     SDValue InVec2, InVec3;
6605     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6606         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6607         ((InVec0.getOpcode() == ISD::UNDEF ||
6608           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6609         ((InVec1.getOpcode() == ISD::UNDEF ||
6610           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6611       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6612
6613     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6614         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6615         ((InVec0.getOpcode() == ISD::UNDEF ||
6616           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6617         ((InVec1.getOpcode() == ISD::UNDEF ||
6618           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6619       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6620   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6621     // Try to match an AVX2 horizontal add/sub of signed integers.
6622     SDValue InVec2, InVec3;
6623     unsigned X86Opcode;
6624     bool CanFold = true;
6625
6626     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6627         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6628         ((InVec0.getOpcode() == ISD::UNDEF ||
6629           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6630         ((InVec1.getOpcode() == ISD::UNDEF ||
6631           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6632       X86Opcode = X86ISD::HADD;
6633     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6634         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6635         ((InVec0.getOpcode() == ISD::UNDEF ||
6636           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6637         ((InVec1.getOpcode() == ISD::UNDEF ||
6638           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6639       X86Opcode = X86ISD::HSUB;
6640     else
6641       CanFold = false;
6642
6643     if (CanFold) {
6644       // Fold this build_vector into a single horizontal add/sub.
6645       // Do this only if the target has AVX2.
6646       if (Subtarget->hasAVX2())
6647         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6648  
6649       // Do not try to expand this build_vector into a pair of horizontal
6650       // add/sub if we can emit a pair of scalar add/sub.
6651       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6652         return SDValue();
6653
6654       // Convert this build_vector into a pair of horizontal binop followed by
6655       // a concat vector.
6656       bool isUndefLO = NumUndefsLO == Half;
6657       bool isUndefHI = NumUndefsHI == Half;
6658       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6659                                    isUndefLO, isUndefHI);
6660     }
6661   }
6662
6663   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6664        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6665     unsigned X86Opcode;
6666     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6667       X86Opcode = X86ISD::HADD;
6668     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6669       X86Opcode = X86ISD::HSUB;
6670     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6671       X86Opcode = X86ISD::FHADD;
6672     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6673       X86Opcode = X86ISD::FHSUB;
6674     else
6675       return SDValue();
6676
6677     // Don't try to expand this build_vector into a pair of horizontal add/sub
6678     // if we can simply emit a pair of scalar add/sub.
6679     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6680       return SDValue();
6681
6682     // Convert this build_vector into two horizontal add/sub followed by
6683     // a concat vector.
6684     bool isUndefLO = NumUndefsLO == Half;
6685     bool isUndefHI = NumUndefsHI == Half;
6686     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6687                                  isUndefLO, isUndefHI);
6688   }
6689
6690   return SDValue();
6691 }
6692
6693 SDValue
6694 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6695   SDLoc dl(Op);
6696
6697   MVT VT = Op.getSimpleValueType();
6698   MVT ExtVT = VT.getVectorElementType();
6699   unsigned NumElems = Op.getNumOperands();
6700
6701   // Generate vectors for predicate vectors.
6702   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6703     return LowerBUILD_VECTORvXi1(Op, DAG);
6704
6705   // Vectors containing all zeros can be matched by pxor and xorps later
6706   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6707     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6708     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6709     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6710       return Op;
6711
6712     return getZeroVector(VT, Subtarget, DAG, dl);
6713   }
6714
6715   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6716   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6717   // vpcmpeqd on 256-bit vectors.
6718   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6719     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6720       return Op;
6721
6722     if (!VT.is512BitVector())
6723       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6724   }
6725
6726   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6727   if (Broadcast.getNode())
6728     return Broadcast;
6729
6730   unsigned EVTBits = ExtVT.getSizeInBits();
6731
6732   unsigned NumZero  = 0;
6733   unsigned NumNonZero = 0;
6734   unsigned NonZeros = 0;
6735   bool IsAllConstants = true;
6736   SmallSet<SDValue, 8> Values;
6737   for (unsigned i = 0; i < NumElems; ++i) {
6738     SDValue Elt = Op.getOperand(i);
6739     if (Elt.getOpcode() == ISD::UNDEF)
6740       continue;
6741     Values.insert(Elt);
6742     if (Elt.getOpcode() != ISD::Constant &&
6743         Elt.getOpcode() != ISD::ConstantFP)
6744       IsAllConstants = false;
6745     if (X86::isZeroNode(Elt))
6746       NumZero++;
6747     else {
6748       NonZeros |= (1 << i);
6749       NumNonZero++;
6750     }
6751   }
6752
6753   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6754   if (NumNonZero == 0)
6755     return DAG.getUNDEF(VT);
6756
6757   // Special case for single non-zero, non-undef, element.
6758   if (NumNonZero == 1) {
6759     unsigned Idx = countTrailingZeros(NonZeros);
6760     SDValue Item = Op.getOperand(Idx);
6761
6762     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6763     // the value are obviously zero, truncate the value to i32 and do the
6764     // insertion that way.  Only do this if the value is non-constant or if the
6765     // value is a constant being inserted into element 0.  It is cheaper to do
6766     // a constant pool load than it is to do a movd + shuffle.
6767     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6768         (!IsAllConstants || Idx == 0)) {
6769       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6770         // Handle SSE only.
6771         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6772         EVT VecVT = MVT::v4i32;
6773         unsigned VecElts = 4;
6774
6775         // Truncate the value (which may itself be a constant) to i32, and
6776         // convert it to a vector with movd (S2V+shuffle to zero extend).
6777         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6778         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6779         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6780
6781         // Now we have our 32-bit value zero extended in the low element of
6782         // a vector.  If Idx != 0, swizzle it into place.
6783         if (Idx != 0) {
6784           SmallVector<int, 4> Mask;
6785           Mask.push_back(Idx);
6786           for (unsigned i = 1; i != VecElts; ++i)
6787             Mask.push_back(i);
6788           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6789                                       &Mask[0]);
6790         }
6791         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6792       }
6793     }
6794
6795     // If we have a constant or non-constant insertion into the low element of
6796     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6797     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6798     // depending on what the source datatype is.
6799     if (Idx == 0) {
6800       if (NumZero == 0)
6801         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6802
6803       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6804           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6805         if (VT.is256BitVector() || VT.is512BitVector()) {
6806           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6807           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6808                              Item, DAG.getIntPtrConstant(0));
6809         }
6810         assert(VT.is128BitVector() && "Expected an SSE value type!");
6811         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6812         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6813         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6814       }
6815
6816       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6817         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6818         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6819         if (VT.is256BitVector()) {
6820           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6821           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6822         } else {
6823           assert(VT.is128BitVector() && "Expected an SSE value type!");
6824           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6825         }
6826         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6827       }
6828     }
6829
6830     // Is it a vector logical left shift?
6831     if (NumElems == 2 && Idx == 1 &&
6832         X86::isZeroNode(Op.getOperand(0)) &&
6833         !X86::isZeroNode(Op.getOperand(1))) {
6834       unsigned NumBits = VT.getSizeInBits();
6835       return getVShift(true, VT,
6836                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6837                                    VT, Op.getOperand(1)),
6838                        NumBits/2, DAG, *this, dl);
6839     }
6840
6841     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6842       return SDValue();
6843
6844     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6845     // is a non-constant being inserted into an element other than the low one,
6846     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6847     // movd/movss) to move this into the low element, then shuffle it into
6848     // place.
6849     if (EVTBits == 32) {
6850       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6851
6852       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6853       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6854       SmallVector<int, 8> MaskVec;
6855       for (unsigned i = 0; i != NumElems; ++i)
6856         MaskVec.push_back(i == Idx ? 0 : 1);
6857       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6858     }
6859   }
6860
6861   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6862   if (Values.size() == 1) {
6863     if (EVTBits == 32) {
6864       // Instead of a shuffle like this:
6865       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6866       // Check if it's possible to issue this instead.
6867       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6868       unsigned Idx = countTrailingZeros(NonZeros);
6869       SDValue Item = Op.getOperand(Idx);
6870       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6871         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6872     }
6873     return SDValue();
6874   }
6875
6876   // A vector full of immediates; various special cases are already
6877   // handled, so this is best done with a single constant-pool load.
6878   if (IsAllConstants)
6879     return SDValue();
6880
6881   // For AVX-length vectors, build the individual 128-bit pieces and use
6882   // shuffles to put them in place.
6883   if (VT.is256BitVector() || VT.is512BitVector()) {
6884     SmallVector<SDValue, 64> V;
6885     for (unsigned i = 0; i != NumElems; ++i)
6886       V.push_back(Op.getOperand(i));
6887
6888     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6889
6890     // Build both the lower and upper subvector.
6891     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6892                                 makeArrayRef(&V[0], NumElems/2));
6893     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6894                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6895
6896     // Recreate the wider vector with the lower and upper part.
6897     if (VT.is256BitVector())
6898       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6899     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6900   }
6901
6902   // Let legalizer expand 2-wide build_vectors.
6903   if (EVTBits == 64) {
6904     if (NumNonZero == 1) {
6905       // One half is zero or undef.
6906       unsigned Idx = countTrailingZeros(NonZeros);
6907       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6908                                  Op.getOperand(Idx));
6909       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6910     }
6911     return SDValue();
6912   }
6913
6914   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6915   if (EVTBits == 8 && NumElems == 16) {
6916     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6917                                         Subtarget, *this);
6918     if (V.getNode()) return V;
6919   }
6920
6921   if (EVTBits == 16 && NumElems == 8) {
6922     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6923                                       Subtarget, *this);
6924     if (V.getNode()) return V;
6925   }
6926
6927   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6928   if (EVTBits == 32 && NumElems == 4) {
6929     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6930                                       NumZero, DAG, Subtarget, *this);
6931     if (V.getNode())
6932       return V;
6933   }
6934
6935   // If element VT is == 32 bits, turn it into a number of shuffles.
6936   SmallVector<SDValue, 8> V(NumElems);
6937   if (NumElems == 4 && NumZero > 0) {
6938     for (unsigned i = 0; i < 4; ++i) {
6939       bool isZero = !(NonZeros & (1 << i));
6940       if (isZero)
6941         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6942       else
6943         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6944     }
6945
6946     for (unsigned i = 0; i < 2; ++i) {
6947       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6948         default: break;
6949         case 0:
6950           V[i] = V[i*2];  // Must be a zero vector.
6951           break;
6952         case 1:
6953           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6954           break;
6955         case 2:
6956           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6957           break;
6958         case 3:
6959           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6960           break;
6961       }
6962     }
6963
6964     bool Reverse1 = (NonZeros & 0x3) == 2;
6965     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6966     int MaskVec[] = {
6967       Reverse1 ? 1 : 0,
6968       Reverse1 ? 0 : 1,
6969       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6970       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6971     };
6972     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6973   }
6974
6975   if (Values.size() > 1 && VT.is128BitVector()) {
6976     // Check for a build vector of consecutive loads.
6977     for (unsigned i = 0; i < NumElems; ++i)
6978       V[i] = Op.getOperand(i);
6979
6980     // Check for elements which are consecutive loads.
6981     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6982     if (LD.getNode())
6983       return LD;
6984
6985     // Check for a build vector from mostly shuffle plus few inserting.
6986     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6987     if (Sh.getNode())
6988       return Sh;
6989
6990     // For SSE 4.1, use insertps to put the high elements into the low element.
6991     if (getSubtarget()->hasSSE41()) {
6992       SDValue Result;
6993       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6994         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6995       else
6996         Result = DAG.getUNDEF(VT);
6997
6998       for (unsigned i = 1; i < NumElems; ++i) {
6999         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7000         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7001                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7002       }
7003       return Result;
7004     }
7005
7006     // Otherwise, expand into a number of unpckl*, start by extending each of
7007     // our (non-undef) elements to the full vector width with the element in the
7008     // bottom slot of the vector (which generates no code for SSE).
7009     for (unsigned i = 0; i < NumElems; ++i) {
7010       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7011         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7012       else
7013         V[i] = DAG.getUNDEF(VT);
7014     }
7015
7016     // Next, we iteratively mix elements, e.g. for v4f32:
7017     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7018     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7019     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7020     unsigned EltStride = NumElems >> 1;
7021     while (EltStride != 0) {
7022       for (unsigned i = 0; i < EltStride; ++i) {
7023         // If V[i+EltStride] is undef and this is the first round of mixing,
7024         // then it is safe to just drop this shuffle: V[i] is already in the
7025         // right place, the one element (since it's the first round) being
7026         // inserted as undef can be dropped.  This isn't safe for successive
7027         // rounds because they will permute elements within both vectors.
7028         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7029             EltStride == NumElems/2)
7030           continue;
7031
7032         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7033       }
7034       EltStride >>= 1;
7035     }
7036     return V[0];
7037   }
7038   return SDValue();
7039 }
7040
7041 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7042 // to create 256-bit vectors from two other 128-bit ones.
7043 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7044   SDLoc dl(Op);
7045   MVT ResVT = Op.getSimpleValueType();
7046
7047   assert((ResVT.is256BitVector() ||
7048           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7049
7050   SDValue V1 = Op.getOperand(0);
7051   SDValue V2 = Op.getOperand(1);
7052   unsigned NumElems = ResVT.getVectorNumElements();
7053   if(ResVT.is256BitVector())
7054     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7055
7056   if (Op.getNumOperands() == 4) {
7057     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7058                                 ResVT.getVectorNumElements()/2);
7059     SDValue V3 = Op.getOperand(2);
7060     SDValue V4 = Op.getOperand(3);
7061     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7062       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7063   }
7064   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7065 }
7066
7067 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7068   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7069   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7070          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7071           Op.getNumOperands() == 4)));
7072
7073   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7074   // from two other 128-bit ones.
7075
7076   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7077   return LowerAVXCONCAT_VECTORS(Op, DAG);
7078 }
7079
7080
7081 //===----------------------------------------------------------------------===//
7082 // Vector shuffle lowering
7083 //
7084 // This is an experimental code path for lowering vector shuffles on x86. It is
7085 // designed to handle arbitrary vector shuffles and blends, gracefully
7086 // degrading performance as necessary. It works hard to recognize idiomatic
7087 // shuffles and lower them to optimal instruction patterns without leaving
7088 // a framework that allows reasonably efficient handling of all vector shuffle
7089 // patterns.
7090 //===----------------------------------------------------------------------===//
7091
7092 /// \brief Tiny helper function to identify a no-op mask.
7093 ///
7094 /// This is a somewhat boring predicate function. It checks whether the mask
7095 /// array input, which is assumed to be a single-input shuffle mask of the kind
7096 /// used by the X86 shuffle instructions (not a fully general
7097 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7098 /// in-place shuffle are 'no-op's.
7099 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7100   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7101     if (Mask[i] != -1 && Mask[i] != i)
7102       return false;
7103   return true;
7104 }
7105
7106 /// \brief Helper function to classify a mask as a single-input mask.
7107 ///
7108 /// This isn't a generic single-input test because in the vector shuffle
7109 /// lowering we canonicalize single inputs to be the first input operand. This
7110 /// means we can more quickly test for a single input by only checking whether
7111 /// an input from the second operand exists. We also assume that the size of
7112 /// mask corresponds to the size of the input vectors which isn't true in the
7113 /// fully general case.
7114 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7115   for (int M : Mask)
7116     if (M >= (int)Mask.size())
7117       return false;
7118   return true;
7119 }
7120
7121 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7122 // 2013 will allow us to use it as a non-type template parameter.
7123 namespace {
7124
7125 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7126 ///
7127 /// See its documentation for details.
7128 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7129   if (Mask.size() != Args.size())
7130     return false;
7131   for (int i = 0, e = Mask.size(); i < e; ++i) {
7132     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7133     assert(*Args[i] < (int)Args.size() * 2 &&
7134            "Argument outside the range of possible shuffle inputs!");
7135     if (Mask[i] != -1 && Mask[i] != *Args[i])
7136       return false;
7137   }
7138   return true;
7139 }
7140
7141 } // namespace
7142
7143 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7144 /// arguments.
7145 ///
7146 /// This is a fast way to test a shuffle mask against a fixed pattern:
7147 ///
7148 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7149 ///
7150 /// It returns true if the mask is exactly as wide as the argument list, and
7151 /// each element of the mask is either -1 (signifying undef) or the value given
7152 /// in the argument.
7153 static const VariadicFunction1<
7154     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7155
7156 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7157 ///
7158 /// This helper function produces an 8-bit shuffle immediate corresponding to
7159 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7160 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7161 /// example.
7162 ///
7163 /// NB: We rely heavily on "undef" masks preserving the input lane.
7164 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7165                                           SelectionDAG &DAG) {
7166   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7167   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7168   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7169   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7170   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7171
7172   unsigned Imm = 0;
7173   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7174   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7175   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7176   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7177   return DAG.getConstant(Imm, MVT::i8);
7178 }
7179
7180 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7181 ///
7182 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7183 /// support for floating point shuffles but not integer shuffles. These
7184 /// instructions will incur a domain crossing penalty on some chips though so
7185 /// it is better to avoid lowering through this for integer vectors where
7186 /// possible.
7187 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7188                                        const X86Subtarget *Subtarget,
7189                                        SelectionDAG &DAG) {
7190   SDLoc DL(Op);
7191   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7192   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7193   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7194   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7195   ArrayRef<int> Mask = SVOp->getMask();
7196   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7197
7198   if (isSingleInputShuffleMask(Mask)) {
7199     // Straight shuffle of a single input vector. Simulate this by using the
7200     // single input as both of the "inputs" to this instruction..
7201     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7202     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7203                        DAG.getConstant(SHUFPDMask, MVT::i8));
7204   }
7205   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7206   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7207
7208   // Use dedicated unpack instructions for masks that match their pattern.
7209   if (isShuffleEquivalent(Mask, 0, 2))
7210     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7211   if (isShuffleEquivalent(Mask, 1, 3))
7212     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7213
7214   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7215   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7216                      DAG.getConstant(SHUFPDMask, MVT::i8));
7217 }
7218
7219 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7220 ///
7221 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7222 /// the integer unit to minimize domain crossing penalties. However, for blends
7223 /// it falls back to the floating point shuffle operation with appropriate bit
7224 /// casting.
7225 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7226                                        const X86Subtarget *Subtarget,
7227                                        SelectionDAG &DAG) {
7228   SDLoc DL(Op);
7229   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7230   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7231   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7232   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7233   ArrayRef<int> Mask = SVOp->getMask();
7234   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7235
7236   if (isSingleInputShuffleMask(Mask)) {
7237     // Straight shuffle of a single input vector. For everything from SSE2
7238     // onward this has a single fast instruction with no scary immediates.
7239     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7240     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7241     int WidenedMask[4] = {
7242         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7243         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7244     return DAG.getNode(
7245         ISD::BITCAST, DL, MVT::v2i64,
7246         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7247                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7248   }
7249
7250   // Use dedicated unpack instructions for masks that match their pattern.
7251   if (isShuffleEquivalent(Mask, 0, 2))
7252     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7253   if (isShuffleEquivalent(Mask, 1, 3))
7254     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7255
7256   // We implement this with SHUFPD which is pretty lame because it will likely
7257   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7258   // However, all the alternatives are still more cycles and newer chips don't
7259   // have this problem. It would be really nice if x86 had better shuffles here.
7260   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7261   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7262   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7263                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7264 }
7265
7266 /// \brief Lower 4-lane 32-bit floating point shuffles.
7267 ///
7268 /// Uses instructions exclusively from the floating point unit to minimize
7269 /// domain crossing penalties, as these are sufficient to implement all v4f32
7270 /// shuffles.
7271 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7272                                        const X86Subtarget *Subtarget,
7273                                        SelectionDAG &DAG) {
7274   SDLoc DL(Op);
7275   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7276   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7277   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7278   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7279   ArrayRef<int> Mask = SVOp->getMask();
7280   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7281
7282   SDValue LowV = V1, HighV = V2;
7283   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7284
7285   int NumV2Elements =
7286       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7287
7288   if (NumV2Elements == 0)
7289     // Straight shuffle of a single input vector. We pass the input vector to
7290     // both operands to simulate this with a SHUFPS.
7291     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7292                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7293
7294   // Use dedicated unpack instructions for masks that match their pattern.
7295   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7296     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7297   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7298     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7299
7300   if (NumV2Elements == 1) {
7301     int V2Index =
7302         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7303         Mask.begin();
7304     // Compute the index adjacent to V2Index and in the same half by toggling
7305     // the low bit.
7306     int V2AdjIndex = V2Index ^ 1;
7307
7308     if (Mask[V2AdjIndex] == -1) {
7309       // Handles all the cases where we have a single V2 element and an undef.
7310       // This will only ever happen in the high lanes because we commute the
7311       // vector otherwise.
7312       if (V2Index < 2)
7313         std::swap(LowV, HighV);
7314       NewMask[V2Index] -= 4;
7315     } else {
7316       // Handle the case where the V2 element ends up adjacent to a V1 element.
7317       // To make this work, blend them together as the first step.
7318       int V1Index = V2AdjIndex;
7319       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7320       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7321                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7322
7323       // Now proceed to reconstruct the final blend as we have the necessary
7324       // high or low half formed.
7325       if (V2Index < 2) {
7326         LowV = V2;
7327         HighV = V1;
7328       } else {
7329         HighV = V2;
7330       }
7331       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7332       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7333     }
7334   } else if (NumV2Elements == 2) {
7335     if (Mask[0] < 4 && Mask[1] < 4) {
7336       // Handle the easy case where we have V1 in the low lanes and V2 in the
7337       // high lanes. We never see this reversed because we sort the shuffle.
7338       NewMask[2] -= 4;
7339       NewMask[3] -= 4;
7340     } else {
7341       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7342       // trying to place elements directly, just blend them and set up the final
7343       // shuffle to place them.
7344
7345       // The first two blend mask elements are for V1, the second two are for
7346       // V2.
7347       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7348                           Mask[2] < 4 ? Mask[2] : Mask[3],
7349                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7350                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7351       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7352                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7353
7354       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7355       // a blend.
7356       LowV = HighV = V1;
7357       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7358       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7359       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7360       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7361     }
7362   }
7363   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7364                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7365 }
7366
7367 /// \brief Lower 4-lane i32 vector shuffles.
7368 ///
7369 /// We try to handle these with integer-domain shuffles where we can, but for
7370 /// blends we use the floating point domain blend instructions.
7371 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7372                                        const X86Subtarget *Subtarget,
7373                                        SelectionDAG &DAG) {
7374   SDLoc DL(Op);
7375   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7376   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7377   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7378   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7379   ArrayRef<int> Mask = SVOp->getMask();
7380   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7381
7382   if (isSingleInputShuffleMask(Mask))
7383     // Straight shuffle of a single input vector. For everything from SSE2
7384     // onward this has a single fast instruction with no scary immediates.
7385     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7386                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7387
7388   // Use dedicated unpack instructions for masks that match their pattern.
7389   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7390     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7391   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7392     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7393
7394   // We implement this with SHUFPS because it can blend from two vectors.
7395   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7396   // up the inputs, bypassing domain shift penalties that we would encur if we
7397   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7398   // relevant.
7399   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7400                      DAG.getVectorShuffle(
7401                          MVT::v4f32, DL,
7402                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7403                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7404 }
7405
7406 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7407 /// shuffle lowering, and the most complex part.
7408 ///
7409 /// The lowering strategy is to try to form pairs of input lanes which are
7410 /// targeted at the same half of the final vector, and then use a dword shuffle
7411 /// to place them onto the right half, and finally unpack the paired lanes into
7412 /// their final position.
7413 ///
7414 /// The exact breakdown of how to form these dword pairs and align them on the
7415 /// correct sides is really tricky. See the comments within the function for
7416 /// more of the details.
7417 static SDValue lowerV8I16SingleInputVectorShuffle(
7418     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7419     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7420   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7421   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7422   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7423
7424   SmallVector<int, 4> LoInputs;
7425   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7426                [](int M) { return M >= 0; });
7427   std::sort(LoInputs.begin(), LoInputs.end());
7428   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7429   SmallVector<int, 4> HiInputs;
7430   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7431                [](int M) { return M >= 0; });
7432   std::sort(HiInputs.begin(), HiInputs.end());
7433   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7434   int NumLToL =
7435       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7436   int NumHToL = LoInputs.size() - NumLToL;
7437   int NumLToH =
7438       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7439   int NumHToH = HiInputs.size() - NumLToH;
7440   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7441   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7442   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7443   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7444
7445   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7446   // such inputs we can swap two of the dwords across the half mark and end up
7447   // with <=2 inputs to each half in each half. Once there, we can fall through
7448   // to the generic code below. For example:
7449   //
7450   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7451   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7452   //
7453   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7454   // and an existing 2-into-2 on the other half. In this case we may have to
7455   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7456   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7457   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7458   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7459   // half than the one we target for fixing) will be fixed when we re-enter this
7460   // path. We will also combine away any sequence of PSHUFD instructions that
7461   // result into a single instruction. Here is an example of the tricky case:
7462   //
7463   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7464   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7465   //
7466   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7467   //
7468   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7469   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7470   //
7471   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7472   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7473   //
7474   // The result is fine to be handled by the generic logic.
7475   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7476                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7477                           int AOffset, int BOffset) {
7478     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7479            "Must call this with A having 3 or 1 inputs from the A half.");
7480     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7481            "Must call this with B having 1 or 3 inputs from the B half.");
7482     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7483            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7484
7485     // Compute the index of dword with only one word among the three inputs in
7486     // a half by taking the sum of the half with three inputs and subtracting
7487     // the sum of the actual three inputs. The difference is the remaining
7488     // slot.
7489     int ADWord, BDWord;
7490     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7491     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7492     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7493     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7494     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7495     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7496     int TripleNonInputIdx =
7497         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7498     TripleDWord = TripleNonInputIdx / 2;
7499
7500     // We use xor with one to compute the adjacent DWord to whichever one the
7501     // OneInput is in.
7502     OneInputDWord = (OneInput / 2) ^ 1;
7503
7504     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7505     // and BToA inputs. If there is also such a problem with the BToB and AToB
7506     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7507     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7508     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7509     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7510       // Compute how many inputs will be flipped by swapping these DWords. We
7511       // need
7512       // to balance this to ensure we don't form a 3-1 shuffle in the other
7513       // half.
7514       int NumFlippedAToBInputs =
7515           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7516           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7517       int NumFlippedBToBInputs =
7518           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7519           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7520       if ((NumFlippedAToBInputs == 1 &&
7521            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7522           (NumFlippedBToBInputs == 1 &&
7523            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7524         // We choose whether to fix the A half or B half based on whether that
7525         // half has zero flipped inputs. At zero, we may not be able to fix it
7526         // with that half. We also bias towards fixing the B half because that
7527         // will more commonly be the high half, and we have to bias one way.
7528         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7529                                                        ArrayRef<int> Inputs) {
7530           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7531           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7532                                          PinnedIdx ^ 1) != Inputs.end();
7533           // Determine whether the free index is in the flipped dword or the
7534           // unflipped dword based on where the pinned index is. We use this bit
7535           // in an xor to conditionally select the adjacent dword.
7536           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7537           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7538                                              FixFreeIdx) != Inputs.end();
7539           if (IsFixIdxInput == IsFixFreeIdxInput)
7540             FixFreeIdx += 1;
7541           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7542                                         FixFreeIdx) != Inputs.end();
7543           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7544                  "We need to be changing the number of flipped inputs!");
7545           int PSHUFHalfMask[] = {0, 1, 2, 3};
7546           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7547           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7548                           MVT::v8i16, V,
7549                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7550
7551           for (int &M : Mask)
7552             if (M != -1 && M == FixIdx)
7553               M = FixFreeIdx;
7554             else if (M != -1 && M == FixFreeIdx)
7555               M = FixIdx;
7556         };
7557         if (NumFlippedBToBInputs != 0) {
7558           int BPinnedIdx =
7559               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7560           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7561         } else {
7562           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7563           int APinnedIdx =
7564               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7565           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7566         }
7567       }
7568     }
7569
7570     int PSHUFDMask[] = {0, 1, 2, 3};
7571     PSHUFDMask[ADWord] = BDWord;
7572     PSHUFDMask[BDWord] = ADWord;
7573     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7574                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7575                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7576                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7577
7578     // Adjust the mask to match the new locations of A and B.
7579     for (int &M : Mask)
7580       if (M != -1 && M/2 == ADWord)
7581         M = 2 * BDWord + M % 2;
7582       else if (M != -1 && M/2 == BDWord)
7583         M = 2 * ADWord + M % 2;
7584
7585     // Recurse back into this routine to re-compute state now that this isn't
7586     // a 3 and 1 problem.
7587     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7588                                 Mask);
7589   };
7590   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7591     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7592   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7593     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7594
7595   // At this point there are at most two inputs to the low and high halves from
7596   // each half. That means the inputs can always be grouped into dwords and
7597   // those dwords can then be moved to the correct half with a dword shuffle.
7598   // We use at most one low and one high word shuffle to collect these paired
7599   // inputs into dwords, and finally a dword shuffle to place them.
7600   int PSHUFLMask[4] = {-1, -1, -1, -1};
7601   int PSHUFHMask[4] = {-1, -1, -1, -1};
7602   int PSHUFDMask[4] = {-1, -1, -1, -1};
7603
7604   // First fix the masks for all the inputs that are staying in their
7605   // original halves. This will then dictate the targets of the cross-half
7606   // shuffles.
7607   auto fixInPlaceInputs =
7608       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7609                     MutableArrayRef<int> SourceHalfMask,
7610                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7611     if (InPlaceInputs.empty())
7612       return;
7613     if (InPlaceInputs.size() == 1) {
7614       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7615           InPlaceInputs[0] - HalfOffset;
7616       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7617       return;
7618     }
7619     if (IncomingInputs.empty()) {
7620       // Just fix all of the in place inputs.
7621       for (int Input : InPlaceInputs) {
7622         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7623         PSHUFDMask[Input / 2] = Input / 2;
7624       }
7625       return;
7626     }
7627
7628     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7629     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7630         InPlaceInputs[0] - HalfOffset;
7631     // Put the second input next to the first so that they are packed into
7632     // a dword. We find the adjacent index by toggling the low bit.
7633     int AdjIndex = InPlaceInputs[0] ^ 1;
7634     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7635     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7636     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7637   };
7638   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7639   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7640
7641   // Now gather the cross-half inputs and place them into a free dword of
7642   // their target half.
7643   // FIXME: This operation could almost certainly be simplified dramatically to
7644   // look more like the 3-1 fixing operation.
7645   auto moveInputsToRightHalf = [&PSHUFDMask](
7646       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7647       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7648       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7649       int DestOffset) {
7650     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7651       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7652     };
7653     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7654                                                int Word) {
7655       int LowWord = Word & ~1;
7656       int HighWord = Word | 1;
7657       return isWordClobbered(SourceHalfMask, LowWord) ||
7658              isWordClobbered(SourceHalfMask, HighWord);
7659     };
7660
7661     if (IncomingInputs.empty())
7662       return;
7663
7664     if (ExistingInputs.empty()) {
7665       // Map any dwords with inputs from them into the right half.
7666       for (int Input : IncomingInputs) {
7667         // If the source half mask maps over the inputs, turn those into
7668         // swaps and use the swapped lane.
7669         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7670           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7671             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7672                 Input - SourceOffset;
7673             // We have to swap the uses in our half mask in one sweep.
7674             for (int &M : HalfMask)
7675               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7676                 M = Input;
7677               else if (M == Input)
7678                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7679           } else {
7680             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7681                        Input - SourceOffset &&
7682                    "Previous placement doesn't match!");
7683           }
7684           // Note that this correctly re-maps both when we do a swap and when
7685           // we observe the other side of the swap above. We rely on that to
7686           // avoid swapping the members of the input list directly.
7687           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7688         }
7689
7690         // Map the input's dword into the correct half.
7691         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7692           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7693         else
7694           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7695                      Input / 2 &&
7696                  "Previous placement doesn't match!");
7697       }
7698
7699       // And just directly shift any other-half mask elements to be same-half
7700       // as we will have mirrored the dword containing the element into the
7701       // same position within that half.
7702       for (int &M : HalfMask)
7703         if (M >= SourceOffset && M < SourceOffset + 4) {
7704           M = M - SourceOffset + DestOffset;
7705           assert(M >= 0 && "This should never wrap below zero!");
7706         }
7707       return;
7708     }
7709
7710     // Ensure we have the input in a viable dword of its current half. This
7711     // is particularly tricky because the original position may be clobbered
7712     // by inputs being moved and *staying* in that half.
7713     if (IncomingInputs.size() == 1) {
7714       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7715         int InputFixed = std::find(std::begin(SourceHalfMask),
7716                                    std::end(SourceHalfMask), -1) -
7717                          std::begin(SourceHalfMask) + SourceOffset;
7718         SourceHalfMask[InputFixed - SourceOffset] =
7719             IncomingInputs[0] - SourceOffset;
7720         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7721                      InputFixed);
7722         IncomingInputs[0] = InputFixed;
7723       }
7724     } else if (IncomingInputs.size() == 2) {
7725       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7726           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7727         // We have two non-adjacent or clobbered inputs we need to extract from
7728         // the source half. To do this, we need to map them into some adjacent
7729         // dword slot in the source mask.
7730         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7731                               IncomingInputs[1] - SourceOffset};
7732
7733         // If there is a free slot in the source half mask adjacent to one of
7734         // the inputs, place the other input in it. We use (Index XOR 1) to
7735         // compute an adjacent index.
7736         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7737             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7738           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7739           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7740           InputsFixed[1] = InputsFixed[0] ^ 1;
7741         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7742                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7743           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7744           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7745           InputsFixed[0] = InputsFixed[1] ^ 1;
7746         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7747                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7748           // The two inputs are in the same DWord but it is clobbered and the
7749           // adjacent DWord isn't used at all. Move both inputs to the free
7750           // slot.
7751           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7752           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7753           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7754           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7755         } else {
7756           // The only way we hit this point is if there is no clobbering
7757           // (because there are no off-half inputs to this half) and there is no
7758           // free slot adjacent to one of the inputs. In this case, we have to
7759           // swap an input with a non-input.
7760           for (int i = 0; i < 4; ++i)
7761             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7762                    "We can't handle any clobbers here!");
7763           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7764                  "Cannot have adjacent inputs here!");
7765
7766           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7767           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7768
7769           // We also have to update the final source mask in this case because
7770           // it may need to undo the above swap.
7771           for (int &M : FinalSourceHalfMask)
7772             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7773               M = InputsFixed[1] + SourceOffset;
7774             else if (M == InputsFixed[1] + SourceOffset)
7775               M = (InputsFixed[0] ^ 1) + SourceOffset;
7776
7777           InputsFixed[1] = InputsFixed[0] ^ 1;
7778         }
7779
7780         // Point everything at the fixed inputs.
7781         for (int &M : HalfMask)
7782           if (M == IncomingInputs[0])
7783             M = InputsFixed[0] + SourceOffset;
7784           else if (M == IncomingInputs[1])
7785             M = InputsFixed[1] + SourceOffset;
7786
7787         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7788         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7789       }
7790     } else {
7791       llvm_unreachable("Unhandled input size!");
7792     }
7793
7794     // Now hoist the DWord down to the right half.
7795     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7796     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7797     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7798     for (int &M : HalfMask)
7799       for (int Input : IncomingInputs)
7800         if (M == Input)
7801           M = FreeDWord * 2 + Input % 2;
7802   };
7803   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7804                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7805   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7806                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7807
7808   // Now enact all the shuffles we've computed to move the inputs into their
7809   // target half.
7810   if (!isNoopShuffleMask(PSHUFLMask))
7811     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7812                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7813   if (!isNoopShuffleMask(PSHUFHMask))
7814     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7815                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7816   if (!isNoopShuffleMask(PSHUFDMask))
7817     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7818                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7819                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7820                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7821
7822   // At this point, each half should contain all its inputs, and we can then
7823   // just shuffle them into their final position.
7824   assert(std::count_if(LoMask.begin(), LoMask.end(),
7825                        [](int M) { return M >= 4; }) == 0 &&
7826          "Failed to lift all the high half inputs to the low mask!");
7827   assert(std::count_if(HiMask.begin(), HiMask.end(),
7828                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7829          "Failed to lift all the low half inputs to the high mask!");
7830
7831   // Do a half shuffle for the low mask.
7832   if (!isNoopShuffleMask(LoMask))
7833     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7834                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7835
7836   // Do a half shuffle with the high mask after shifting its values down.
7837   for (int &M : HiMask)
7838     if (M >= 0)
7839       M -= 4;
7840   if (!isNoopShuffleMask(HiMask))
7841     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7842                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7843
7844   return V;
7845 }
7846
7847 /// \brief Detect whether the mask pattern should be lowered through
7848 /// interleaving.
7849 ///
7850 /// This essentially tests whether viewing the mask as an interleaving of two
7851 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7852 /// lowering it through interleaving is a significantly better strategy.
7853 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7854   int NumEvenInputs[2] = {0, 0};
7855   int NumOddInputs[2] = {0, 0};
7856   int NumLoInputs[2] = {0, 0};
7857   int NumHiInputs[2] = {0, 0};
7858   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7859     if (Mask[i] < 0)
7860       continue;
7861
7862     int InputIdx = Mask[i] >= Size;
7863
7864     if (i < Size / 2)
7865       ++NumLoInputs[InputIdx];
7866     else
7867       ++NumHiInputs[InputIdx];
7868
7869     if ((i % 2) == 0)
7870       ++NumEvenInputs[InputIdx];
7871     else
7872       ++NumOddInputs[InputIdx];
7873   }
7874
7875   // The minimum number of cross-input results for both the interleaved and
7876   // split cases. If interleaving results in fewer cross-input results, return
7877   // true.
7878   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7879                                     NumEvenInputs[0] + NumOddInputs[1]);
7880   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7881                               NumLoInputs[0] + NumHiInputs[1]);
7882   return InterleavedCrosses < SplitCrosses;
7883 }
7884
7885 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7886 ///
7887 /// This strategy only works when the inputs from each vector fit into a single
7888 /// half of that vector, and generally there are not so many inputs as to leave
7889 /// the in-place shuffles required highly constrained (and thus expensive). It
7890 /// shifts all the inputs into a single side of both input vectors and then
7891 /// uses an unpack to interleave these inputs in a single vector. At that
7892 /// point, we will fall back on the generic single input shuffle lowering.
7893 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7894                                                  SDValue V2,
7895                                                  MutableArrayRef<int> Mask,
7896                                                  const X86Subtarget *Subtarget,
7897                                                  SelectionDAG &DAG) {
7898   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7899   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7900   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7901   for (int i = 0; i < 8; ++i)
7902     if (Mask[i] >= 0 && Mask[i] < 4)
7903       LoV1Inputs.push_back(i);
7904     else if (Mask[i] >= 4 && Mask[i] < 8)
7905       HiV1Inputs.push_back(i);
7906     else if (Mask[i] >= 8 && Mask[i] < 12)
7907       LoV2Inputs.push_back(i);
7908     else if (Mask[i] >= 12)
7909       HiV2Inputs.push_back(i);
7910
7911   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7912   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7913   (void)NumV1Inputs;
7914   (void)NumV2Inputs;
7915   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7916   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7917   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7918
7919   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7920                      HiV1Inputs.size() + HiV2Inputs.size();
7921
7922   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7923                               ArrayRef<int> HiInputs, bool MoveToLo,
7924                               int MaskOffset) {
7925     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7926     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7927     if (BadInputs.empty())
7928       return V;
7929
7930     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7931     int MoveOffset = MoveToLo ? 0 : 4;
7932
7933     if (GoodInputs.empty()) {
7934       for (int BadInput : BadInputs) {
7935         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7936         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7937       }
7938     } else {
7939       if (GoodInputs.size() == 2) {
7940         // If the low inputs are spread across two dwords, pack them into
7941         // a single dword.
7942         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7943         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7944         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7945         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7946       } else {
7947         // Otherwise pin the good inputs.
7948         for (int GoodInput : GoodInputs)
7949           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7950       }
7951
7952       if (BadInputs.size() == 2) {
7953         // If we have two bad inputs then there may be either one or two good
7954         // inputs fixed in place. Find a fixed input, and then find the *other*
7955         // two adjacent indices by using modular arithmetic.
7956         int GoodMaskIdx =
7957             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7958                          [](int M) { return M >= 0; }) -
7959             std::begin(MoveMask);
7960         int MoveMaskIdx =
7961             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
7962         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7963         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7964         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7965         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7966         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7967         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7968       } else {
7969         assert(BadInputs.size() == 1 && "All sizes handled");
7970         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7971                                     std::end(MoveMask), -1) -
7972                           std::begin(MoveMask);
7973         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7974         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7975       }
7976     }
7977
7978     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7979                                 MoveMask);
7980   };
7981   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7982                         /*MaskOffset*/ 0);
7983   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7984                         /*MaskOffset*/ 8);
7985
7986   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7987   // cross-half traffic in the final shuffle.
7988
7989   // Munge the mask to be a single-input mask after the unpack merges the
7990   // results.
7991   for (int &M : Mask)
7992     if (M != -1)
7993       M = 2 * (M % 4) + (M / 8);
7994
7995   return DAG.getVectorShuffle(
7996       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7997                                   DL, MVT::v8i16, V1, V2),
7998       DAG.getUNDEF(MVT::v8i16), Mask);
7999 }
8000
8001 /// \brief Generic lowering of 8-lane i16 shuffles.
8002 ///
8003 /// This handles both single-input shuffles and combined shuffle/blends with
8004 /// two inputs. The single input shuffles are immediately delegated to
8005 /// a dedicated lowering routine.
8006 ///
8007 /// The blends are lowered in one of three fundamental ways. If there are few
8008 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8009 /// of the input is significantly cheaper when lowered as an interleaving of
8010 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8011 /// halves of the inputs separately (making them have relatively few inputs)
8012 /// and then concatenate them.
8013 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8014                                        const X86Subtarget *Subtarget,
8015                                        SelectionDAG &DAG) {
8016   SDLoc DL(Op);
8017   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8018   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8019   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8020   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8021   ArrayRef<int> OrigMask = SVOp->getMask();
8022   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8023                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8024   MutableArrayRef<int> Mask(MaskStorage);
8025
8026   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8027
8028   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8029   auto isV2 = [](int M) { return M >= 8; };
8030
8031   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
8032   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8033
8034   if (NumV2Inputs == 0)
8035     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8036
8037   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
8038                             "to be V1-input shuffles.");
8039
8040   if (NumV1Inputs + NumV2Inputs <= 4)
8041     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
8042
8043   // Check whether an interleaving lowering is likely to be more efficient.
8044   // This isn't perfect but it is a strong heuristic that tends to work well on
8045   // the kinds of shuffles that show up in practice.
8046   //
8047   // FIXME: Handle 1x, 2x, and 4x interleaving.
8048   if (shouldLowerAsInterleaving(Mask)) {
8049     // FIXME: Figure out whether we should pack these into the low or high
8050     // halves.
8051
8052     int EMask[8], OMask[8];
8053     for (int i = 0; i < 4; ++i) {
8054       EMask[i] = Mask[2*i];
8055       OMask[i] = Mask[2*i + 1];
8056       EMask[i + 4] = -1;
8057       OMask[i + 4] = -1;
8058     }
8059
8060     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8061     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8062
8063     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8064   }
8065
8066   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8067   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8068
8069   for (int i = 0; i < 4; ++i) {
8070     LoBlendMask[i] = Mask[i];
8071     HiBlendMask[i] = Mask[i + 4];
8072   }
8073
8074   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8075   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8076   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8077   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8078
8079   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8080                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8081 }
8082
8083 /// \brief Check whether a compaction lowering can be done by dropping even
8084 /// elements and compute how many times even elements must be dropped.
8085 ///
8086 /// This handles shuffles which take every Nth element where N is a power of
8087 /// two. Example shuffle masks:
8088 ///
8089 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8090 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8091 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8092 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8093 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8094 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8095 ///
8096 /// Any of these lanes can of course be undef.
8097 ///
8098 /// This routine only supports N <= 3.
8099 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8100 /// for larger N.
8101 ///
8102 /// \returns N above, or the number of times even elements must be dropped if
8103 /// there is such a number. Otherwise returns zero.
8104 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8105   // Figure out whether we're looping over two inputs or just one.
8106   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8107
8108   // The modulus for the shuffle vector entries is based on whether this is
8109   // a single input or not.
8110   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8111   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8112          "We should only be called with masks with a power-of-2 size!");
8113
8114   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8115
8116   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8117   // and 2^3 simultaneously. This is because we may have ambiguity with
8118   // partially undef inputs.
8119   bool ViableForN[3] = {true, true, true};
8120
8121   for (int i = 0, e = Mask.size(); i < e; ++i) {
8122     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8123     // want.
8124     if (Mask[i] == -1)
8125       continue;
8126
8127     bool IsAnyViable = false;
8128     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8129       if (ViableForN[j]) {
8130         uint64_t N = j + 1;
8131
8132         // The shuffle mask must be equal to (i * 2^N) % M.
8133         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8134           IsAnyViable = true;
8135         else
8136           ViableForN[j] = false;
8137       }
8138     // Early exit if we exhaust the possible powers of two.
8139     if (!IsAnyViable)
8140       break;
8141   }
8142
8143   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8144     if (ViableForN[j])
8145       return j + 1;
8146
8147   // Return 0 as there is no viable power of two.
8148   return 0;
8149 }
8150
8151 /// \brief Generic lowering of v16i8 shuffles.
8152 ///
8153 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8154 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8155 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8156 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8157 /// back together.
8158 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8159                                        const X86Subtarget *Subtarget,
8160                                        SelectionDAG &DAG) {
8161   SDLoc DL(Op);
8162   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8163   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8164   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8165   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8166   ArrayRef<int> OrigMask = SVOp->getMask();
8167   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8168   int MaskStorage[16] = {
8169       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8170       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8171       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8172       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8173   MutableArrayRef<int> Mask(MaskStorage);
8174   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8175   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8176
8177   // For single-input shuffles, there are some nicer lowering tricks we can use.
8178   if (isSingleInputShuffleMask(Mask)) {
8179     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8180     // Notably, this handles splat and partial-splat shuffles more efficiently.
8181     // However, it only makes sense if the pre-duplication shuffle simplifies
8182     // things significantly. Currently, this means we need to be able to
8183     // express the pre-duplication shuffle as an i16 shuffle.
8184     //
8185     // FIXME: We should check for other patterns which can be widened into an
8186     // i16 shuffle as well.
8187     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8188       for (int i = 0; i < 16; i += 2) {
8189         if (Mask[i] != Mask[i + 1])
8190           return false;
8191       }
8192       return true;
8193     };
8194     auto tryToWidenViaDuplication = [&]() -> SDValue {
8195       if (!canWidenViaDuplication(Mask))
8196         return SDValue();
8197       SmallVector<int, 4> LoInputs;
8198       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8199                    [](int M) { return M >= 0 && M < 8; });
8200       std::sort(LoInputs.begin(), LoInputs.end());
8201       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8202                      LoInputs.end());
8203       SmallVector<int, 4> HiInputs;
8204       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8205                    [](int M) { return M >= 8; });
8206       std::sort(HiInputs.begin(), HiInputs.end());
8207       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8208                      HiInputs.end());
8209
8210       bool TargetLo = LoInputs.size() >= HiInputs.size();
8211       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8212       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8213
8214       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8215       SmallDenseMap<int, int, 8> LaneMap;
8216       for (int I : InPlaceInputs) {
8217         PreDupI16Shuffle[I/2] = I/2;
8218         LaneMap[I] = I;
8219       }
8220       int j = TargetLo ? 0 : 4, je = j + 4;
8221       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8222         // Check if j is already a shuffle of this input. This happens when
8223         // there are two adjacent bytes after we move the low one.
8224         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8225           // If we haven't yet mapped the input, search for a slot into which
8226           // we can map it.
8227           while (j < je && PreDupI16Shuffle[j] != -1)
8228             ++j;
8229
8230           if (j == je)
8231             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8232             return SDValue();
8233
8234           // Map this input with the i16 shuffle.
8235           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8236         }
8237
8238         // Update the lane map based on the mapping we ended up with.
8239         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8240       }
8241       V1 = DAG.getNode(
8242           ISD::BITCAST, DL, MVT::v16i8,
8243           DAG.getVectorShuffle(MVT::v8i16, DL,
8244                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8245                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8246
8247       // Unpack the bytes to form the i16s that will be shuffled into place.
8248       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8249                        MVT::v16i8, V1, V1);
8250
8251       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8252       for (int i = 0; i < 16; i += 2) {
8253         if (Mask[i] != -1)
8254           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8255         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8256       }
8257       return DAG.getNode(
8258           ISD::BITCAST, DL, MVT::v16i8,
8259           DAG.getVectorShuffle(MVT::v8i16, DL,
8260                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8261                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8262     };
8263     if (SDValue V = tryToWidenViaDuplication())
8264       return V;
8265   }
8266
8267   // Check whether an interleaving lowering is likely to be more efficient.
8268   // This isn't perfect but it is a strong heuristic that tends to work well on
8269   // the kinds of shuffles that show up in practice.
8270   //
8271   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8272   if (shouldLowerAsInterleaving(Mask)) {
8273     // FIXME: Figure out whether we should pack these into the low or high
8274     // halves.
8275
8276     int EMask[16], OMask[16];
8277     for (int i = 0; i < 8; ++i) {
8278       EMask[i] = Mask[2*i];
8279       OMask[i] = Mask[2*i + 1];
8280       EMask[i + 8] = -1;
8281       OMask[i + 8] = -1;
8282     }
8283
8284     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8285     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8286
8287     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8288   }
8289
8290   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8291   // with PSHUFB. It is important to do this before we attempt to generate any
8292   // blends but after all of the single-input lowerings. If the single input
8293   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8294   // want to preserve that and we can DAG combine any longer sequences into
8295   // a PSHUFB in the end. But once we start blending from multiple inputs,
8296   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8297   // and there are *very* few patterns that would actually be faster than the
8298   // PSHUFB approach because of its ability to zero lanes.
8299   //
8300   // FIXME: The only exceptions to the above are blends which are exact
8301   // interleavings with direct instructions supporting them. We currently don't
8302   // handle those well here.
8303   if (Subtarget->hasSSSE3()) {
8304     SDValue V1Mask[16];
8305     SDValue V2Mask[16];
8306     for (int i = 0; i < 16; ++i)
8307       if (Mask[i] == -1) {
8308         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8309       } else {
8310         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8311         V2Mask[i] =
8312             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8313       }
8314     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8315                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8316     if (isSingleInputShuffleMask(Mask))
8317       return V1; // Single inputs are easy.
8318
8319     // Otherwise, blend the two.
8320     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8321                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8322     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8323   }
8324
8325   // Check whether a compaction lowering can be done. This handles shuffles
8326   // which take every Nth element for some even N. See the helper function for
8327   // details.
8328   //
8329   // We special case these as they can be particularly efficiently handled with
8330   // the PACKUSB instruction on x86 and they show up in common patterns of
8331   // rearranging bytes to truncate wide elements.
8332   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8333     // NumEvenDrops is the power of two stride of the elements. Another way of
8334     // thinking about it is that we need to drop the even elements this many
8335     // times to get the original input.
8336     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8337
8338     // First we need to zero all the dropped bytes.
8339     assert(NumEvenDrops <= 3 &&
8340            "No support for dropping even elements more than 3 times.");
8341     // We use the mask type to pick which bytes are preserved based on how many
8342     // elements are dropped.
8343     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8344     SDValue ByteClearMask =
8345         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8346                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8347     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8348     if (!IsSingleInput)
8349       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8350
8351     // Now pack things back together.
8352     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8353     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8354     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8355     for (int i = 1; i < NumEvenDrops; ++i) {
8356       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8357       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8358     }
8359
8360     return Result;
8361   }
8362
8363   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8364   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8365   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8366   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8367
8368   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8369                             MutableArrayRef<int> V1HalfBlendMask,
8370                             MutableArrayRef<int> V2HalfBlendMask) {
8371     for (int i = 0; i < 8; ++i)
8372       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8373         V1HalfBlendMask[i] = HalfMask[i];
8374         HalfMask[i] = i;
8375       } else if (HalfMask[i] >= 16) {
8376         V2HalfBlendMask[i] = HalfMask[i] - 16;
8377         HalfMask[i] = i + 8;
8378       }
8379   };
8380   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8381   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8382
8383   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8384
8385   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8386                              MutableArrayRef<int> HiBlendMask) {
8387     SDValue V1, V2;
8388     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8389     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8390     // i16s.
8391     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8392                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8393         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8394                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8395       // Use a mask to drop the high bytes.
8396       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8397       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8398                        DAG.getConstant(0x00FF, MVT::v8i16));
8399
8400       // This will be a single vector shuffle instead of a blend so nuke V2.
8401       V2 = DAG.getUNDEF(MVT::v8i16);
8402
8403       // Squash the masks to point directly into V1.
8404       for (int &M : LoBlendMask)
8405         if (M >= 0)
8406           M /= 2;
8407       for (int &M : HiBlendMask)
8408         if (M >= 0)
8409           M /= 2;
8410     } else {
8411       // Otherwise just unpack the low half of V into V1 and the high half into
8412       // V2 so that we can blend them as i16s.
8413       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8414                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8415       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8416                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8417     }
8418
8419     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8420     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8421     return std::make_pair(BlendedLo, BlendedHi);
8422   };
8423   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8424   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8425   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8426
8427   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8428   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8429
8430   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8431 }
8432
8433 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8434 ///
8435 /// This routine breaks down the specific type of 128-bit shuffle and
8436 /// dispatches to the lowering routines accordingly.
8437 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8438                                         MVT VT, const X86Subtarget *Subtarget,
8439                                         SelectionDAG &DAG) {
8440   switch (VT.SimpleTy) {
8441   case MVT::v2i64:
8442     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8443   case MVT::v2f64:
8444     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8445   case MVT::v4i32:
8446     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8447   case MVT::v4f32:
8448     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8449   case MVT::v8i16:
8450     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8451   case MVT::v16i8:
8452     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8453
8454   default:
8455     llvm_unreachable("Unimplemented!");
8456   }
8457 }
8458
8459 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8460   int Size = Mask.size();
8461   for (int M : Mask.slice(0, Size / 2))
8462     if (M >= 0 && (M % Size) >= Size / 2)
8463       return true;
8464   for (int M : Mask.slice(Size / 2, Size / 2))
8465     if (M >= 0 && (M % Size) < Size / 2)
8466       return true;
8467   return false;
8468 }
8469
8470 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8471 /// shuffles.
8472 ///
8473 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8474 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8475 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8476 /// we encode the logic here for specific shuffle lowering routines to bail to
8477 /// when they exhaust the features avaible to more directly handle the shuffle.
8478 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8479                                                 SDValue V2,
8480                                                 const X86Subtarget *Subtarget,
8481                                                 SelectionDAG &DAG) {
8482   SDLoc DL(Op);
8483   MVT VT = Op.getSimpleValueType();
8484   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8485   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8486   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8487   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8488   ArrayRef<int> Mask = SVOp->getMask();
8489
8490   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8491   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8492
8493   int NumElements = VT.getVectorNumElements();
8494   int SplitNumElements = NumElements / 2;
8495   MVT ScalarVT = VT.getScalarType();
8496   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8497
8498   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8499                              DAG.getIntPtrConstant(0));
8500   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8501                              DAG.getIntPtrConstant(SplitNumElements));
8502   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8503                              DAG.getIntPtrConstant(0));
8504   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8505                              DAG.getIntPtrConstant(SplitNumElements));
8506
8507   // Now create two 4-way blends of these half-width vectors.
8508   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8509     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8510     for (int i = 0; i < SplitNumElements; ++i) {
8511       int M = HalfMask[i];
8512       if (M >= NumElements) {
8513         V2BlendMask.push_back(M - NumElements);
8514         V1BlendMask.push_back(-1);
8515         BlendMask.push_back(SplitNumElements + i);
8516       } else if (M >= 0) {
8517         V2BlendMask.push_back(-1);
8518         V1BlendMask.push_back(M);
8519         BlendMask.push_back(i);
8520       } else {
8521         V2BlendMask.push_back(-1);
8522         V1BlendMask.push_back(-1);
8523         BlendMask.push_back(-1);
8524       }
8525     }
8526     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8527     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8528     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8529   };
8530   SDValue Lo = HalfBlend(LoMask);
8531   SDValue Hi = HalfBlend(HiMask);
8532   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8533 }
8534
8535 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8536 ///
8537 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8538 /// isn't available.
8539 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8540                                        const X86Subtarget *Subtarget,
8541                                        SelectionDAG &DAG) {
8542   SDLoc DL(Op);
8543   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8544   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8545   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8546   ArrayRef<int> Mask = SVOp->getMask();
8547   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8548
8549   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8550   // shuffles aren't a problem and FP and int have the same patterns.
8551
8552   // FIXME: We can handle these more cleverly than splitting for v4f64.
8553   if (isHalfCrossingShuffleMask(Mask))
8554     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8555
8556   if (isSingleInputShuffleMask(Mask)) {
8557     // Non-half-crossing single input shuffles can be lowerid with an
8558     // interleaved permutation.
8559     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8560                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8561     return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8562                        DAG.getConstant(VPERMILPMask, MVT::i8));
8563   }
8564
8565   // X86 has dedicated unpack instructions that can handle specific blend
8566   // operations: UNPCKH and UNPCKL.
8567   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8568     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8569   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8570     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8571   // FIXME: It would be nice to find a way to get canonicalization to commute
8572   // these patterns.
8573   if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8574     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8575   if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8576     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8577
8578   // Check if the blend happens to exactly fit that of SHUFPD.
8579   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8580       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8581     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8582                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8583     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8584                        DAG.getConstant(SHUFPDMask, MVT::i8));
8585   }
8586   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8587       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8588     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8589                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8590     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8591                        DAG.getConstant(SHUFPDMask, MVT::i8));
8592   }
8593
8594   // Shuffle the input elements into the desired positions in V1 and V2 and
8595   // blend them together.
8596   int V1Mask[] = {-1, -1, -1, -1};
8597   int V2Mask[] = {-1, -1, -1, -1};
8598   for (int i = 0; i < 4; ++i)
8599     if (Mask[i] >= 0 && Mask[i] < 4)
8600       V1Mask[i] = Mask[i];
8601     else if (Mask[i] >= 4)
8602       V2Mask[i] = Mask[i] - 4;
8603
8604   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8605   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8606
8607   unsigned BlendMask = 0;
8608   for (int i = 0; i < 4; ++i)
8609     if (Mask[i] >= 4)
8610       BlendMask |= 1 << i;
8611
8612   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8613                      DAG.getConstant(BlendMask, MVT::i8));
8614 }
8615
8616 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8617 ///
8618 /// Largely delegates to common code when we have AVX2 and to the floating-point
8619 /// code when we only have AVX.
8620 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8621                                        const X86Subtarget *Subtarget,
8622                                        SelectionDAG &DAG) {
8623   SDLoc DL(Op);
8624   assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8625   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8626   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8627   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8628   ArrayRef<int> Mask = SVOp->getMask();
8629   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8630
8631   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8632   // shuffles aren't a problem and FP and int have the same patterns.
8633
8634   if (isHalfCrossingShuffleMask(Mask))
8635     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8636
8637   // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8638   // delegate to floating point code.
8639   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8640   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8641   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8642                      lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8643 }
8644
8645 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8646 ///
8647 /// This routine either breaks down the specific type of a 256-bit x86 vector
8648 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8649 /// together based on the available instructions.
8650 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8651                                         MVT VT, const X86Subtarget *Subtarget,
8652                                         SelectionDAG &DAG) {
8653   switch (VT.SimpleTy) {
8654   case MVT::v4f64:
8655     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8656   case MVT::v4i64:
8657     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8658   case MVT::v8i32:
8659   case MVT::v8f32:
8660   case MVT::v16i16:
8661   case MVT::v32i8:
8662     // Fall back to the basic pattern of extracting the high half and forming
8663     // a 4-way blend.
8664     // FIXME: Add targeted lowering for each type that can document rationale
8665     // for delegating to this when necessary.
8666     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8667
8668   default:
8669     llvm_unreachable("Not a valid 256-bit x86 vector type!");
8670   }
8671 }
8672
8673 /// \brief Tiny helper function to test whether a shuffle mask could be
8674 /// simplified by widening the elements being shuffled.
8675 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8676   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8677     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8678       return false;
8679
8680   return true;
8681 }
8682
8683 /// \brief Top-level lowering for x86 vector shuffles.
8684 ///
8685 /// This handles decomposition, canonicalization, and lowering of all x86
8686 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8687 /// above in helper routines. The canonicalization attempts to widen shuffles
8688 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8689 /// s.t. only one of the two inputs needs to be tested, etc.
8690 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8691                                   SelectionDAG &DAG) {
8692   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8693   ArrayRef<int> Mask = SVOp->getMask();
8694   SDValue V1 = Op.getOperand(0);
8695   SDValue V2 = Op.getOperand(1);
8696   MVT VT = Op.getSimpleValueType();
8697   int NumElements = VT.getVectorNumElements();
8698   SDLoc dl(Op);
8699
8700   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8701
8702   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8703   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8704   if (V1IsUndef && V2IsUndef)
8705     return DAG.getUNDEF(VT);
8706
8707   // When we create a shuffle node we put the UNDEF node to second operand,
8708   // but in some cases the first operand may be transformed to UNDEF.
8709   // In this case we should just commute the node.
8710   if (V1IsUndef)
8711     return DAG.getCommutedVectorShuffle(*SVOp);
8712
8713   // Check for non-undef masks pointing at an undef vector and make the masks
8714   // undef as well. This makes it easier to match the shuffle based solely on
8715   // the mask.
8716   if (V2IsUndef)
8717     for (int M : Mask)
8718       if (M >= NumElements) {
8719         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8720         for (int &M : NewMask)
8721           if (M >= NumElements)
8722             M = -1;
8723         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8724       }
8725
8726   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8727   // lanes but wider integers. We cap this to not form integers larger than i64
8728   // but it might be interesting to form i128 integers to handle flipping the
8729   // low and high halves of AVX 256-bit vectors.
8730   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8731       canWidenShuffleElements(Mask)) {
8732     SmallVector<int, 8> NewMask;
8733     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8734       NewMask.push_back(Mask[i] / 2);
8735     MVT NewVT =
8736         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8737                          VT.getVectorNumElements() / 2);
8738     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8739     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8740     return DAG.getNode(ISD::BITCAST, dl, VT,
8741                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8742   }
8743
8744   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8745   for (int M : SVOp->getMask())
8746     if (M < 0)
8747       ++NumUndefElements;
8748     else if (M < NumElements)
8749       ++NumV1Elements;
8750     else
8751       ++NumV2Elements;
8752
8753   // Commute the shuffle as needed such that more elements come from V1 than
8754   // V2. This allows us to match the shuffle pattern strictly on how many
8755   // elements come from V1 without handling the symmetric cases.
8756   if (NumV2Elements > NumV1Elements)
8757     return DAG.getCommutedVectorShuffle(*SVOp);
8758
8759   // When the number of V1 and V2 elements are the same, try to minimize the
8760   // number of uses of V2 in the low half of the vector.
8761   if (NumV1Elements == NumV2Elements) {
8762     int LowV1Elements = 0, LowV2Elements = 0;
8763     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8764       if (M >= NumElements)
8765         ++LowV2Elements;
8766       else if (M >= 0)
8767         ++LowV1Elements;
8768     if (LowV2Elements > LowV1Elements)
8769       return DAG.getCommutedVectorShuffle(*SVOp);
8770   }
8771
8772   // For each vector width, delegate to a specialized lowering routine.
8773   if (VT.getSizeInBits() == 128)
8774     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8775
8776   if (VT.getSizeInBits() == 256)
8777     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8778
8779   llvm_unreachable("Unimplemented!");
8780 }
8781
8782
8783 //===----------------------------------------------------------------------===//
8784 // Legacy vector shuffle lowering
8785 //
8786 // This code is the legacy code handling vector shuffles until the above
8787 // replaces its functionality and performance.
8788 //===----------------------------------------------------------------------===//
8789
8790 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8791                         bool hasInt256, unsigned *MaskOut = nullptr) {
8792   MVT EltVT = VT.getVectorElementType();
8793
8794   // There is no blend with immediate in AVX-512.
8795   if (VT.is512BitVector())
8796     return false;
8797
8798   if (!hasSSE41 || EltVT == MVT::i8)
8799     return false;
8800   if (!hasInt256 && VT == MVT::v16i16)
8801     return false;
8802
8803   unsigned MaskValue = 0;
8804   unsigned NumElems = VT.getVectorNumElements();
8805   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8806   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8807   unsigned NumElemsInLane = NumElems / NumLanes;
8808
8809   // Blend for v16i16 should be symetric for the both lanes.
8810   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8811
8812     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8813     int EltIdx = MaskVals[i];
8814
8815     if ((EltIdx < 0 || EltIdx == (int)i) &&
8816         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8817       continue;
8818
8819     if (((unsigned)EltIdx == (i + NumElems)) &&
8820         (SndLaneEltIdx < 0 ||
8821          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8822       MaskValue |= (1 << i);
8823     else
8824       return false;
8825   }
8826
8827   if (MaskOut)
8828     *MaskOut = MaskValue;
8829   return true;
8830 }
8831
8832 // Try to lower a shuffle node into a simple blend instruction.
8833 // This function assumes isBlendMask returns true for this
8834 // SuffleVectorSDNode
8835 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8836                                           unsigned MaskValue,
8837                                           const X86Subtarget *Subtarget,
8838                                           SelectionDAG &DAG) {
8839   MVT VT = SVOp->getSimpleValueType(0);
8840   MVT EltVT = VT.getVectorElementType();
8841   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8842                      Subtarget->hasInt256() && "Trying to lower a "
8843                                                "VECTOR_SHUFFLE to a Blend but "
8844                                                "with the wrong mask"));
8845   SDValue V1 = SVOp->getOperand(0);
8846   SDValue V2 = SVOp->getOperand(1);
8847   SDLoc dl(SVOp);
8848   unsigned NumElems = VT.getVectorNumElements();
8849
8850   // Convert i32 vectors to floating point if it is not AVX2.
8851   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8852   MVT BlendVT = VT;
8853   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8854     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8855                                NumElems);
8856     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8857     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8858   }
8859
8860   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8861                             DAG.getConstant(MaskValue, MVT::i32));
8862   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8863 }
8864
8865 /// In vector type \p VT, return true if the element at index \p InputIdx
8866 /// falls on a different 128-bit lane than \p OutputIdx.
8867 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8868                                      unsigned OutputIdx) {
8869   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8870   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8871 }
8872
8873 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8874 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8875 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8876 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8877 /// zero.
8878 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8879                          SelectionDAG &DAG) {
8880   MVT VT = V1.getSimpleValueType();
8881   assert(VT.is128BitVector() || VT.is256BitVector());
8882
8883   MVT EltVT = VT.getVectorElementType();
8884   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8885   unsigned NumElts = VT.getVectorNumElements();
8886
8887   SmallVector<SDValue, 32> PshufbMask;
8888   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8889     int InputIdx = MaskVals[OutputIdx];
8890     unsigned InputByteIdx;
8891
8892     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8893       InputByteIdx = 0x80;
8894     else {
8895       // Cross lane is not allowed.
8896       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8897         return SDValue();
8898       InputByteIdx = InputIdx * EltSizeInBytes;
8899       // Index is an byte offset within the 128-bit lane.
8900       InputByteIdx &= 0xf;
8901     }
8902
8903     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8904       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8905       if (InputByteIdx != 0x80)
8906         ++InputByteIdx;
8907     }
8908   }
8909
8910   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8911   if (ShufVT != VT)
8912     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8913   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8914                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8915 }
8916
8917 // v8i16 shuffles - Prefer shuffles in the following order:
8918 // 1. [all]   pshuflw, pshufhw, optional move
8919 // 2. [ssse3] 1 x pshufb
8920 // 3. [ssse3] 2 x pshufb + 1 x por
8921 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8922 static SDValue
8923 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8924                          SelectionDAG &DAG) {
8925   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8926   SDValue V1 = SVOp->getOperand(0);
8927   SDValue V2 = SVOp->getOperand(1);
8928   SDLoc dl(SVOp);
8929   SmallVector<int, 8> MaskVals;
8930
8931   // Determine if more than 1 of the words in each of the low and high quadwords
8932   // of the result come from the same quadword of one of the two inputs.  Undef
8933   // mask values count as coming from any quadword, for better codegen.
8934   //
8935   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8936   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8937   unsigned LoQuad[] = { 0, 0, 0, 0 };
8938   unsigned HiQuad[] = { 0, 0, 0, 0 };
8939   // Indices of quads used.
8940   std::bitset<4> InputQuads;
8941   for (unsigned i = 0; i < 8; ++i) {
8942     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8943     int EltIdx = SVOp->getMaskElt(i);
8944     MaskVals.push_back(EltIdx);
8945     if (EltIdx < 0) {
8946       ++Quad[0];
8947       ++Quad[1];
8948       ++Quad[2];
8949       ++Quad[3];
8950       continue;
8951     }
8952     ++Quad[EltIdx / 4];
8953     InputQuads.set(EltIdx / 4);
8954   }
8955
8956   int BestLoQuad = -1;
8957   unsigned MaxQuad = 1;
8958   for (unsigned i = 0; i < 4; ++i) {
8959     if (LoQuad[i] > MaxQuad) {
8960       BestLoQuad = i;
8961       MaxQuad = LoQuad[i];
8962     }
8963   }
8964
8965   int BestHiQuad = -1;
8966   MaxQuad = 1;
8967   for (unsigned i = 0; i < 4; ++i) {
8968     if (HiQuad[i] > MaxQuad) {
8969       BestHiQuad = i;
8970       MaxQuad = HiQuad[i];
8971     }
8972   }
8973
8974   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8975   // of the two input vectors, shuffle them into one input vector so only a
8976   // single pshufb instruction is necessary. If there are more than 2 input
8977   // quads, disable the next transformation since it does not help SSSE3.
8978   bool V1Used = InputQuads[0] || InputQuads[1];
8979   bool V2Used = InputQuads[2] || InputQuads[3];
8980   if (Subtarget->hasSSSE3()) {
8981     if (InputQuads.count() == 2 && V1Used && V2Used) {
8982       BestLoQuad = InputQuads[0] ? 0 : 1;
8983       BestHiQuad = InputQuads[2] ? 2 : 3;
8984     }
8985     if (InputQuads.count() > 2) {
8986       BestLoQuad = -1;
8987       BestHiQuad = -1;
8988     }
8989   }
8990
8991   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8992   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8993   // words from all 4 input quadwords.
8994   SDValue NewV;
8995   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8996     int MaskV[] = {
8997       BestLoQuad < 0 ? 0 : BestLoQuad,
8998       BestHiQuad < 0 ? 1 : BestHiQuad
8999     };
9000     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
9001                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
9002                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
9003     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
9004
9005     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
9006     // source words for the shuffle, to aid later transformations.
9007     bool AllWordsInNewV = true;
9008     bool InOrder[2] = { true, true };
9009     for (unsigned i = 0; i != 8; ++i) {
9010       int idx = MaskVals[i];
9011       if (idx != (int)i)
9012         InOrder[i/4] = false;
9013       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
9014         continue;
9015       AllWordsInNewV = false;
9016       break;
9017     }
9018
9019     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
9020     if (AllWordsInNewV) {
9021       for (int i = 0; i != 8; ++i) {
9022         int idx = MaskVals[i];
9023         if (idx < 0)
9024           continue;
9025         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
9026         if ((idx != i) && idx < 4)
9027           pshufhw = false;
9028         if ((idx != i) && idx > 3)
9029           pshuflw = false;
9030       }
9031       V1 = NewV;
9032       V2Used = false;
9033       BestLoQuad = 0;
9034       BestHiQuad = 1;
9035     }
9036
9037     // If we've eliminated the use of V2, and the new mask is a pshuflw or
9038     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
9039     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
9040       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
9041       unsigned TargetMask = 0;
9042       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
9043                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
9044       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9045       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
9046                              getShufflePSHUFLWImmediate(SVOp);
9047       V1 = NewV.getOperand(0);
9048       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
9049     }
9050   }
9051
9052   // Promote splats to a larger type which usually leads to more efficient code.
9053   // FIXME: Is this true if pshufb is available?
9054   if (SVOp->isSplat())
9055     return PromoteSplat(SVOp, DAG);
9056
9057   // If we have SSSE3, and all words of the result are from 1 input vector,
9058   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
9059   // is present, fall back to case 4.
9060   if (Subtarget->hasSSSE3()) {
9061     SmallVector<SDValue,16> pshufbMask;
9062
9063     // If we have elements from both input vectors, set the high bit of the
9064     // shuffle mask element to zero out elements that come from V2 in the V1
9065     // mask, and elements that come from V1 in the V2 mask, so that the two
9066     // results can be OR'd together.
9067     bool TwoInputs = V1Used && V2Used;
9068     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9069     if (!TwoInputs)
9070       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9071
9072     // Calculate the shuffle mask for the second input, shuffle it, and
9073     // OR it with the first shuffled input.
9074     CommuteVectorShuffleMask(MaskVals, 8);
9075     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9076     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9077     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9078   }
9079
9080   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9081   // and update MaskVals with new element order.
9082   std::bitset<8> InOrder;
9083   if (BestLoQuad >= 0) {
9084     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9085     for (int i = 0; i != 4; ++i) {
9086       int idx = MaskVals[i];
9087       if (idx < 0) {
9088         InOrder.set(i);
9089       } else if ((idx / 4) == BestLoQuad) {
9090         MaskV[i] = idx & 3;
9091         InOrder.set(i);
9092       }
9093     }
9094     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9095                                 &MaskV[0]);
9096
9097     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9098       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9099       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9100                                   NewV.getOperand(0),
9101                                   getShufflePSHUFLWImmediate(SVOp), DAG);
9102     }
9103   }
9104
9105   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9106   // and update MaskVals with the new element order.
9107   if (BestHiQuad >= 0) {
9108     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9109     for (unsigned i = 4; i != 8; ++i) {
9110       int idx = MaskVals[i];
9111       if (idx < 0) {
9112         InOrder.set(i);
9113       } else if ((idx / 4) == BestHiQuad) {
9114         MaskV[i] = (idx & 3) + 4;
9115         InOrder.set(i);
9116       }
9117     }
9118     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9119                                 &MaskV[0]);
9120
9121     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9122       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9123       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9124                                   NewV.getOperand(0),
9125                                   getShufflePSHUFHWImmediate(SVOp), DAG);
9126     }
9127   }
9128
9129   // In case BestHi & BestLo were both -1, which means each quadword has a word
9130   // from each of the four input quadwords, calculate the InOrder bitvector now
9131   // before falling through to the insert/extract cleanup.
9132   if (BestLoQuad == -1 && BestHiQuad == -1) {
9133     NewV = V1;
9134     for (int i = 0; i != 8; ++i)
9135       if (MaskVals[i] < 0 || MaskVals[i] == i)
9136         InOrder.set(i);
9137   }
9138
9139   // The other elements are put in the right place using pextrw and pinsrw.
9140   for (unsigned i = 0; i != 8; ++i) {
9141     if (InOrder[i])
9142       continue;
9143     int EltIdx = MaskVals[i];
9144     if (EltIdx < 0)
9145       continue;
9146     SDValue ExtOp = (EltIdx < 8) ?
9147       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9148                   DAG.getIntPtrConstant(EltIdx)) :
9149       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9150                   DAG.getIntPtrConstant(EltIdx - 8));
9151     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9152                        DAG.getIntPtrConstant(i));
9153   }
9154   return NewV;
9155 }
9156
9157 /// \brief v16i16 shuffles
9158 ///
9159 /// FIXME: We only support generation of a single pshufb currently.  We can
9160 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9161 /// well (e.g 2 x pshufb + 1 x por).
9162 static SDValue
9163 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9165   SDValue V1 = SVOp->getOperand(0);
9166   SDValue V2 = SVOp->getOperand(1);
9167   SDLoc dl(SVOp);
9168
9169   if (V2.getOpcode() != ISD::UNDEF)
9170     return SDValue();
9171
9172   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9173   return getPSHUFB(MaskVals, V1, dl, DAG);
9174 }
9175
9176 // v16i8 shuffles - Prefer shuffles in the following order:
9177 // 1. [ssse3] 1 x pshufb
9178 // 2. [ssse3] 2 x pshufb + 1 x por
9179 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
9180 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9181                                         const X86Subtarget* Subtarget,
9182                                         SelectionDAG &DAG) {
9183   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9184   SDValue V1 = SVOp->getOperand(0);
9185   SDValue V2 = SVOp->getOperand(1);
9186   SDLoc dl(SVOp);
9187   ArrayRef<int> MaskVals = SVOp->getMask();
9188
9189   // Promote splats to a larger type which usually leads to more efficient code.
9190   // FIXME: Is this true if pshufb is available?
9191   if (SVOp->isSplat())
9192     return PromoteSplat(SVOp, DAG);
9193
9194   // If we have SSSE3, case 1 is generated when all result bytes come from
9195   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
9196   // present, fall back to case 3.
9197
9198   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9199   if (Subtarget->hasSSSE3()) {
9200     SmallVector<SDValue,16> pshufbMask;
9201
9202     // If all result elements are from one input vector, then only translate
9203     // undef mask values to 0x80 (zero out result) in the pshufb mask.
9204     //
9205     // Otherwise, we have elements from both input vectors, and must zero out
9206     // elements that come from V2 in the first mask, and V1 in the second mask
9207     // so that we can OR them together.
9208     for (unsigned i = 0; i != 16; ++i) {
9209       int EltIdx = MaskVals[i];
9210       if (EltIdx < 0 || EltIdx >= 16)
9211         EltIdx = 0x80;
9212       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9213     }
9214     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9215                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9216                                  MVT::v16i8, pshufbMask));
9217
9218     // As PSHUFB will zero elements with negative indices, it's safe to ignore
9219     // the 2nd operand if it's undefined or zero.
9220     if (V2.getOpcode() == ISD::UNDEF ||
9221         ISD::isBuildVectorAllZeros(V2.getNode()))
9222       return V1;
9223
9224     // Calculate the shuffle mask for the second input, shuffle it, and
9225     // OR it with the first shuffled input.
9226     pshufbMask.clear();
9227     for (unsigned i = 0; i != 16; ++i) {
9228       int EltIdx = MaskVals[i];
9229       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9230       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9231     }
9232     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9233                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9234                                  MVT::v16i8, pshufbMask));
9235     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9236   }
9237
9238   // No SSSE3 - Calculate in place words and then fix all out of place words
9239   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
9240   // the 16 different words that comprise the two doublequadword input vectors.
9241   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9242   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9243   SDValue NewV = V1;
9244   for (int i = 0; i != 8; ++i) {
9245     int Elt0 = MaskVals[i*2];
9246     int Elt1 = MaskVals[i*2+1];
9247
9248     // This word of the result is all undef, skip it.
9249     if (Elt0 < 0 && Elt1 < 0)
9250       continue;
9251
9252     // This word of the result is already in the correct place, skip it.
9253     if ((Elt0 == i*2) && (Elt1 == i*2+1))
9254       continue;
9255
9256     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9257     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9258     SDValue InsElt;
9259
9260     // If Elt0 and Elt1 are defined, are consecutive, and can be load
9261     // using a single extract together, load it and store it.
9262     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9263       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9264                            DAG.getIntPtrConstant(Elt1 / 2));
9265       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9266                         DAG.getIntPtrConstant(i));
9267       continue;
9268     }
9269
9270     // If Elt1 is defined, extract it from the appropriate source.  If the
9271     // source byte is not also odd, shift the extracted word left 8 bits
9272     // otherwise clear the bottom 8 bits if we need to do an or.
9273     if (Elt1 >= 0) {
9274       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9275                            DAG.getIntPtrConstant(Elt1 / 2));
9276       if ((Elt1 & 1) == 0)
9277         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9278                              DAG.getConstant(8,
9279                                   TLI.getShiftAmountTy(InsElt.getValueType())));
9280       else if (Elt0 >= 0)
9281         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9282                              DAG.getConstant(0xFF00, MVT::i16));
9283     }
9284     // If Elt0 is defined, extract it from the appropriate source.  If the
9285     // source byte is not also even, shift the extracted word right 8 bits. If
9286     // Elt1 was also defined, OR the extracted values together before
9287     // inserting them in the result.
9288     if (Elt0 >= 0) {
9289       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9290                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9291       if ((Elt0 & 1) != 0)
9292         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9293                               DAG.getConstant(8,
9294                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
9295       else if (Elt1 >= 0)
9296         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9297                              DAG.getConstant(0x00FF, MVT::i16));
9298       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9299                          : InsElt0;
9300     }
9301     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9302                        DAG.getIntPtrConstant(i));
9303   }
9304   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9305 }
9306
9307 // v32i8 shuffles - Translate to VPSHUFB if possible.
9308 static
9309 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9310                                  const X86Subtarget *Subtarget,
9311                                  SelectionDAG &DAG) {
9312   MVT VT = SVOp->getSimpleValueType(0);
9313   SDValue V1 = SVOp->getOperand(0);
9314   SDValue V2 = SVOp->getOperand(1);
9315   SDLoc dl(SVOp);
9316   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9317
9318   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9319   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9320   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9321
9322   // VPSHUFB may be generated if
9323   // (1) one of input vector is undefined or zeroinitializer.
9324   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9325   // And (2) the mask indexes don't cross the 128-bit lane.
9326   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9327       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9328     return SDValue();
9329
9330   if (V1IsAllZero && !V2IsAllZero) {
9331     CommuteVectorShuffleMask(MaskVals, 32);
9332     V1 = V2;
9333   }
9334   return getPSHUFB(MaskVals, V1, dl, DAG);
9335 }
9336
9337 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9338 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9339 /// done when every pair / quad of shuffle mask elements point to elements in
9340 /// the right sequence. e.g.
9341 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9342 static
9343 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9344                                  SelectionDAG &DAG) {
9345   MVT VT = SVOp->getSimpleValueType(0);
9346   SDLoc dl(SVOp);
9347   unsigned NumElems = VT.getVectorNumElements();
9348   MVT NewVT;
9349   unsigned Scale;
9350   switch (VT.SimpleTy) {
9351   default: llvm_unreachable("Unexpected!");
9352   case MVT::v2i64:
9353   case MVT::v2f64:
9354            return SDValue(SVOp, 0);
9355   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9356   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9357   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9358   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9359   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9360   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9361   }
9362
9363   SmallVector<int, 8> MaskVec;
9364   for (unsigned i = 0; i != NumElems; i += Scale) {
9365     int StartIdx = -1;
9366     for (unsigned j = 0; j != Scale; ++j) {
9367       int EltIdx = SVOp->getMaskElt(i+j);
9368       if (EltIdx < 0)
9369         continue;
9370       if (StartIdx < 0)
9371         StartIdx = (EltIdx / Scale);
9372       if (EltIdx != (int)(StartIdx*Scale + j))
9373         return SDValue();
9374     }
9375     MaskVec.push_back(StartIdx);
9376   }
9377
9378   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9379   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9380   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9381 }
9382
9383 /// getVZextMovL - Return a zero-extending vector move low node.
9384 ///
9385 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9386                             SDValue SrcOp, SelectionDAG &DAG,
9387                             const X86Subtarget *Subtarget, SDLoc dl) {
9388   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9389     LoadSDNode *LD = nullptr;
9390     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9391       LD = dyn_cast<LoadSDNode>(SrcOp);
9392     if (!LD) {
9393       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9394       // instead.
9395       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9396       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9397           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9398           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9399           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9400         // PR2108
9401         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9402         return DAG.getNode(ISD::BITCAST, dl, VT,
9403                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9404                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9405                                                    OpVT,
9406                                                    SrcOp.getOperand(0)
9407                                                           .getOperand(0))));
9408       }
9409     }
9410   }
9411
9412   return DAG.getNode(ISD::BITCAST, dl, VT,
9413                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9414                                  DAG.getNode(ISD::BITCAST, dl,
9415                                              OpVT, SrcOp)));
9416 }
9417
9418 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9419 /// which could not be matched by any known target speficic shuffle
9420 static SDValue
9421 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9422
9423   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9424   if (NewOp.getNode())
9425     return NewOp;
9426
9427   MVT VT = SVOp->getSimpleValueType(0);
9428
9429   unsigned NumElems = VT.getVectorNumElements();
9430   unsigned NumLaneElems = NumElems / 2;
9431
9432   SDLoc dl(SVOp);
9433   MVT EltVT = VT.getVectorElementType();
9434   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9435   SDValue Output[2];
9436
9437   SmallVector<int, 16> Mask;
9438   for (unsigned l = 0; l < 2; ++l) {
9439     // Build a shuffle mask for the output, discovering on the fly which
9440     // input vectors to use as shuffle operands (recorded in InputUsed).
9441     // If building a suitable shuffle vector proves too hard, then bail
9442     // out with UseBuildVector set.
9443     bool UseBuildVector = false;
9444     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9445     unsigned LaneStart = l * NumLaneElems;
9446     for (unsigned i = 0; i != NumLaneElems; ++i) {
9447       // The mask element.  This indexes into the input.
9448       int Idx = SVOp->getMaskElt(i+LaneStart);
9449       if (Idx < 0) {
9450         // the mask element does not index into any input vector.
9451         Mask.push_back(-1);
9452         continue;
9453       }
9454
9455       // The input vector this mask element indexes into.
9456       int Input = Idx / NumLaneElems;
9457
9458       // Turn the index into an offset from the start of the input vector.
9459       Idx -= Input * NumLaneElems;
9460
9461       // Find or create a shuffle vector operand to hold this input.
9462       unsigned OpNo;
9463       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9464         if (InputUsed[OpNo] == Input)
9465           // This input vector is already an operand.
9466           break;
9467         if (InputUsed[OpNo] < 0) {
9468           // Create a new operand for this input vector.
9469           InputUsed[OpNo] = Input;
9470           break;
9471         }
9472       }
9473
9474       if (OpNo >= array_lengthof(InputUsed)) {
9475         // More than two input vectors used!  Give up on trying to create a
9476         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9477         UseBuildVector = true;
9478         break;
9479       }
9480
9481       // Add the mask index for the new shuffle vector.
9482       Mask.push_back(Idx + OpNo * NumLaneElems);
9483     }
9484
9485     if (UseBuildVector) {
9486       SmallVector<SDValue, 16> SVOps;
9487       for (unsigned i = 0; i != NumLaneElems; ++i) {
9488         // The mask element.  This indexes into the input.
9489         int Idx = SVOp->getMaskElt(i+LaneStart);
9490         if (Idx < 0) {
9491           SVOps.push_back(DAG.getUNDEF(EltVT));
9492           continue;
9493         }
9494
9495         // The input vector this mask element indexes into.
9496         int Input = Idx / NumElems;
9497
9498         // Turn the index into an offset from the start of the input vector.
9499         Idx -= Input * NumElems;
9500
9501         // Extract the vector element by hand.
9502         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9503                                     SVOp->getOperand(Input),
9504                                     DAG.getIntPtrConstant(Idx)));
9505       }
9506
9507       // Construct the output using a BUILD_VECTOR.
9508       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9509     } else if (InputUsed[0] < 0) {
9510       // No input vectors were used! The result is undefined.
9511       Output[l] = DAG.getUNDEF(NVT);
9512     } else {
9513       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9514                                         (InputUsed[0] % 2) * NumLaneElems,
9515                                         DAG, dl);
9516       // If only one input was used, use an undefined vector for the other.
9517       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9518         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9519                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9520       // At least one input vector was used. Create a new shuffle vector.
9521       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9522     }
9523
9524     Mask.clear();
9525   }
9526
9527   // Concatenate the result back
9528   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9529 }
9530
9531 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9532 /// 4 elements, and match them with several different shuffle types.
9533 static SDValue
9534 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9535   SDValue V1 = SVOp->getOperand(0);
9536   SDValue V2 = SVOp->getOperand(1);
9537   SDLoc dl(SVOp);
9538   MVT VT = SVOp->getSimpleValueType(0);
9539
9540   assert(VT.is128BitVector() && "Unsupported vector size");
9541
9542   std::pair<int, int> Locs[4];
9543   int Mask1[] = { -1, -1, -1, -1 };
9544   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9545
9546   unsigned NumHi = 0;
9547   unsigned NumLo = 0;
9548   for (unsigned i = 0; i != 4; ++i) {
9549     int Idx = PermMask[i];
9550     if (Idx < 0) {
9551       Locs[i] = std::make_pair(-1, -1);
9552     } else {
9553       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9554       if (Idx < 4) {
9555         Locs[i] = std::make_pair(0, NumLo);
9556         Mask1[NumLo] = Idx;
9557         NumLo++;
9558       } else {
9559         Locs[i] = std::make_pair(1, NumHi);
9560         if (2+NumHi < 4)
9561           Mask1[2+NumHi] = Idx;
9562         NumHi++;
9563       }
9564     }
9565   }
9566
9567   if (NumLo <= 2 && NumHi <= 2) {
9568     // If no more than two elements come from either vector. This can be
9569     // implemented with two shuffles. First shuffle gather the elements.
9570     // The second shuffle, which takes the first shuffle as both of its
9571     // vector operands, put the elements into the right order.
9572     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9573
9574     int Mask2[] = { -1, -1, -1, -1 };
9575
9576     for (unsigned i = 0; i != 4; ++i)
9577       if (Locs[i].first != -1) {
9578         unsigned Idx = (i < 2) ? 0 : 4;
9579         Idx += Locs[i].first * 2 + Locs[i].second;
9580         Mask2[i] = Idx;
9581       }
9582
9583     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9584   }
9585
9586   if (NumLo == 3 || NumHi == 3) {
9587     // Otherwise, we must have three elements from one vector, call it X, and
9588     // one element from the other, call it Y.  First, use a shufps to build an
9589     // intermediate vector with the one element from Y and the element from X
9590     // that will be in the same half in the final destination (the indexes don't
9591     // matter). Then, use a shufps to build the final vector, taking the half
9592     // containing the element from Y from the intermediate, and the other half
9593     // from X.
9594     if (NumHi == 3) {
9595       // Normalize it so the 3 elements come from V1.
9596       CommuteVectorShuffleMask(PermMask, 4);
9597       std::swap(V1, V2);
9598     }
9599
9600     // Find the element from V2.
9601     unsigned HiIndex;
9602     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9603       int Val = PermMask[HiIndex];
9604       if (Val < 0)
9605         continue;
9606       if (Val >= 4)
9607         break;
9608     }
9609
9610     Mask1[0] = PermMask[HiIndex];
9611     Mask1[1] = -1;
9612     Mask1[2] = PermMask[HiIndex^1];
9613     Mask1[3] = -1;
9614     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9615
9616     if (HiIndex >= 2) {
9617       Mask1[0] = PermMask[0];
9618       Mask1[1] = PermMask[1];
9619       Mask1[2] = HiIndex & 1 ? 6 : 4;
9620       Mask1[3] = HiIndex & 1 ? 4 : 6;
9621       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9622     }
9623
9624     Mask1[0] = HiIndex & 1 ? 2 : 0;
9625     Mask1[1] = HiIndex & 1 ? 0 : 2;
9626     Mask1[2] = PermMask[2];
9627     Mask1[3] = PermMask[3];
9628     if (Mask1[2] >= 0)
9629       Mask1[2] += 4;
9630     if (Mask1[3] >= 0)
9631       Mask1[3] += 4;
9632     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9633   }
9634
9635   // Break it into (shuffle shuffle_hi, shuffle_lo).
9636   int LoMask[] = { -1, -1, -1, -1 };
9637   int HiMask[] = { -1, -1, -1, -1 };
9638
9639   int *MaskPtr = LoMask;
9640   unsigned MaskIdx = 0;
9641   unsigned LoIdx = 0;
9642   unsigned HiIdx = 2;
9643   for (unsigned i = 0; i != 4; ++i) {
9644     if (i == 2) {
9645       MaskPtr = HiMask;
9646       MaskIdx = 1;
9647       LoIdx = 0;
9648       HiIdx = 2;
9649     }
9650     int Idx = PermMask[i];
9651     if (Idx < 0) {
9652       Locs[i] = std::make_pair(-1, -1);
9653     } else if (Idx < 4) {
9654       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9655       MaskPtr[LoIdx] = Idx;
9656       LoIdx++;
9657     } else {
9658       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9659       MaskPtr[HiIdx] = Idx;
9660       HiIdx++;
9661     }
9662   }
9663
9664   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9665   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9666   int MaskOps[] = { -1, -1, -1, -1 };
9667   for (unsigned i = 0; i != 4; ++i)
9668     if (Locs[i].first != -1)
9669       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9670   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9671 }
9672
9673 static bool MayFoldVectorLoad(SDValue V) {
9674   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9675     V = V.getOperand(0);
9676
9677   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9678     V = V.getOperand(0);
9679   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9680       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9681     // BUILD_VECTOR (load), undef
9682     V = V.getOperand(0);
9683
9684   return MayFoldLoad(V);
9685 }
9686
9687 static
9688 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9689   MVT VT = Op.getSimpleValueType();
9690
9691   // Canonizalize to v2f64.
9692   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9693   return DAG.getNode(ISD::BITCAST, dl, VT,
9694                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9695                                           V1, DAG));
9696 }
9697
9698 static
9699 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9700                         bool HasSSE2) {
9701   SDValue V1 = Op.getOperand(0);
9702   SDValue V2 = Op.getOperand(1);
9703   MVT VT = Op.getSimpleValueType();
9704
9705   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9706
9707   if (HasSSE2 && VT == MVT::v2f64)
9708     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9709
9710   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9711   return DAG.getNode(ISD::BITCAST, dl, VT,
9712                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9713                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9714                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9715 }
9716
9717 static
9718 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9719   SDValue V1 = Op.getOperand(0);
9720   SDValue V2 = Op.getOperand(1);
9721   MVT VT = Op.getSimpleValueType();
9722
9723   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9724          "unsupported shuffle type");
9725
9726   if (V2.getOpcode() == ISD::UNDEF)
9727     V2 = V1;
9728
9729   // v4i32 or v4f32
9730   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9731 }
9732
9733 static
9734 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9735   SDValue V1 = Op.getOperand(0);
9736   SDValue V2 = Op.getOperand(1);
9737   MVT VT = Op.getSimpleValueType();
9738   unsigned NumElems = VT.getVectorNumElements();
9739
9740   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9741   // operand of these instructions is only memory, so check if there's a
9742   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9743   // same masks.
9744   bool CanFoldLoad = false;
9745
9746   // Trivial case, when V2 comes from a load.
9747   if (MayFoldVectorLoad(V2))
9748     CanFoldLoad = true;
9749
9750   // When V1 is a load, it can be folded later into a store in isel, example:
9751   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9752   //    turns into:
9753   //  (MOVLPSmr addr:$src1, VR128:$src2)
9754   // So, recognize this potential and also use MOVLPS or MOVLPD
9755   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9756     CanFoldLoad = true;
9757
9758   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9759   if (CanFoldLoad) {
9760     if (HasSSE2 && NumElems == 2)
9761       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9762
9763     if (NumElems == 4)
9764       // If we don't care about the second element, proceed to use movss.
9765       if (SVOp->getMaskElt(1) != -1)
9766         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9767   }
9768
9769   // movl and movlp will both match v2i64, but v2i64 is never matched by
9770   // movl earlier because we make it strict to avoid messing with the movlp load
9771   // folding logic (see the code above getMOVLP call). Match it here then,
9772   // this is horrible, but will stay like this until we move all shuffle
9773   // matching to x86 specific nodes. Note that for the 1st condition all
9774   // types are matched with movsd.
9775   if (HasSSE2) {
9776     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9777     // as to remove this logic from here, as much as possible
9778     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9779       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9780     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9781   }
9782
9783   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9784
9785   // Invert the operand order and use SHUFPS to match it.
9786   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9787                               getShuffleSHUFImmediate(SVOp), DAG);
9788 }
9789
9790 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9791                                          SelectionDAG &DAG) {
9792   SDLoc dl(Load);
9793   MVT VT = Load->getSimpleValueType(0);
9794   MVT EVT = VT.getVectorElementType();
9795   SDValue Addr = Load->getOperand(1);
9796   SDValue NewAddr = DAG.getNode(
9797       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9798       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9799
9800   SDValue NewLoad =
9801       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9802                   DAG.getMachineFunction().getMachineMemOperand(
9803                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9804   return NewLoad;
9805 }
9806
9807 // It is only safe to call this function if isINSERTPSMask is true for
9808 // this shufflevector mask.
9809 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9810                            SelectionDAG &DAG) {
9811   // Generate an insertps instruction when inserting an f32 from memory onto a
9812   // v4f32 or when copying a member from one v4f32 to another.
9813   // We also use it for transferring i32 from one register to another,
9814   // since it simply copies the same bits.
9815   // If we're transferring an i32 from memory to a specific element in a
9816   // register, we output a generic DAG that will match the PINSRD
9817   // instruction.
9818   MVT VT = SVOp->getSimpleValueType(0);
9819   MVT EVT = VT.getVectorElementType();
9820   SDValue V1 = SVOp->getOperand(0);
9821   SDValue V2 = SVOp->getOperand(1);
9822   auto Mask = SVOp->getMask();
9823   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9824          "unsupported vector type for insertps/pinsrd");
9825
9826   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9827   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9828   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9829
9830   SDValue From;
9831   SDValue To;
9832   unsigned DestIndex;
9833   if (FromV1 == 1) {
9834     From = V1;
9835     To = V2;
9836     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9837                 Mask.begin();
9838
9839     // If we have 1 element from each vector, we have to check if we're
9840     // changing V1's element's place. If so, we're done. Otherwise, we
9841     // should assume we're changing V2's element's place and behave
9842     // accordingly.
9843     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9844     assert(DestIndex <= INT32_MAX && "truncated destination index");
9845     if (FromV1 == FromV2 &&
9846         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9847       From = V2;
9848       To = V1;
9849       DestIndex =
9850           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9851     }
9852   } else {
9853     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9854            "More than one element from V1 and from V2, or no elements from one "
9855            "of the vectors. This case should not have returned true from "
9856            "isINSERTPSMask");
9857     From = V2;
9858     To = V1;
9859     DestIndex =
9860         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9861   }
9862
9863   // Get an index into the source vector in the range [0,4) (the mask is
9864   // in the range [0,8) because it can address V1 and V2)
9865   unsigned SrcIndex = Mask[DestIndex] % 4;
9866   if (MayFoldLoad(From)) {
9867     // Trivial case, when From comes from a load and is only used by the
9868     // shuffle. Make it use insertps from the vector that we need from that
9869     // load.
9870     SDValue NewLoad =
9871         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9872     if (!NewLoad.getNode())
9873       return SDValue();
9874
9875     if (EVT == MVT::f32) {
9876       // Create this as a scalar to vector to match the instruction pattern.
9877       SDValue LoadScalarToVector =
9878           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9879       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9880       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9881                          InsertpsMask);
9882     } else { // EVT == MVT::i32
9883       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9884       // instruction, to match the PINSRD instruction, which loads an i32 to a
9885       // certain vector element.
9886       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9887                          DAG.getConstant(DestIndex, MVT::i32));
9888     }
9889   }
9890
9891   // Vector-element-to-vector
9892   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9893   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9894 }
9895
9896 // Reduce a vector shuffle to zext.
9897 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9898                                     SelectionDAG &DAG) {
9899   // PMOVZX is only available from SSE41.
9900   if (!Subtarget->hasSSE41())
9901     return SDValue();
9902
9903   MVT VT = Op.getSimpleValueType();
9904
9905   // Only AVX2 support 256-bit vector integer extending.
9906   if (!Subtarget->hasInt256() && VT.is256BitVector())
9907     return SDValue();
9908
9909   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9910   SDLoc DL(Op);
9911   SDValue V1 = Op.getOperand(0);
9912   SDValue V2 = Op.getOperand(1);
9913   unsigned NumElems = VT.getVectorNumElements();
9914
9915   // Extending is an unary operation and the element type of the source vector
9916   // won't be equal to or larger than i64.
9917   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9918       VT.getVectorElementType() == MVT::i64)
9919     return SDValue();
9920
9921   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9922   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9923   while ((1U << Shift) < NumElems) {
9924     if (SVOp->getMaskElt(1U << Shift) == 1)
9925       break;
9926     Shift += 1;
9927     // The maximal ratio is 8, i.e. from i8 to i64.
9928     if (Shift > 3)
9929       return SDValue();
9930   }
9931
9932   // Check the shuffle mask.
9933   unsigned Mask = (1U << Shift) - 1;
9934   for (unsigned i = 0; i != NumElems; ++i) {
9935     int EltIdx = SVOp->getMaskElt(i);
9936     if ((i & Mask) != 0 && EltIdx != -1)
9937       return SDValue();
9938     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9939       return SDValue();
9940   }
9941
9942   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9943   MVT NeVT = MVT::getIntegerVT(NBits);
9944   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9945
9946   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9947     return SDValue();
9948
9949   // Simplify the operand as it's prepared to be fed into shuffle.
9950   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9951   if (V1.getOpcode() == ISD::BITCAST &&
9952       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9953       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9954       V1.getOperand(0).getOperand(0)
9955         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9956     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9957     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9958     ConstantSDNode *CIdx =
9959       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9960     // If it's foldable, i.e. normal load with single use, we will let code
9961     // selection to fold it. Otherwise, we will short the conversion sequence.
9962     if (CIdx && CIdx->getZExtValue() == 0 &&
9963         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9964       MVT FullVT = V.getSimpleValueType();
9965       MVT V1VT = V1.getSimpleValueType();
9966       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9967         // The "ext_vec_elt" node is wider than the result node.
9968         // In this case we should extract subvector from V.
9969         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9970         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9971         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9972                                         FullVT.getVectorNumElements()/Ratio);
9973         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9974                         DAG.getIntPtrConstant(0));
9975       }
9976       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9977     }
9978   }
9979
9980   return DAG.getNode(ISD::BITCAST, DL, VT,
9981                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9982 }
9983
9984 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9985                                       SelectionDAG &DAG) {
9986   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9987   MVT VT = Op.getSimpleValueType();
9988   SDLoc dl(Op);
9989   SDValue V1 = Op.getOperand(0);
9990   SDValue V2 = Op.getOperand(1);
9991
9992   if (isZeroShuffle(SVOp))
9993     return getZeroVector(VT, Subtarget, DAG, dl);
9994
9995   // Handle splat operations
9996   if (SVOp->isSplat()) {
9997     // Use vbroadcast whenever the splat comes from a foldable load
9998     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9999     if (Broadcast.getNode())
10000       return Broadcast;
10001   }
10002
10003   // Check integer expanding shuffles.
10004   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
10005   if (NewOp.getNode())
10006     return NewOp;
10007
10008   // If the shuffle can be profitably rewritten as a narrower shuffle, then
10009   // do it!
10010   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
10011       VT == MVT::v32i8) {
10012     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10013     if (NewOp.getNode())
10014       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
10015   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
10016     // FIXME: Figure out a cleaner way to do this.
10017     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
10018       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10019       if (NewOp.getNode()) {
10020         MVT NewVT = NewOp.getSimpleValueType();
10021         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
10022                                NewVT, true, false))
10023           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
10024                               dl);
10025       }
10026     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
10027       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10028       if (NewOp.getNode()) {
10029         MVT NewVT = NewOp.getSimpleValueType();
10030         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
10031           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
10032                               dl);
10033       }
10034     }
10035   }
10036   return SDValue();
10037 }
10038
10039 SDValue
10040 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
10041   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10042   SDValue V1 = Op.getOperand(0);
10043   SDValue V2 = Op.getOperand(1);
10044   MVT VT = Op.getSimpleValueType();
10045   SDLoc dl(Op);
10046   unsigned NumElems = VT.getVectorNumElements();
10047   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10048   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10049   bool V1IsSplat = false;
10050   bool V2IsSplat = false;
10051   bool HasSSE2 = Subtarget->hasSSE2();
10052   bool HasFp256    = Subtarget->hasFp256();
10053   bool HasInt256   = Subtarget->hasInt256();
10054   MachineFunction &MF = DAG.getMachineFunction();
10055   bool OptForSize = MF.getFunction()->getAttributes().
10056     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10057
10058   // Check if we should use the experimental vector shuffle lowering. If so,
10059   // delegate completely to that code path.
10060   if (ExperimentalVectorShuffleLowering)
10061     return lowerVectorShuffle(Op, Subtarget, DAG);
10062
10063   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10064
10065   if (V1IsUndef && V2IsUndef)
10066     return DAG.getUNDEF(VT);
10067
10068   // When we create a shuffle node we put the UNDEF node to second operand,
10069   // but in some cases the first operand may be transformed to UNDEF.
10070   // In this case we should just commute the node.
10071   if (V1IsUndef)
10072     return DAG.getCommutedVectorShuffle(*SVOp);
10073
10074   // Vector shuffle lowering takes 3 steps:
10075   //
10076   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10077   //    narrowing and commutation of operands should be handled.
10078   // 2) Matching of shuffles with known shuffle masks to x86 target specific
10079   //    shuffle nodes.
10080   // 3) Rewriting of unmatched masks into new generic shuffle operations,
10081   //    so the shuffle can be broken into other shuffles and the legalizer can
10082   //    try the lowering again.
10083   //
10084   // The general idea is that no vector_shuffle operation should be left to
10085   // be matched during isel, all of them must be converted to a target specific
10086   // node here.
10087
10088   // Normalize the input vectors. Here splats, zeroed vectors, profitable
10089   // narrowing and commutation of operands should be handled. The actual code
10090   // doesn't include all of those, work in progress...
10091   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10092   if (NewOp.getNode())
10093     return NewOp;
10094
10095   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10096
10097   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10098   // unpckh_undef). Only use pshufd if speed is more important than size.
10099   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10100     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10101   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10102     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10103
10104   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10105       V2IsUndef && MayFoldVectorLoad(V1))
10106     return getMOVDDup(Op, dl, V1, DAG);
10107
10108   if (isMOVHLPS_v_undef_Mask(M, VT))
10109     return getMOVHighToLow(Op, dl, DAG);
10110
10111   // Use to match splats
10112   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10113       (VT == MVT::v2f64 || VT == MVT::v2i64))
10114     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10115
10116   if (isPSHUFDMask(M, VT)) {
10117     // The actual implementation will match the mask in the if above and then
10118     // during isel it can match several different instructions, not only pshufd
10119     // as its name says, sad but true, emulate the behavior for now...
10120     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10121       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10122
10123     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10124
10125     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10126       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10127
10128     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10129       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10130                                   DAG);
10131
10132     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10133                                 TargetMask, DAG);
10134   }
10135
10136   if (isPALIGNRMask(M, VT, Subtarget))
10137     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10138                                 getShufflePALIGNRImmediate(SVOp),
10139                                 DAG);
10140
10141   if (isVALIGNMask(M, VT, Subtarget))
10142     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10143                                 getShuffleVALIGNImmediate(SVOp),
10144                                 DAG);
10145
10146   // Check if this can be converted into a logical shift.
10147   bool isLeft = false;
10148   unsigned ShAmt = 0;
10149   SDValue ShVal;
10150   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10151   if (isShift && ShVal.hasOneUse()) {
10152     // If the shifted value has multiple uses, it may be cheaper to use
10153     // v_set0 + movlhps or movhlps, etc.
10154     MVT EltVT = VT.getVectorElementType();
10155     ShAmt *= EltVT.getSizeInBits();
10156     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10157   }
10158
10159   if (isMOVLMask(M, VT)) {
10160     if (ISD::isBuildVectorAllZeros(V1.getNode()))
10161       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10162     if (!isMOVLPMask(M, VT)) {
10163       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10164         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10165
10166       if (VT == MVT::v4i32 || VT == MVT::v4f32)
10167         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10168     }
10169   }
10170
10171   // FIXME: fold these into legal mask.
10172   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10173     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10174
10175   if (isMOVHLPSMask(M, VT))
10176     return getMOVHighToLow(Op, dl, DAG);
10177
10178   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10179     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10180
10181   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10182     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10183
10184   if (isMOVLPMask(M, VT))
10185     return getMOVLP(Op, dl, DAG, HasSSE2);
10186
10187   if (ShouldXformToMOVHLPS(M, VT) ||
10188       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10189     return DAG.getCommutedVectorShuffle(*SVOp);
10190
10191   if (isShift) {
10192     // No better options. Use a vshldq / vsrldq.
10193     MVT EltVT = VT.getVectorElementType();
10194     ShAmt *= EltVT.getSizeInBits();
10195     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10196   }
10197
10198   bool Commuted = false;
10199   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
10200   // 1,1,1,1 -> v8i16 though.
10201   BitVector UndefElements;
10202   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10203     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10204       V1IsSplat = true;
10205   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10206     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10207       V2IsSplat = true;
10208
10209   // Canonicalize the splat or undef, if present, to be on the RHS.
10210   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10211     CommuteVectorShuffleMask(M, NumElems);
10212     std::swap(V1, V2);
10213     std::swap(V1IsSplat, V2IsSplat);
10214     Commuted = true;
10215   }
10216
10217   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10218     // Shuffling low element of v1 into undef, just return v1.
10219     if (V2IsUndef)
10220       return V1;
10221     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10222     // the instruction selector will not match, so get a canonical MOVL with
10223     // swapped operands to undo the commute.
10224     return getMOVL(DAG, dl, VT, V2, V1);
10225   }
10226
10227   if (isUNPCKLMask(M, VT, HasInt256))
10228     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10229
10230   if (isUNPCKHMask(M, VT, HasInt256))
10231     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10232
10233   if (V2IsSplat) {
10234     // Normalize mask so all entries that point to V2 points to its first
10235     // element then try to match unpck{h|l} again. If match, return a
10236     // new vector_shuffle with the corrected mask.p
10237     SmallVector<int, 8> NewMask(M.begin(), M.end());
10238     NormalizeMask(NewMask, NumElems);
10239     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10240       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10241     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10242       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10243   }
10244
10245   if (Commuted) {
10246     // Commute is back and try unpck* again.
10247     // FIXME: this seems wrong.
10248     CommuteVectorShuffleMask(M, NumElems);
10249     std::swap(V1, V2);
10250     std::swap(V1IsSplat, V2IsSplat);
10251
10252     if (isUNPCKLMask(M, VT, HasInt256))
10253       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10254
10255     if (isUNPCKHMask(M, VT, HasInt256))
10256       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10257   }
10258
10259   // Normalize the node to match x86 shuffle ops if needed
10260   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10261     return DAG.getCommutedVectorShuffle(*SVOp);
10262
10263   // The checks below are all present in isShuffleMaskLegal, but they are
10264   // inlined here right now to enable us to directly emit target specific
10265   // nodes, and remove one by one until they don't return Op anymore.
10266
10267   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10268       SVOp->getSplatIndex() == 0 && V2IsUndef) {
10269     if (VT == MVT::v2f64 || VT == MVT::v2i64)
10270       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10271   }
10272
10273   if (isPSHUFHWMask(M, VT, HasInt256))
10274     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10275                                 getShufflePSHUFHWImmediate(SVOp),
10276                                 DAG);
10277
10278   if (isPSHUFLWMask(M, VT, HasInt256))
10279     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10280                                 getShufflePSHUFLWImmediate(SVOp),
10281                                 DAG);
10282
10283   unsigned MaskValue;
10284   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10285                   &MaskValue))
10286     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10287
10288   if (isSHUFPMask(M, VT))
10289     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10290                                 getShuffleSHUFImmediate(SVOp), DAG);
10291
10292   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10293     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10294   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10295     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10296
10297   //===--------------------------------------------------------------------===//
10298   // Generate target specific nodes for 128 or 256-bit shuffles only
10299   // supported in the AVX instruction set.
10300   //
10301
10302   // Handle VMOVDDUPY permutations
10303   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10304     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10305
10306   // Handle VPERMILPS/D* permutations
10307   if (isVPERMILPMask(M, VT)) {
10308     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10309       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10310                                   getShuffleSHUFImmediate(SVOp), DAG);
10311     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10312                                 getShuffleSHUFImmediate(SVOp), DAG);
10313   }
10314
10315   unsigned Idx;
10316   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10317     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10318                               Idx*(NumElems/2), DAG, dl);
10319
10320   // Handle VPERM2F128/VPERM2I128 permutations
10321   if (isVPERM2X128Mask(M, VT, HasFp256))
10322     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10323                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10324
10325   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10326     return getINSERTPS(SVOp, dl, DAG);
10327
10328   unsigned Imm8;
10329   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10330     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10331
10332   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10333       VT.is512BitVector()) {
10334     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10335     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10336     SmallVector<SDValue, 16> permclMask;
10337     for (unsigned i = 0; i != NumElems; ++i) {
10338       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10339     }
10340
10341     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10342     if (V2IsUndef)
10343       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10344       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10345                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10346     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10347                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10348   }
10349
10350   //===--------------------------------------------------------------------===//
10351   // Since no target specific shuffle was selected for this generic one,
10352   // lower it into other known shuffles. FIXME: this isn't true yet, but
10353   // this is the plan.
10354   //
10355
10356   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10357   if (VT == MVT::v8i16) {
10358     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10359     if (NewOp.getNode())
10360       return NewOp;
10361   }
10362
10363   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10364     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10365     if (NewOp.getNode())
10366       return NewOp;
10367   }
10368
10369   if (VT == MVT::v16i8) {
10370     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10371     if (NewOp.getNode())
10372       return NewOp;
10373   }
10374
10375   if (VT == MVT::v32i8) {
10376     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10377     if (NewOp.getNode())
10378       return NewOp;
10379   }
10380
10381   // Handle all 128-bit wide vectors with 4 elements, and match them with
10382   // several different shuffle types.
10383   if (NumElems == 4 && VT.is128BitVector())
10384     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10385
10386   // Handle general 256-bit shuffles
10387   if (VT.is256BitVector())
10388     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10389
10390   return SDValue();
10391 }
10392
10393 // This function assumes its argument is a BUILD_VECTOR of constants or
10394 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10395 // true.
10396 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10397                                     unsigned &MaskValue) {
10398   MaskValue = 0;
10399   unsigned NumElems = BuildVector->getNumOperands();
10400   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10401   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10402   unsigned NumElemsInLane = NumElems / NumLanes;
10403
10404   // Blend for v16i16 should be symetric for the both lanes.
10405   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10406     SDValue EltCond = BuildVector->getOperand(i);
10407     SDValue SndLaneEltCond =
10408         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10409
10410     int Lane1Cond = -1, Lane2Cond = -1;
10411     if (isa<ConstantSDNode>(EltCond))
10412       Lane1Cond = !isZero(EltCond);
10413     if (isa<ConstantSDNode>(SndLaneEltCond))
10414       Lane2Cond = !isZero(SndLaneEltCond);
10415
10416     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10417       // Lane1Cond != 0, means we want the first argument.
10418       // Lane1Cond == 0, means we want the second argument.
10419       // The encoding of this argument is 0 for the first argument, 1
10420       // for the second. Therefore, invert the condition.
10421       MaskValue |= !Lane1Cond << i;
10422     else if (Lane1Cond < 0)
10423       MaskValue |= !Lane2Cond << i;
10424     else
10425       return false;
10426   }
10427   return true;
10428 }
10429
10430 // Try to lower a vselect node into a simple blend instruction.
10431 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10432                                    SelectionDAG &DAG) {
10433   SDValue Cond = Op.getOperand(0);
10434   SDValue LHS = Op.getOperand(1);
10435   SDValue RHS = Op.getOperand(2);
10436   SDLoc dl(Op);
10437   MVT VT = Op.getSimpleValueType();
10438   MVT EltVT = VT.getVectorElementType();
10439   unsigned NumElems = VT.getVectorNumElements();
10440
10441   // There is no blend with immediate in AVX-512.
10442   if (VT.is512BitVector())
10443     return SDValue();
10444
10445   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10446     return SDValue();
10447   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10448     return SDValue();
10449
10450   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10451     return SDValue();
10452
10453   // Check the mask for BLEND and build the value.
10454   unsigned MaskValue = 0;
10455   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10456     return SDValue();
10457
10458   // Convert i32 vectors to floating point if it is not AVX2.
10459   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10460   MVT BlendVT = VT;
10461   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10462     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10463                                NumElems);
10464     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10465     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10466   }
10467
10468   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10469                             DAG.getConstant(MaskValue, MVT::i32));
10470   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10471 }
10472
10473 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10474   // A vselect where all conditions and data are constants can be optimized into
10475   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10476   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10477       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10478       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10479     return SDValue();
10480   
10481   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10482   if (BlendOp.getNode())
10483     return BlendOp;
10484
10485   // Some types for vselect were previously set to Expand, not Legal or
10486   // Custom. Return an empty SDValue so we fall-through to Expand, after
10487   // the Custom lowering phase.
10488   MVT VT = Op.getSimpleValueType();
10489   switch (VT.SimpleTy) {
10490   default:
10491     break;
10492   case MVT::v8i16:
10493   case MVT::v16i16:
10494     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10495       break;
10496     return SDValue();
10497   }
10498
10499   // We couldn't create a "Blend with immediate" node.
10500   // This node should still be legal, but we'll have to emit a blendv*
10501   // instruction.
10502   return Op;
10503 }
10504
10505 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10506   MVT VT = Op.getSimpleValueType();
10507   SDLoc dl(Op);
10508
10509   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10510     return SDValue();
10511
10512   if (VT.getSizeInBits() == 8) {
10513     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10514                                   Op.getOperand(0), Op.getOperand(1));
10515     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10516                                   DAG.getValueType(VT));
10517     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10518   }
10519
10520   if (VT.getSizeInBits() == 16) {
10521     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10522     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10523     if (Idx == 0)
10524       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10525                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10526                                      DAG.getNode(ISD::BITCAST, dl,
10527                                                  MVT::v4i32,
10528                                                  Op.getOperand(0)),
10529                                      Op.getOperand(1)));
10530     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10531                                   Op.getOperand(0), Op.getOperand(1));
10532     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10533                                   DAG.getValueType(VT));
10534     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10535   }
10536
10537   if (VT == MVT::f32) {
10538     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10539     // the result back to FR32 register. It's only worth matching if the
10540     // result has a single use which is a store or a bitcast to i32.  And in
10541     // the case of a store, it's not worth it if the index is a constant 0,
10542     // because a MOVSSmr can be used instead, which is smaller and faster.
10543     if (!Op.hasOneUse())
10544       return SDValue();
10545     SDNode *User = *Op.getNode()->use_begin();
10546     if ((User->getOpcode() != ISD::STORE ||
10547          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10548           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10549         (User->getOpcode() != ISD::BITCAST ||
10550          User->getValueType(0) != MVT::i32))
10551       return SDValue();
10552     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10553                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10554                                               Op.getOperand(0)),
10555                                               Op.getOperand(1));
10556     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10557   }
10558
10559   if (VT == MVT::i32 || VT == MVT::i64) {
10560     // ExtractPS/pextrq works with constant index.
10561     if (isa<ConstantSDNode>(Op.getOperand(1)))
10562       return Op;
10563   }
10564   return SDValue();
10565 }
10566
10567 /// Extract one bit from mask vector, like v16i1 or v8i1.
10568 /// AVX-512 feature.
10569 SDValue
10570 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10571   SDValue Vec = Op.getOperand(0);
10572   SDLoc dl(Vec);
10573   MVT VecVT = Vec.getSimpleValueType();
10574   SDValue Idx = Op.getOperand(1);
10575   MVT EltVT = Op.getSimpleValueType();
10576
10577   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10578
10579   // variable index can't be handled in mask registers,
10580   // extend vector to VR512
10581   if (!isa<ConstantSDNode>(Idx)) {
10582     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10583     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10584     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10585                               ExtVT.getVectorElementType(), Ext, Idx);
10586     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10587   }
10588
10589   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10590   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10591   unsigned MaxSift = rc->getSize()*8 - 1;
10592   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10593                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10594   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10595                     DAG.getConstant(MaxSift, MVT::i8));
10596   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10597                        DAG.getIntPtrConstant(0));
10598 }
10599
10600 SDValue
10601 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10602                                            SelectionDAG &DAG) const {
10603   SDLoc dl(Op);
10604   SDValue Vec = Op.getOperand(0);
10605   MVT VecVT = Vec.getSimpleValueType();
10606   SDValue Idx = Op.getOperand(1);
10607
10608   if (Op.getSimpleValueType() == MVT::i1)
10609     return ExtractBitFromMaskVector(Op, DAG);
10610
10611   if (!isa<ConstantSDNode>(Idx)) {
10612     if (VecVT.is512BitVector() ||
10613         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10614          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10615
10616       MVT MaskEltVT =
10617         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10618       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10619                                     MaskEltVT.getSizeInBits());
10620
10621       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10622       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10623                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10624                                 Idx, DAG.getConstant(0, getPointerTy()));
10625       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10626       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10627                         Perm, DAG.getConstant(0, getPointerTy()));
10628     }
10629     return SDValue();
10630   }
10631
10632   // If this is a 256-bit vector result, first extract the 128-bit vector and
10633   // then extract the element from the 128-bit vector.
10634   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10635
10636     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10637     // Get the 128-bit vector.
10638     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10639     MVT EltVT = VecVT.getVectorElementType();
10640
10641     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10642
10643     //if (IdxVal >= NumElems/2)
10644     //  IdxVal -= NumElems/2;
10645     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10646     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10647                        DAG.getConstant(IdxVal, MVT::i32));
10648   }
10649
10650   assert(VecVT.is128BitVector() && "Unexpected vector length");
10651
10652   if (Subtarget->hasSSE41()) {
10653     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10654     if (Res.getNode())
10655       return Res;
10656   }
10657
10658   MVT VT = Op.getSimpleValueType();
10659   // TODO: handle v16i8.
10660   if (VT.getSizeInBits() == 16) {
10661     SDValue Vec = Op.getOperand(0);
10662     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10663     if (Idx == 0)
10664       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10665                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10666                                      DAG.getNode(ISD::BITCAST, dl,
10667                                                  MVT::v4i32, Vec),
10668                                      Op.getOperand(1)));
10669     // Transform it so it match pextrw which produces a 32-bit result.
10670     MVT EltVT = MVT::i32;
10671     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10672                                   Op.getOperand(0), Op.getOperand(1));
10673     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10674                                   DAG.getValueType(VT));
10675     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10676   }
10677
10678   if (VT.getSizeInBits() == 32) {
10679     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10680     if (Idx == 0)
10681       return Op;
10682
10683     // SHUFPS the element to the lowest double word, then movss.
10684     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10685     MVT VVT = Op.getOperand(0).getSimpleValueType();
10686     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10687                                        DAG.getUNDEF(VVT), Mask);
10688     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10689                        DAG.getIntPtrConstant(0));
10690   }
10691
10692   if (VT.getSizeInBits() == 64) {
10693     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10694     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10695     //        to match extract_elt for f64.
10696     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10697     if (Idx == 0)
10698       return Op;
10699
10700     // UNPCKHPD the element to the lowest double word, then movsd.
10701     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10702     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10703     int Mask[2] = { 1, -1 };
10704     MVT VVT = Op.getOperand(0).getSimpleValueType();
10705     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10706                                        DAG.getUNDEF(VVT), Mask);
10707     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10708                        DAG.getIntPtrConstant(0));
10709   }
10710
10711   return SDValue();
10712 }
10713
10714 /// Insert one bit to mask vector, like v16i1 or v8i1.
10715 /// AVX-512 feature.
10716 SDValue 
10717 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10718   SDLoc dl(Op);
10719   SDValue Vec = Op.getOperand(0);
10720   SDValue Elt = Op.getOperand(1);
10721   SDValue Idx = Op.getOperand(2);
10722   MVT VecVT = Vec.getSimpleValueType();
10723
10724   if (!isa<ConstantSDNode>(Idx)) {
10725     // Non constant index. Extend source and destination,
10726     // insert element and then truncate the result.
10727     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10728     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10729     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10730       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10731       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10732     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10733   }
10734
10735   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10736   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10737   if (Vec.getOpcode() == ISD::UNDEF)
10738     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10739                        DAG.getConstant(IdxVal, MVT::i8));
10740   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10741   unsigned MaxSift = rc->getSize()*8 - 1;
10742   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10743                     DAG.getConstant(MaxSift, MVT::i8));
10744   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10745                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10746   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10747 }
10748
10749 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10750                                                   SelectionDAG &DAG) const {
10751   MVT VT = Op.getSimpleValueType();
10752   MVT EltVT = VT.getVectorElementType();
10753
10754   if (EltVT == MVT::i1)
10755     return InsertBitToMaskVector(Op, DAG);
10756
10757   SDLoc dl(Op);
10758   SDValue N0 = Op.getOperand(0);
10759   SDValue N1 = Op.getOperand(1);
10760   SDValue N2 = Op.getOperand(2);
10761   if (!isa<ConstantSDNode>(N2))
10762     return SDValue();
10763   auto *N2C = cast<ConstantSDNode>(N2);
10764   unsigned IdxVal = N2C->getZExtValue();
10765
10766   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10767   // into that, and then insert the subvector back into the result.
10768   if (VT.is256BitVector() || VT.is512BitVector()) {
10769     // Get the desired 128-bit vector half.
10770     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10771
10772     // Insert the element into the desired half.
10773     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10774     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10775
10776     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10777                     DAG.getConstant(IdxIn128, MVT::i32));
10778
10779     // Insert the changed part back to the 256-bit vector
10780     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10781   }
10782   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10783
10784   if (Subtarget->hasSSE41()) {
10785     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10786       unsigned Opc;
10787       if (VT == MVT::v8i16) {
10788         Opc = X86ISD::PINSRW;
10789       } else {
10790         assert(VT == MVT::v16i8);
10791         Opc = X86ISD::PINSRB;
10792       }
10793
10794       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10795       // argument.
10796       if (N1.getValueType() != MVT::i32)
10797         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10798       if (N2.getValueType() != MVT::i32)
10799         N2 = DAG.getIntPtrConstant(IdxVal);
10800       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10801     }
10802
10803     if (EltVT == MVT::f32) {
10804       // Bits [7:6] of the constant are the source select.  This will always be
10805       //  zero here.  The DAG Combiner may combine an extract_elt index into
10806       //  these
10807       //  bits.  For example (insert (extract, 3), 2) could be matched by
10808       //  putting
10809       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10810       // Bits [5:4] of the constant are the destination select.  This is the
10811       //  value of the incoming immediate.
10812       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10813       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10814       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10815       // Create this as a scalar to vector..
10816       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10817       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10818     }
10819
10820     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10821       // PINSR* works with constant index.
10822       return Op;
10823     }
10824   }
10825
10826   if (EltVT == MVT::i8)
10827     return SDValue();
10828
10829   if (EltVT.getSizeInBits() == 16) {
10830     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10831     // as its second argument.
10832     if (N1.getValueType() != MVT::i32)
10833       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10834     if (N2.getValueType() != MVT::i32)
10835       N2 = DAG.getIntPtrConstant(IdxVal);
10836     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10837   }
10838   return SDValue();
10839 }
10840
10841 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10842   SDLoc dl(Op);
10843   MVT OpVT = Op.getSimpleValueType();
10844
10845   // If this is a 256-bit vector result, first insert into a 128-bit
10846   // vector and then insert into the 256-bit vector.
10847   if (!OpVT.is128BitVector()) {
10848     // Insert into a 128-bit vector.
10849     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10850     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10851                                  OpVT.getVectorNumElements() / SizeFactor);
10852
10853     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10854
10855     // Insert the 128-bit vector.
10856     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10857   }
10858
10859   if (OpVT == MVT::v1i64 &&
10860       Op.getOperand(0).getValueType() == MVT::i64)
10861     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10862
10863   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10864   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10865   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10866                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10867 }
10868
10869 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10870 // a simple subregister reference or explicit instructions to grab
10871 // upper bits of a vector.
10872 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10873                                       SelectionDAG &DAG) {
10874   SDLoc dl(Op);
10875   SDValue In =  Op.getOperand(0);
10876   SDValue Idx = Op.getOperand(1);
10877   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10878   MVT ResVT   = Op.getSimpleValueType();
10879   MVT InVT    = In.getSimpleValueType();
10880
10881   if (Subtarget->hasFp256()) {
10882     if (ResVT.is128BitVector() &&
10883         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10884         isa<ConstantSDNode>(Idx)) {
10885       return Extract128BitVector(In, IdxVal, DAG, dl);
10886     }
10887     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10888         isa<ConstantSDNode>(Idx)) {
10889       return Extract256BitVector(In, IdxVal, DAG, dl);
10890     }
10891   }
10892   return SDValue();
10893 }
10894
10895 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10896 // simple superregister reference or explicit instructions to insert
10897 // the upper bits of a vector.
10898 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10899                                      SelectionDAG &DAG) {
10900   if (Subtarget->hasFp256()) {
10901     SDLoc dl(Op.getNode());
10902     SDValue Vec = Op.getNode()->getOperand(0);
10903     SDValue SubVec = Op.getNode()->getOperand(1);
10904     SDValue Idx = Op.getNode()->getOperand(2);
10905
10906     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10907          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10908         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10909         isa<ConstantSDNode>(Idx)) {
10910       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10911       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10912     }
10913
10914     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10915         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10916         isa<ConstantSDNode>(Idx)) {
10917       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10918       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10919     }
10920   }
10921   return SDValue();
10922 }
10923
10924 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10925 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10926 // one of the above mentioned nodes. It has to be wrapped because otherwise
10927 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10928 // be used to form addressing mode. These wrapped nodes will be selected
10929 // into MOV32ri.
10930 SDValue
10931 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10932   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10933
10934   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10935   // global base reg.
10936   unsigned char OpFlag = 0;
10937   unsigned WrapperKind = X86ISD::Wrapper;
10938   CodeModel::Model M = DAG.getTarget().getCodeModel();
10939
10940   if (Subtarget->isPICStyleRIPRel() &&
10941       (M == CodeModel::Small || M == CodeModel::Kernel))
10942     WrapperKind = X86ISD::WrapperRIP;
10943   else if (Subtarget->isPICStyleGOT())
10944     OpFlag = X86II::MO_GOTOFF;
10945   else if (Subtarget->isPICStyleStubPIC())
10946     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10947
10948   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10949                                              CP->getAlignment(),
10950                                              CP->getOffset(), OpFlag);
10951   SDLoc DL(CP);
10952   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10953   // With PIC, the address is actually $g + Offset.
10954   if (OpFlag) {
10955     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10956                          DAG.getNode(X86ISD::GlobalBaseReg,
10957                                      SDLoc(), getPointerTy()),
10958                          Result);
10959   }
10960
10961   return Result;
10962 }
10963
10964 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10965   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10966
10967   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10968   // global base reg.
10969   unsigned char OpFlag = 0;
10970   unsigned WrapperKind = X86ISD::Wrapper;
10971   CodeModel::Model M = DAG.getTarget().getCodeModel();
10972
10973   if (Subtarget->isPICStyleRIPRel() &&
10974       (M == CodeModel::Small || M == CodeModel::Kernel))
10975     WrapperKind = X86ISD::WrapperRIP;
10976   else if (Subtarget->isPICStyleGOT())
10977     OpFlag = X86II::MO_GOTOFF;
10978   else if (Subtarget->isPICStyleStubPIC())
10979     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10980
10981   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10982                                           OpFlag);
10983   SDLoc DL(JT);
10984   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10985
10986   // With PIC, the address is actually $g + Offset.
10987   if (OpFlag)
10988     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10989                          DAG.getNode(X86ISD::GlobalBaseReg,
10990                                      SDLoc(), getPointerTy()),
10991                          Result);
10992
10993   return Result;
10994 }
10995
10996 SDValue
10997 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10998   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10999
11000   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11001   // global base reg.
11002   unsigned char OpFlag = 0;
11003   unsigned WrapperKind = X86ISD::Wrapper;
11004   CodeModel::Model M = DAG.getTarget().getCodeModel();
11005
11006   if (Subtarget->isPICStyleRIPRel() &&
11007       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11008     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11009       OpFlag = X86II::MO_GOTPCREL;
11010     WrapperKind = X86ISD::WrapperRIP;
11011   } else if (Subtarget->isPICStyleGOT()) {
11012     OpFlag = X86II::MO_GOT;
11013   } else if (Subtarget->isPICStyleStubPIC()) {
11014     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11015   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11016     OpFlag = X86II::MO_DARWIN_NONLAZY;
11017   }
11018
11019   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11020
11021   SDLoc DL(Op);
11022   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11023
11024   // With PIC, the address is actually $g + Offset.
11025   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11026       !Subtarget->is64Bit()) {
11027     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11028                          DAG.getNode(X86ISD::GlobalBaseReg,
11029                                      SDLoc(), getPointerTy()),
11030                          Result);
11031   }
11032
11033   // For symbols that require a load from a stub to get the address, emit the
11034   // load.
11035   if (isGlobalStubReference(OpFlag))
11036     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11037                          MachinePointerInfo::getGOT(), false, false, false, 0);
11038
11039   return Result;
11040 }
11041
11042 SDValue
11043 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11044   // Create the TargetBlockAddressAddress node.
11045   unsigned char OpFlags =
11046     Subtarget->ClassifyBlockAddressReference();
11047   CodeModel::Model M = DAG.getTarget().getCodeModel();
11048   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11049   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11050   SDLoc dl(Op);
11051   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11052                                              OpFlags);
11053
11054   if (Subtarget->isPICStyleRIPRel() &&
11055       (M == CodeModel::Small || M == CodeModel::Kernel))
11056     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11057   else
11058     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11059
11060   // With PIC, the address is actually $g + Offset.
11061   if (isGlobalRelativeToPICBase(OpFlags)) {
11062     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11063                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11064                          Result);
11065   }
11066
11067   return Result;
11068 }
11069
11070 SDValue
11071 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11072                                       int64_t Offset, SelectionDAG &DAG) const {
11073   // Create the TargetGlobalAddress node, folding in the constant
11074   // offset if it is legal.
11075   unsigned char OpFlags =
11076       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11077   CodeModel::Model M = DAG.getTarget().getCodeModel();
11078   SDValue Result;
11079   if (OpFlags == X86II::MO_NO_FLAG &&
11080       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11081     // A direct static reference to a global.
11082     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11083     Offset = 0;
11084   } else {
11085     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11086   }
11087
11088   if (Subtarget->isPICStyleRIPRel() &&
11089       (M == CodeModel::Small || M == CodeModel::Kernel))
11090     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11091   else
11092     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11093
11094   // With PIC, the address is actually $g + Offset.
11095   if (isGlobalRelativeToPICBase(OpFlags)) {
11096     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11097                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11098                          Result);
11099   }
11100
11101   // For globals that require a load from a stub to get the address, emit the
11102   // load.
11103   if (isGlobalStubReference(OpFlags))
11104     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11105                          MachinePointerInfo::getGOT(), false, false, false, 0);
11106
11107   // If there was a non-zero offset that we didn't fold, create an explicit
11108   // addition for it.
11109   if (Offset != 0)
11110     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11111                          DAG.getConstant(Offset, getPointerTy()));
11112
11113   return Result;
11114 }
11115
11116 SDValue
11117 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11118   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11119   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11120   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11121 }
11122
11123 static SDValue
11124 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11125            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11126            unsigned char OperandFlags, bool LocalDynamic = false) {
11127   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11128   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11129   SDLoc dl(GA);
11130   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11131                                            GA->getValueType(0),
11132                                            GA->getOffset(),
11133                                            OperandFlags);
11134
11135   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11136                                            : X86ISD::TLSADDR;
11137
11138   if (InFlag) {
11139     SDValue Ops[] = { Chain,  TGA, *InFlag };
11140     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11141   } else {
11142     SDValue Ops[]  = { Chain, TGA };
11143     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11144   }
11145
11146   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11147   MFI->setAdjustsStack(true);
11148
11149   SDValue Flag = Chain.getValue(1);
11150   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11151 }
11152
11153 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11154 static SDValue
11155 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11156                                 const EVT PtrVT) {
11157   SDValue InFlag;
11158   SDLoc dl(GA);  // ? function entry point might be better
11159   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11160                                    DAG.getNode(X86ISD::GlobalBaseReg,
11161                                                SDLoc(), PtrVT), InFlag);
11162   InFlag = Chain.getValue(1);
11163
11164   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11165 }
11166
11167 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11168 static SDValue
11169 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11170                                 const EVT PtrVT) {
11171   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11172                     X86::RAX, X86II::MO_TLSGD);
11173 }
11174
11175 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11176                                            SelectionDAG &DAG,
11177                                            const EVT PtrVT,
11178                                            bool is64Bit) {
11179   SDLoc dl(GA);
11180
11181   // Get the start address of the TLS block for this module.
11182   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11183       .getInfo<X86MachineFunctionInfo>();
11184   MFI->incNumLocalDynamicTLSAccesses();
11185
11186   SDValue Base;
11187   if (is64Bit) {
11188     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11189                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11190   } else {
11191     SDValue InFlag;
11192     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11193         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11194     InFlag = Chain.getValue(1);
11195     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11196                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11197   }
11198
11199   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11200   // of Base.
11201
11202   // Build x@dtpoff.
11203   unsigned char OperandFlags = X86II::MO_DTPOFF;
11204   unsigned WrapperKind = X86ISD::Wrapper;
11205   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11206                                            GA->getValueType(0),
11207                                            GA->getOffset(), OperandFlags);
11208   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11209
11210   // Add x@dtpoff with the base.
11211   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11212 }
11213
11214 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11215 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11216                                    const EVT PtrVT, TLSModel::Model model,
11217                                    bool is64Bit, bool isPIC) {
11218   SDLoc dl(GA);
11219
11220   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11221   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11222                                                          is64Bit ? 257 : 256));
11223
11224   SDValue ThreadPointer =
11225       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11226                   MachinePointerInfo(Ptr), false, false, false, 0);
11227
11228   unsigned char OperandFlags = 0;
11229   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11230   // initialexec.
11231   unsigned WrapperKind = X86ISD::Wrapper;
11232   if (model == TLSModel::LocalExec) {
11233     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11234   } else if (model == TLSModel::InitialExec) {
11235     if (is64Bit) {
11236       OperandFlags = X86II::MO_GOTTPOFF;
11237       WrapperKind = X86ISD::WrapperRIP;
11238     } else {
11239       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11240     }
11241   } else {
11242     llvm_unreachable("Unexpected model");
11243   }
11244
11245   // emit "addl x@ntpoff,%eax" (local exec)
11246   // or "addl x@indntpoff,%eax" (initial exec)
11247   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11248   SDValue TGA =
11249       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11250                                  GA->getOffset(), OperandFlags);
11251   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11252
11253   if (model == TLSModel::InitialExec) {
11254     if (isPIC && !is64Bit) {
11255       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11256                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11257                            Offset);
11258     }
11259
11260     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11261                          MachinePointerInfo::getGOT(), false, false, false, 0);
11262   }
11263
11264   // The address of the thread local variable is the add of the thread
11265   // pointer with the offset of the variable.
11266   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11267 }
11268
11269 SDValue
11270 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11271
11272   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11273   const GlobalValue *GV = GA->getGlobal();
11274
11275   if (Subtarget->isTargetELF()) {
11276     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11277
11278     switch (model) {
11279       case TLSModel::GeneralDynamic:
11280         if (Subtarget->is64Bit())
11281           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11282         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11283       case TLSModel::LocalDynamic:
11284         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11285                                            Subtarget->is64Bit());
11286       case TLSModel::InitialExec:
11287       case TLSModel::LocalExec:
11288         return LowerToTLSExecModel(
11289             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11290             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11291     }
11292     llvm_unreachable("Unknown TLS model.");
11293   }
11294
11295   if (Subtarget->isTargetDarwin()) {
11296     // Darwin only has one model of TLS.  Lower to that.
11297     unsigned char OpFlag = 0;
11298     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11299                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11300
11301     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11302     // global base reg.
11303     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11304                  !Subtarget->is64Bit();
11305     if (PIC32)
11306       OpFlag = X86II::MO_TLVP_PIC_BASE;
11307     else
11308       OpFlag = X86II::MO_TLVP;
11309     SDLoc DL(Op);
11310     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11311                                                 GA->getValueType(0),
11312                                                 GA->getOffset(), OpFlag);
11313     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11314
11315     // With PIC32, the address is actually $g + Offset.
11316     if (PIC32)
11317       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11318                            DAG.getNode(X86ISD::GlobalBaseReg,
11319                                        SDLoc(), getPointerTy()),
11320                            Offset);
11321
11322     // Lowering the machine isd will make sure everything is in the right
11323     // location.
11324     SDValue Chain = DAG.getEntryNode();
11325     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11326     SDValue Args[] = { Chain, Offset };
11327     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11328
11329     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11330     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11331     MFI->setAdjustsStack(true);
11332
11333     // And our return value (tls address) is in the standard call return value
11334     // location.
11335     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11336     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11337                               Chain.getValue(1));
11338   }
11339
11340   if (Subtarget->isTargetKnownWindowsMSVC() ||
11341       Subtarget->isTargetWindowsGNU()) {
11342     // Just use the implicit TLS architecture
11343     // Need to generate someting similar to:
11344     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11345     //                                  ; from TEB
11346     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11347     //   mov     rcx, qword [rdx+rcx*8]
11348     //   mov     eax, .tls$:tlsvar
11349     //   [rax+rcx] contains the address
11350     // Windows 64bit: gs:0x58
11351     // Windows 32bit: fs:__tls_array
11352
11353     SDLoc dl(GA);
11354     SDValue Chain = DAG.getEntryNode();
11355
11356     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11357     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11358     // use its literal value of 0x2C.
11359     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11360                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11361                                                              256)
11362                                         : Type::getInt32PtrTy(*DAG.getContext(),
11363                                                               257));
11364
11365     SDValue TlsArray =
11366         Subtarget->is64Bit()
11367             ? DAG.getIntPtrConstant(0x58)
11368             : (Subtarget->isTargetWindowsGNU()
11369                    ? DAG.getIntPtrConstant(0x2C)
11370                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11371
11372     SDValue ThreadPointer =
11373         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11374                     MachinePointerInfo(Ptr), false, false, false, 0);
11375
11376     // Load the _tls_index variable
11377     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11378     if (Subtarget->is64Bit())
11379       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11380                            IDX, MachinePointerInfo(), MVT::i32,
11381                            false, false, false, 0);
11382     else
11383       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11384                         false, false, false, 0);
11385
11386     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11387                                     getPointerTy());
11388     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11389
11390     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11391     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11392                       false, false, false, 0);
11393
11394     // Get the offset of start of .tls section
11395     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11396                                              GA->getValueType(0),
11397                                              GA->getOffset(), X86II::MO_SECREL);
11398     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11399
11400     // The address of the thread local variable is the add of the thread
11401     // pointer with the offset of the variable.
11402     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11403   }
11404
11405   llvm_unreachable("TLS not implemented for this target.");
11406 }
11407
11408 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11409 /// and take a 2 x i32 value to shift plus a shift amount.
11410 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11411   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11412   MVT VT = Op.getSimpleValueType();
11413   unsigned VTBits = VT.getSizeInBits();
11414   SDLoc dl(Op);
11415   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11416   SDValue ShOpLo = Op.getOperand(0);
11417   SDValue ShOpHi = Op.getOperand(1);
11418   SDValue ShAmt  = Op.getOperand(2);
11419   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11420   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11421   // during isel.
11422   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11423                                   DAG.getConstant(VTBits - 1, MVT::i8));
11424   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11425                                      DAG.getConstant(VTBits - 1, MVT::i8))
11426                        : DAG.getConstant(0, VT);
11427
11428   SDValue Tmp2, Tmp3;
11429   if (Op.getOpcode() == ISD::SHL_PARTS) {
11430     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11431     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11432   } else {
11433     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11434     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11435   }
11436
11437   // If the shift amount is larger or equal than the width of a part we can't
11438   // rely on the results of shld/shrd. Insert a test and select the appropriate
11439   // values for large shift amounts.
11440   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11441                                 DAG.getConstant(VTBits, MVT::i8));
11442   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11443                              AndNode, DAG.getConstant(0, MVT::i8));
11444
11445   SDValue Hi, Lo;
11446   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11447   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11448   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11449
11450   if (Op.getOpcode() == ISD::SHL_PARTS) {
11451     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11452     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11453   } else {
11454     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11455     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11456   }
11457
11458   SDValue Ops[2] = { Lo, Hi };
11459   return DAG.getMergeValues(Ops, dl);
11460 }
11461
11462 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11463                                            SelectionDAG &DAG) const {
11464   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11465
11466   if (SrcVT.isVector())
11467     return SDValue();
11468
11469   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11470          "Unknown SINT_TO_FP to lower!");
11471
11472   // These are really Legal; return the operand so the caller accepts it as
11473   // Legal.
11474   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11475     return Op;
11476   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11477       Subtarget->is64Bit()) {
11478     return Op;
11479   }
11480
11481   SDLoc dl(Op);
11482   unsigned Size = SrcVT.getSizeInBits()/8;
11483   MachineFunction &MF = DAG.getMachineFunction();
11484   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11485   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11486   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11487                                StackSlot,
11488                                MachinePointerInfo::getFixedStack(SSFI),
11489                                false, false, 0);
11490   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11491 }
11492
11493 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11494                                      SDValue StackSlot,
11495                                      SelectionDAG &DAG) const {
11496   // Build the FILD
11497   SDLoc DL(Op);
11498   SDVTList Tys;
11499   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11500   if (useSSE)
11501     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11502   else
11503     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11504
11505   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11506
11507   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11508   MachineMemOperand *MMO;
11509   if (FI) {
11510     int SSFI = FI->getIndex();
11511     MMO =
11512       DAG.getMachineFunction()
11513       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11514                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11515   } else {
11516     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11517     StackSlot = StackSlot.getOperand(1);
11518   }
11519   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11520   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11521                                            X86ISD::FILD, DL,
11522                                            Tys, Ops, SrcVT, MMO);
11523
11524   if (useSSE) {
11525     Chain = Result.getValue(1);
11526     SDValue InFlag = Result.getValue(2);
11527
11528     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11529     // shouldn't be necessary except that RFP cannot be live across
11530     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11531     MachineFunction &MF = DAG.getMachineFunction();
11532     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11533     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11534     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11535     Tys = DAG.getVTList(MVT::Other);
11536     SDValue Ops[] = {
11537       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11538     };
11539     MachineMemOperand *MMO =
11540       DAG.getMachineFunction()
11541       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11542                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11543
11544     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11545                                     Ops, Op.getValueType(), MMO);
11546     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11547                          MachinePointerInfo::getFixedStack(SSFI),
11548                          false, false, false, 0);
11549   }
11550
11551   return Result;
11552 }
11553
11554 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11555 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11556                                                SelectionDAG &DAG) const {
11557   // This algorithm is not obvious. Here it is what we're trying to output:
11558   /*
11559      movq       %rax,  %xmm0
11560      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11561      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11562      #ifdef __SSE3__
11563        haddpd   %xmm0, %xmm0
11564      #else
11565        pshufd   $0x4e, %xmm0, %xmm1
11566        addpd    %xmm1, %xmm0
11567      #endif
11568   */
11569
11570   SDLoc dl(Op);
11571   LLVMContext *Context = DAG.getContext();
11572
11573   // Build some magic constants.
11574   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11575   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11576   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11577
11578   SmallVector<Constant*,2> CV1;
11579   CV1.push_back(
11580     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11581                                       APInt(64, 0x4330000000000000ULL))));
11582   CV1.push_back(
11583     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11584                                       APInt(64, 0x4530000000000000ULL))));
11585   Constant *C1 = ConstantVector::get(CV1);
11586   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11587
11588   // Load the 64-bit value into an XMM register.
11589   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11590                             Op.getOperand(0));
11591   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11592                               MachinePointerInfo::getConstantPool(),
11593                               false, false, false, 16);
11594   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11595                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11596                               CLod0);
11597
11598   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11599                               MachinePointerInfo::getConstantPool(),
11600                               false, false, false, 16);
11601   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11602   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11603   SDValue Result;
11604
11605   if (Subtarget->hasSSE3()) {
11606     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11607     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11608   } else {
11609     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11610     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11611                                            S2F, 0x4E, DAG);
11612     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11613                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11614                          Sub);
11615   }
11616
11617   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11618                      DAG.getIntPtrConstant(0));
11619 }
11620
11621 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11622 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11623                                                SelectionDAG &DAG) const {
11624   SDLoc dl(Op);
11625   // FP constant to bias correct the final result.
11626   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11627                                    MVT::f64);
11628
11629   // Load the 32-bit value into an XMM register.
11630   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11631                              Op.getOperand(0));
11632
11633   // Zero out the upper parts of the register.
11634   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11635
11636   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11637                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11638                      DAG.getIntPtrConstant(0));
11639
11640   // Or the load with the bias.
11641   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11642                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11643                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11644                                                    MVT::v2f64, Load)),
11645                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11646                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11647                                                    MVT::v2f64, Bias)));
11648   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11649                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11650                    DAG.getIntPtrConstant(0));
11651
11652   // Subtract the bias.
11653   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11654
11655   // Handle final rounding.
11656   EVT DestVT = Op.getValueType();
11657
11658   if (DestVT.bitsLT(MVT::f64))
11659     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11660                        DAG.getIntPtrConstant(0));
11661   if (DestVT.bitsGT(MVT::f64))
11662     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11663
11664   // Handle final rounding.
11665   return Sub;
11666 }
11667
11668 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11669                                                SelectionDAG &DAG) const {
11670   SDValue N0 = Op.getOperand(0);
11671   MVT SVT = N0.getSimpleValueType();
11672   SDLoc dl(Op);
11673
11674   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11675           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11676          "Custom UINT_TO_FP is not supported!");
11677
11678   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11679   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11680                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11681 }
11682
11683 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11684                                            SelectionDAG &DAG) const {
11685   SDValue N0 = Op.getOperand(0);
11686   SDLoc dl(Op);
11687
11688   if (Op.getValueType().isVector())
11689     return lowerUINT_TO_FP_vec(Op, DAG);
11690
11691   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11692   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11693   // the optimization here.
11694   if (DAG.SignBitIsZero(N0))
11695     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11696
11697   MVT SrcVT = N0.getSimpleValueType();
11698   MVT DstVT = Op.getSimpleValueType();
11699   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11700     return LowerUINT_TO_FP_i64(Op, DAG);
11701   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11702     return LowerUINT_TO_FP_i32(Op, DAG);
11703   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11704     return SDValue();
11705
11706   // Make a 64-bit buffer, and use it to build an FILD.
11707   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11708   if (SrcVT == MVT::i32) {
11709     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11710     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11711                                      getPointerTy(), StackSlot, WordOff);
11712     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11713                                   StackSlot, MachinePointerInfo(),
11714                                   false, false, 0);
11715     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11716                                   OffsetSlot, MachinePointerInfo(),
11717                                   false, false, 0);
11718     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11719     return Fild;
11720   }
11721
11722   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11723   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11724                                StackSlot, MachinePointerInfo(),
11725                                false, false, 0);
11726   // For i64 source, we need to add the appropriate power of 2 if the input
11727   // was negative.  This is the same as the optimization in
11728   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11729   // we must be careful to do the computation in x87 extended precision, not
11730   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11731   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11732   MachineMemOperand *MMO =
11733     DAG.getMachineFunction()
11734     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11735                           MachineMemOperand::MOLoad, 8, 8);
11736
11737   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11738   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11739   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11740                                          MVT::i64, MMO);
11741
11742   APInt FF(32, 0x5F800000ULL);
11743
11744   // Check whether the sign bit is set.
11745   SDValue SignSet = DAG.getSetCC(dl,
11746                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11747                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11748                                  ISD::SETLT);
11749
11750   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11751   SDValue FudgePtr = DAG.getConstantPool(
11752                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11753                                          getPointerTy());
11754
11755   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11756   SDValue Zero = DAG.getIntPtrConstant(0);
11757   SDValue Four = DAG.getIntPtrConstant(4);
11758   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11759                                Zero, Four);
11760   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11761
11762   // Load the value out, extending it from f32 to f80.
11763   // FIXME: Avoid the extend by constructing the right constant pool?
11764   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11765                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11766                                  MVT::f32, false, false, false, 4);
11767   // Extend everything to 80 bits to force it to be done on x87.
11768   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11769   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11770 }
11771
11772 std::pair<SDValue,SDValue>
11773 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11774                                     bool IsSigned, bool IsReplace) const {
11775   SDLoc DL(Op);
11776
11777   EVT DstTy = Op.getValueType();
11778
11779   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11780     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11781     DstTy = MVT::i64;
11782   }
11783
11784   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11785          DstTy.getSimpleVT() >= MVT::i16 &&
11786          "Unknown FP_TO_INT to lower!");
11787
11788   // These are really Legal.
11789   if (DstTy == MVT::i32 &&
11790       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11791     return std::make_pair(SDValue(), SDValue());
11792   if (Subtarget->is64Bit() &&
11793       DstTy == MVT::i64 &&
11794       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11795     return std::make_pair(SDValue(), SDValue());
11796
11797   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11798   // stack slot, or into the FTOL runtime function.
11799   MachineFunction &MF = DAG.getMachineFunction();
11800   unsigned MemSize = DstTy.getSizeInBits()/8;
11801   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11802   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11803
11804   unsigned Opc;
11805   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11806     Opc = X86ISD::WIN_FTOL;
11807   else
11808     switch (DstTy.getSimpleVT().SimpleTy) {
11809     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11810     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11811     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11812     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11813     }
11814
11815   SDValue Chain = DAG.getEntryNode();
11816   SDValue Value = Op.getOperand(0);
11817   EVT TheVT = Op.getOperand(0).getValueType();
11818   // FIXME This causes a redundant load/store if the SSE-class value is already
11819   // in memory, such as if it is on the callstack.
11820   if (isScalarFPTypeInSSEReg(TheVT)) {
11821     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11822     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11823                          MachinePointerInfo::getFixedStack(SSFI),
11824                          false, false, 0);
11825     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11826     SDValue Ops[] = {
11827       Chain, StackSlot, DAG.getValueType(TheVT)
11828     };
11829
11830     MachineMemOperand *MMO =
11831       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11832                               MachineMemOperand::MOLoad, MemSize, MemSize);
11833     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11834     Chain = Value.getValue(1);
11835     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11836     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11837   }
11838
11839   MachineMemOperand *MMO =
11840     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11841                             MachineMemOperand::MOStore, MemSize, MemSize);
11842
11843   if (Opc != X86ISD::WIN_FTOL) {
11844     // Build the FP_TO_INT*_IN_MEM
11845     SDValue Ops[] = { Chain, Value, StackSlot };
11846     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11847                                            Ops, DstTy, MMO);
11848     return std::make_pair(FIST, StackSlot);
11849   } else {
11850     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11851       DAG.getVTList(MVT::Other, MVT::Glue),
11852       Chain, Value);
11853     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11854       MVT::i32, ftol.getValue(1));
11855     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11856       MVT::i32, eax.getValue(2));
11857     SDValue Ops[] = { eax, edx };
11858     SDValue pair = IsReplace
11859       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11860       : DAG.getMergeValues(Ops, DL);
11861     return std::make_pair(pair, SDValue());
11862   }
11863 }
11864
11865 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11866                               const X86Subtarget *Subtarget) {
11867   MVT VT = Op->getSimpleValueType(0);
11868   SDValue In = Op->getOperand(0);
11869   MVT InVT = In.getSimpleValueType();
11870   SDLoc dl(Op);
11871
11872   // Optimize vectors in AVX mode:
11873   //
11874   //   v8i16 -> v8i32
11875   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11876   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11877   //   Concat upper and lower parts.
11878   //
11879   //   v4i32 -> v4i64
11880   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11881   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11882   //   Concat upper and lower parts.
11883   //
11884
11885   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11886       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11887       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11888     return SDValue();
11889
11890   if (Subtarget->hasInt256())
11891     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11892
11893   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11894   SDValue Undef = DAG.getUNDEF(InVT);
11895   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11896   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11897   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11898
11899   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11900                              VT.getVectorNumElements()/2);
11901
11902   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11903   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11904
11905   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11906 }
11907
11908 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11909                                         SelectionDAG &DAG) {
11910   MVT VT = Op->getSimpleValueType(0);
11911   SDValue In = Op->getOperand(0);
11912   MVT InVT = In.getSimpleValueType();
11913   SDLoc DL(Op);
11914   unsigned int NumElts = VT.getVectorNumElements();
11915   if (NumElts != 8 && NumElts != 16)
11916     return SDValue();
11917
11918   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11919     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11920
11921   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11923   // Now we have only mask extension
11924   assert(InVT.getVectorElementType() == MVT::i1);
11925   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11926   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11927   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11928   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11929   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11930                            MachinePointerInfo::getConstantPool(),
11931                            false, false, false, Alignment);
11932
11933   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11934   if (VT.is512BitVector())
11935     return Brcst;
11936   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11937 }
11938
11939 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11940                                SelectionDAG &DAG) {
11941   if (Subtarget->hasFp256()) {
11942     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11943     if (Res.getNode())
11944       return Res;
11945   }
11946
11947   return SDValue();
11948 }
11949
11950 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11951                                 SelectionDAG &DAG) {
11952   SDLoc DL(Op);
11953   MVT VT = Op.getSimpleValueType();
11954   SDValue In = Op.getOperand(0);
11955   MVT SVT = In.getSimpleValueType();
11956
11957   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11958     return LowerZERO_EXTEND_AVX512(Op, DAG);
11959
11960   if (Subtarget->hasFp256()) {
11961     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11962     if (Res.getNode())
11963       return Res;
11964   }
11965
11966   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11967          VT.getVectorNumElements() != SVT.getVectorNumElements());
11968   return SDValue();
11969 }
11970
11971 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11972   SDLoc DL(Op);
11973   MVT VT = Op.getSimpleValueType();
11974   SDValue In = Op.getOperand(0);
11975   MVT InVT = In.getSimpleValueType();
11976
11977   if (VT == MVT::i1) {
11978     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11979            "Invalid scalar TRUNCATE operation");
11980     if (InVT.getSizeInBits() >= 32)
11981       return SDValue();
11982     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11983     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11984   }
11985   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11986          "Invalid TRUNCATE operation");
11987
11988   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11989     if (VT.getVectorElementType().getSizeInBits() >=8)
11990       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11991
11992     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11993     unsigned NumElts = InVT.getVectorNumElements();
11994     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11995     if (InVT.getSizeInBits() < 512) {
11996       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11997       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11998       InVT = ExtVT;
11999     }
12000     
12001     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12002     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12003     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12004     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12005     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12006                            MachinePointerInfo::getConstantPool(),
12007                            false, false, false, Alignment);
12008     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12009     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12010     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12011   }
12012
12013   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12014     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12015     if (Subtarget->hasInt256()) {
12016       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12017       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12018       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12019                                 ShufMask);
12020       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12021                          DAG.getIntPtrConstant(0));
12022     }
12023
12024     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12025                                DAG.getIntPtrConstant(0));
12026     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12027                                DAG.getIntPtrConstant(2));
12028     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12029     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12030     static const int ShufMask[] = {0, 2, 4, 6};
12031     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12032   }
12033
12034   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12035     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12036     if (Subtarget->hasInt256()) {
12037       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12038
12039       SmallVector<SDValue,32> pshufbMask;
12040       for (unsigned i = 0; i < 2; ++i) {
12041         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12042         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12043         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12044         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12045         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12046         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12047         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12048         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12049         for (unsigned j = 0; j < 8; ++j)
12050           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12051       }
12052       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12053       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12054       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12055
12056       static const int ShufMask[] = {0,  2,  -1,  -1};
12057       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12058                                 &ShufMask[0]);
12059       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12060                        DAG.getIntPtrConstant(0));
12061       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12062     }
12063
12064     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12065                                DAG.getIntPtrConstant(0));
12066
12067     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12068                                DAG.getIntPtrConstant(4));
12069
12070     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12071     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12072
12073     // The PSHUFB mask:
12074     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12075                                    -1, -1, -1, -1, -1, -1, -1, -1};
12076
12077     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12078     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12079     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12080
12081     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12082     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12083
12084     // The MOVLHPS Mask:
12085     static const int ShufMask2[] = {0, 1, 4, 5};
12086     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12087     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12088   }
12089
12090   // Handle truncation of V256 to V128 using shuffles.
12091   if (!VT.is128BitVector() || !InVT.is256BitVector())
12092     return SDValue();
12093
12094   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12095
12096   unsigned NumElems = VT.getVectorNumElements();
12097   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12098
12099   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12100   // Prepare truncation shuffle mask
12101   for (unsigned i = 0; i != NumElems; ++i)
12102     MaskVec[i] = i * 2;
12103   SDValue V = DAG.getVectorShuffle(NVT, DL,
12104                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12105                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12106   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12107                      DAG.getIntPtrConstant(0));
12108 }
12109
12110 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12111                                            SelectionDAG &DAG) const {
12112   assert(!Op.getSimpleValueType().isVector());
12113
12114   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12115     /*IsSigned=*/ true, /*IsReplace=*/ false);
12116   SDValue FIST = Vals.first, StackSlot = Vals.second;
12117   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12118   if (!FIST.getNode()) return Op;
12119
12120   if (StackSlot.getNode())
12121     // Load the result.
12122     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12123                        FIST, StackSlot, MachinePointerInfo(),
12124                        false, false, false, 0);
12125
12126   // The node is the result.
12127   return FIST;
12128 }
12129
12130 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12131                                            SelectionDAG &DAG) const {
12132   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12133     /*IsSigned=*/ false, /*IsReplace=*/ false);
12134   SDValue FIST = Vals.first, StackSlot = Vals.second;
12135   assert(FIST.getNode() && "Unexpected failure");
12136
12137   if (StackSlot.getNode())
12138     // Load the result.
12139     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12140                        FIST, StackSlot, MachinePointerInfo(),
12141                        false, false, false, 0);
12142
12143   // The node is the result.
12144   return FIST;
12145 }
12146
12147 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12148   SDLoc DL(Op);
12149   MVT VT = Op.getSimpleValueType();
12150   SDValue In = Op.getOperand(0);
12151   MVT SVT = In.getSimpleValueType();
12152
12153   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12154
12155   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12156                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12157                                  In, DAG.getUNDEF(SVT)));
12158 }
12159
12160 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
12161   LLVMContext *Context = DAG.getContext();
12162   SDLoc dl(Op);
12163   MVT VT = Op.getSimpleValueType();
12164   MVT EltVT = VT;
12165   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12166   if (VT.isVector()) {
12167     EltVT = VT.getVectorElementType();
12168     NumElts = VT.getVectorNumElements();
12169   }
12170   Constant *C;
12171   if (EltVT == MVT::f64)
12172     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12173                                           APInt(64, ~(1ULL << 63))));
12174   else
12175     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12176                                           APInt(32, ~(1U << 31))));
12177   C = ConstantVector::getSplat(NumElts, C);
12178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12179   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12180   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12181   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12182                              MachinePointerInfo::getConstantPool(),
12183                              false, false, false, Alignment);
12184   if (VT.isVector()) {
12185     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12186     return DAG.getNode(ISD::BITCAST, dl, VT,
12187                        DAG.getNode(ISD::AND, dl, ANDVT,
12188                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
12189                                                Op.getOperand(0)),
12190                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
12191   }
12192   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
12193 }
12194
12195 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
12196   LLVMContext *Context = DAG.getContext();
12197   SDLoc dl(Op);
12198   MVT VT = Op.getSimpleValueType();
12199   MVT EltVT = VT;
12200   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12201   if (VT.isVector()) {
12202     EltVT = VT.getVectorElementType();
12203     NumElts = VT.getVectorNumElements();
12204   }
12205   Constant *C;
12206   if (EltVT == MVT::f64)
12207     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12208                                           APInt(64, 1ULL << 63)));
12209   else
12210     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12211                                           APInt(32, 1U << 31)));
12212   C = ConstantVector::getSplat(NumElts, C);
12213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12214   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12215   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12216   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12217                              MachinePointerInfo::getConstantPool(),
12218                              false, false, false, Alignment);
12219   if (VT.isVector()) {
12220     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
12221     return DAG.getNode(ISD::BITCAST, dl, VT,
12222                        DAG.getNode(ISD::XOR, dl, XORVT,
12223                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
12224                                                Op.getOperand(0)),
12225                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
12226   }
12227
12228   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
12229 }
12230
12231 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12233   LLVMContext *Context = DAG.getContext();
12234   SDValue Op0 = Op.getOperand(0);
12235   SDValue Op1 = Op.getOperand(1);
12236   SDLoc dl(Op);
12237   MVT VT = Op.getSimpleValueType();
12238   MVT SrcVT = Op1.getSimpleValueType();
12239
12240   // If second operand is smaller, extend it first.
12241   if (SrcVT.bitsLT(VT)) {
12242     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12243     SrcVT = VT;
12244   }
12245   // And if it is bigger, shrink it first.
12246   if (SrcVT.bitsGT(VT)) {
12247     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12248     SrcVT = VT;
12249   }
12250
12251   // At this point the operands and the result should have the same
12252   // type, and that won't be f80 since that is not custom lowered.
12253
12254   // First get the sign bit of second operand.
12255   SmallVector<Constant*,4> CV;
12256   if (SrcVT == MVT::f64) {
12257     const fltSemantics &Sem = APFloat::IEEEdouble;
12258     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12259     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12260   } else {
12261     const fltSemantics &Sem = APFloat::IEEEsingle;
12262     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12263     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12264     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12265     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12266   }
12267   Constant *C = ConstantVector::get(CV);
12268   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12269   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12270                               MachinePointerInfo::getConstantPool(),
12271                               false, false, false, 16);
12272   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12273
12274   // Shift sign bit right or left if the two operands have different types.
12275   if (SrcVT.bitsGT(VT)) {
12276     // Op0 is MVT::f32, Op1 is MVT::f64.
12277     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12278     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12279                           DAG.getConstant(32, MVT::i32));
12280     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12281     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12282                           DAG.getIntPtrConstant(0));
12283   }
12284
12285   // Clear first operand sign bit.
12286   CV.clear();
12287   if (VT == MVT::f64) {
12288     const fltSemantics &Sem = APFloat::IEEEdouble;
12289     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12290                                                    APInt(64, ~(1ULL << 63)))));
12291     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12292   } else {
12293     const fltSemantics &Sem = APFloat::IEEEsingle;
12294     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12295                                                    APInt(32, ~(1U << 31)))));
12296     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12297     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12298     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12299   }
12300   C = ConstantVector::get(CV);
12301   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12302   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12303                               MachinePointerInfo::getConstantPool(),
12304                               false, false, false, 16);
12305   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12306
12307   // Or the value with the sign bit.
12308   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12309 }
12310
12311 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12312   SDValue N0 = Op.getOperand(0);
12313   SDLoc dl(Op);
12314   MVT VT = Op.getSimpleValueType();
12315
12316   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12317   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12318                                   DAG.getConstant(1, VT));
12319   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12320 }
12321
12322 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12323 //
12324 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12325                                       SelectionDAG &DAG) {
12326   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12327
12328   if (!Subtarget->hasSSE41())
12329     return SDValue();
12330
12331   if (!Op->hasOneUse())
12332     return SDValue();
12333
12334   SDNode *N = Op.getNode();
12335   SDLoc DL(N);
12336
12337   SmallVector<SDValue, 8> Opnds;
12338   DenseMap<SDValue, unsigned> VecInMap;
12339   SmallVector<SDValue, 8> VecIns;
12340   EVT VT = MVT::Other;
12341
12342   // Recognize a special case where a vector is casted into wide integer to
12343   // test all 0s.
12344   Opnds.push_back(N->getOperand(0));
12345   Opnds.push_back(N->getOperand(1));
12346
12347   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12348     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12349     // BFS traverse all OR'd operands.
12350     if (I->getOpcode() == ISD::OR) {
12351       Opnds.push_back(I->getOperand(0));
12352       Opnds.push_back(I->getOperand(1));
12353       // Re-evaluate the number of nodes to be traversed.
12354       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12355       continue;
12356     }
12357
12358     // Quit if a non-EXTRACT_VECTOR_ELT
12359     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12360       return SDValue();
12361
12362     // Quit if without a constant index.
12363     SDValue Idx = I->getOperand(1);
12364     if (!isa<ConstantSDNode>(Idx))
12365       return SDValue();
12366
12367     SDValue ExtractedFromVec = I->getOperand(0);
12368     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12369     if (M == VecInMap.end()) {
12370       VT = ExtractedFromVec.getValueType();
12371       // Quit if not 128/256-bit vector.
12372       if (!VT.is128BitVector() && !VT.is256BitVector())
12373         return SDValue();
12374       // Quit if not the same type.
12375       if (VecInMap.begin() != VecInMap.end() &&
12376           VT != VecInMap.begin()->first.getValueType())
12377         return SDValue();
12378       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12379       VecIns.push_back(ExtractedFromVec);
12380     }
12381     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12382   }
12383
12384   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12385          "Not extracted from 128-/256-bit vector.");
12386
12387   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12388
12389   for (DenseMap<SDValue, unsigned>::const_iterator
12390         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12391     // Quit if not all elements are used.
12392     if (I->second != FullMask)
12393       return SDValue();
12394   }
12395
12396   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12397
12398   // Cast all vectors into TestVT for PTEST.
12399   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12400     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12401
12402   // If more than one full vectors are evaluated, OR them first before PTEST.
12403   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12404     // Each iteration will OR 2 nodes and append the result until there is only
12405     // 1 node left, i.e. the final OR'd value of all vectors.
12406     SDValue LHS = VecIns[Slot];
12407     SDValue RHS = VecIns[Slot + 1];
12408     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12409   }
12410
12411   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12412                      VecIns.back(), VecIns.back());
12413 }
12414
12415 /// \brief return true if \c Op has a use that doesn't just read flags.
12416 static bool hasNonFlagsUse(SDValue Op) {
12417   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12418        ++UI) {
12419     SDNode *User = *UI;
12420     unsigned UOpNo = UI.getOperandNo();
12421     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12422       // Look pass truncate.
12423       UOpNo = User->use_begin().getOperandNo();
12424       User = *User->use_begin();
12425     }
12426
12427     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12428         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12429       return true;
12430   }
12431   return false;
12432 }
12433
12434 /// Emit nodes that will be selected as "test Op0,Op0", or something
12435 /// equivalent.
12436 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12437                                     SelectionDAG &DAG) const {
12438   if (Op.getValueType() == MVT::i1)
12439     // KORTEST instruction should be selected
12440     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12441                        DAG.getConstant(0, Op.getValueType()));
12442
12443   // CF and OF aren't always set the way we want. Determine which
12444   // of these we need.
12445   bool NeedCF = false;
12446   bool NeedOF = false;
12447   switch (X86CC) {
12448   default: break;
12449   case X86::COND_A: case X86::COND_AE:
12450   case X86::COND_B: case X86::COND_BE:
12451     NeedCF = true;
12452     break;
12453   case X86::COND_G: case X86::COND_GE:
12454   case X86::COND_L: case X86::COND_LE:
12455   case X86::COND_O: case X86::COND_NO: {
12456     // Check if we really need to set the
12457     // Overflow flag. If NoSignedWrap is present
12458     // that is not actually needed.
12459     switch (Op->getOpcode()) {
12460     case ISD::ADD:
12461     case ISD::SUB:
12462     case ISD::MUL:
12463     case ISD::SHL: {
12464       const BinaryWithFlagsSDNode *BinNode =
12465           cast<BinaryWithFlagsSDNode>(Op.getNode());
12466       if (BinNode->hasNoSignedWrap())
12467         break;
12468     }
12469     default:
12470       NeedOF = true;
12471       break;
12472     }
12473     break;
12474   }
12475   }
12476   // See if we can use the EFLAGS value from the operand instead of
12477   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12478   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12479   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12480     // Emit a CMP with 0, which is the TEST pattern.
12481     //if (Op.getValueType() == MVT::i1)
12482     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12483     //                     DAG.getConstant(0, MVT::i1));
12484     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12485                        DAG.getConstant(0, Op.getValueType()));
12486   }
12487   unsigned Opcode = 0;
12488   unsigned NumOperands = 0;
12489
12490   // Truncate operations may prevent the merge of the SETCC instruction
12491   // and the arithmetic instruction before it. Attempt to truncate the operands
12492   // of the arithmetic instruction and use a reduced bit-width instruction.
12493   bool NeedTruncation = false;
12494   SDValue ArithOp = Op;
12495   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12496     SDValue Arith = Op->getOperand(0);
12497     // Both the trunc and the arithmetic op need to have one user each.
12498     if (Arith->hasOneUse())
12499       switch (Arith.getOpcode()) {
12500         default: break;
12501         case ISD::ADD:
12502         case ISD::SUB:
12503         case ISD::AND:
12504         case ISD::OR:
12505         case ISD::XOR: {
12506           NeedTruncation = true;
12507           ArithOp = Arith;
12508         }
12509       }
12510   }
12511
12512   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12513   // which may be the result of a CAST.  We use the variable 'Op', which is the
12514   // non-casted variable when we check for possible users.
12515   switch (ArithOp.getOpcode()) {
12516   case ISD::ADD:
12517     // Due to an isel shortcoming, be conservative if this add is likely to be
12518     // selected as part of a load-modify-store instruction. When the root node
12519     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12520     // uses of other nodes in the match, such as the ADD in this case. This
12521     // leads to the ADD being left around and reselected, with the result being
12522     // two adds in the output.  Alas, even if none our users are stores, that
12523     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12524     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12525     // climbing the DAG back to the root, and it doesn't seem to be worth the
12526     // effort.
12527     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12528          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12529       if (UI->getOpcode() != ISD::CopyToReg &&
12530           UI->getOpcode() != ISD::SETCC &&
12531           UI->getOpcode() != ISD::STORE)
12532         goto default_case;
12533
12534     if (ConstantSDNode *C =
12535         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12536       // An add of one will be selected as an INC.
12537       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12538         Opcode = X86ISD::INC;
12539         NumOperands = 1;
12540         break;
12541       }
12542
12543       // An add of negative one (subtract of one) will be selected as a DEC.
12544       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12545         Opcode = X86ISD::DEC;
12546         NumOperands = 1;
12547         break;
12548       }
12549     }
12550
12551     // Otherwise use a regular EFLAGS-setting add.
12552     Opcode = X86ISD::ADD;
12553     NumOperands = 2;
12554     break;
12555   case ISD::SHL:
12556   case ISD::SRL:
12557     // If we have a constant logical shift that's only used in a comparison
12558     // against zero turn it into an equivalent AND. This allows turning it into
12559     // a TEST instruction later.
12560     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12561         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12562       EVT VT = Op.getValueType();
12563       unsigned BitWidth = VT.getSizeInBits();
12564       unsigned ShAmt = Op->getConstantOperandVal(1);
12565       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12566         break;
12567       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12568                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12569                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12570       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12571         break;
12572       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12573                                 DAG.getConstant(Mask, VT));
12574       DAG.ReplaceAllUsesWith(Op, New);
12575       Op = New;
12576     }
12577     break;
12578
12579   case ISD::AND:
12580     // If the primary and result isn't used, don't bother using X86ISD::AND,
12581     // because a TEST instruction will be better.
12582     if (!hasNonFlagsUse(Op))
12583       break;
12584     // FALL THROUGH
12585   case ISD::SUB:
12586   case ISD::OR:
12587   case ISD::XOR:
12588     // Due to the ISEL shortcoming noted above, be conservative if this op is
12589     // likely to be selected as part of a load-modify-store instruction.
12590     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12591            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12592       if (UI->getOpcode() == ISD::STORE)
12593         goto default_case;
12594
12595     // Otherwise use a regular EFLAGS-setting instruction.
12596     switch (ArithOp.getOpcode()) {
12597     default: llvm_unreachable("unexpected operator!");
12598     case ISD::SUB: Opcode = X86ISD::SUB; break;
12599     case ISD::XOR: Opcode = X86ISD::XOR; break;
12600     case ISD::AND: Opcode = X86ISD::AND; break;
12601     case ISD::OR: {
12602       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12603         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12604         if (EFLAGS.getNode())
12605           return EFLAGS;
12606       }
12607       Opcode = X86ISD::OR;
12608       break;
12609     }
12610     }
12611
12612     NumOperands = 2;
12613     break;
12614   case X86ISD::ADD:
12615   case X86ISD::SUB:
12616   case X86ISD::INC:
12617   case X86ISD::DEC:
12618   case X86ISD::OR:
12619   case X86ISD::XOR:
12620   case X86ISD::AND:
12621     return SDValue(Op.getNode(), 1);
12622   default:
12623   default_case:
12624     break;
12625   }
12626
12627   // If we found that truncation is beneficial, perform the truncation and
12628   // update 'Op'.
12629   if (NeedTruncation) {
12630     EVT VT = Op.getValueType();
12631     SDValue WideVal = Op->getOperand(0);
12632     EVT WideVT = WideVal.getValueType();
12633     unsigned ConvertedOp = 0;
12634     // Use a target machine opcode to prevent further DAGCombine
12635     // optimizations that may separate the arithmetic operations
12636     // from the setcc node.
12637     switch (WideVal.getOpcode()) {
12638       default: break;
12639       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12640       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12641       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12642       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12643       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12644     }
12645
12646     if (ConvertedOp) {
12647       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12648       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12649         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12650         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12651         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12652       }
12653     }
12654   }
12655
12656   if (Opcode == 0)
12657     // Emit a CMP with 0, which is the TEST pattern.
12658     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12659                        DAG.getConstant(0, Op.getValueType()));
12660
12661   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12662   SmallVector<SDValue, 4> Ops;
12663   for (unsigned i = 0; i != NumOperands; ++i)
12664     Ops.push_back(Op.getOperand(i));
12665
12666   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12667   DAG.ReplaceAllUsesWith(Op, New);
12668   return SDValue(New.getNode(), 1);
12669 }
12670
12671 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12672 /// equivalent.
12673 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12674                                    SDLoc dl, SelectionDAG &DAG) const {
12675   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12676     if (C->getAPIntValue() == 0)
12677       return EmitTest(Op0, X86CC, dl, DAG);
12678
12679      if (Op0.getValueType() == MVT::i1)
12680        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12681   }
12682  
12683   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12684        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12685     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12686     // This avoids subregister aliasing issues. Keep the smaller reference 
12687     // if we're optimizing for size, however, as that'll allow better folding 
12688     // of memory operations.
12689     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12690         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12691              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12692         !Subtarget->isAtom()) {
12693       unsigned ExtendOp =
12694           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12695       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12696       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12697     }
12698     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12699     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12700     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12701                               Op0, Op1);
12702     return SDValue(Sub.getNode(), 1);
12703   }
12704   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12705 }
12706
12707 /// Convert a comparison if required by the subtarget.
12708 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12709                                                  SelectionDAG &DAG) const {
12710   // If the subtarget does not support the FUCOMI instruction, floating-point
12711   // comparisons have to be converted.
12712   if (Subtarget->hasCMov() ||
12713       Cmp.getOpcode() != X86ISD::CMP ||
12714       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12715       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12716     return Cmp;
12717
12718   // The instruction selector will select an FUCOM instruction instead of
12719   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12720   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12721   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12722   SDLoc dl(Cmp);
12723   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12724   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12725   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12726                             DAG.getConstant(8, MVT::i8));
12727   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12728   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12729 }
12730
12731 static bool isAllOnes(SDValue V) {
12732   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12733   return C && C->isAllOnesValue();
12734 }
12735
12736 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12737 /// if it's possible.
12738 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12739                                      SDLoc dl, SelectionDAG &DAG) const {
12740   SDValue Op0 = And.getOperand(0);
12741   SDValue Op1 = And.getOperand(1);
12742   if (Op0.getOpcode() == ISD::TRUNCATE)
12743     Op0 = Op0.getOperand(0);
12744   if (Op1.getOpcode() == ISD::TRUNCATE)
12745     Op1 = Op1.getOperand(0);
12746
12747   SDValue LHS, RHS;
12748   if (Op1.getOpcode() == ISD::SHL)
12749     std::swap(Op0, Op1);
12750   if (Op0.getOpcode() == ISD::SHL) {
12751     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12752       if (And00C->getZExtValue() == 1) {
12753         // If we looked past a truncate, check that it's only truncating away
12754         // known zeros.
12755         unsigned BitWidth = Op0.getValueSizeInBits();
12756         unsigned AndBitWidth = And.getValueSizeInBits();
12757         if (BitWidth > AndBitWidth) {
12758           APInt Zeros, Ones;
12759           DAG.computeKnownBits(Op0, Zeros, Ones);
12760           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12761             return SDValue();
12762         }
12763         LHS = Op1;
12764         RHS = Op0.getOperand(1);
12765       }
12766   } else if (Op1.getOpcode() == ISD::Constant) {
12767     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12768     uint64_t AndRHSVal = AndRHS->getZExtValue();
12769     SDValue AndLHS = Op0;
12770
12771     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12772       LHS = AndLHS.getOperand(0);
12773       RHS = AndLHS.getOperand(1);
12774     }
12775
12776     // Use BT if the immediate can't be encoded in a TEST instruction.
12777     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12778       LHS = AndLHS;
12779       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12780     }
12781   }
12782
12783   if (LHS.getNode()) {
12784     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12785     // instruction.  Since the shift amount is in-range-or-undefined, we know
12786     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12787     // the encoding for the i16 version is larger than the i32 version.
12788     // Also promote i16 to i32 for performance / code size reason.
12789     if (LHS.getValueType() == MVT::i8 ||
12790         LHS.getValueType() == MVT::i16)
12791       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12792
12793     // If the operand types disagree, extend the shift amount to match.  Since
12794     // BT ignores high bits (like shifts) we can use anyextend.
12795     if (LHS.getValueType() != RHS.getValueType())
12796       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12797
12798     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12799     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12800     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12801                        DAG.getConstant(Cond, MVT::i8), BT);
12802   }
12803
12804   return SDValue();
12805 }
12806
12807 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12808 /// mask CMPs.
12809 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12810                               SDValue &Op1) {
12811   unsigned SSECC;
12812   bool Swap = false;
12813
12814   // SSE Condition code mapping:
12815   //  0 - EQ
12816   //  1 - LT
12817   //  2 - LE
12818   //  3 - UNORD
12819   //  4 - NEQ
12820   //  5 - NLT
12821   //  6 - NLE
12822   //  7 - ORD
12823   switch (SetCCOpcode) {
12824   default: llvm_unreachable("Unexpected SETCC condition");
12825   case ISD::SETOEQ:
12826   case ISD::SETEQ:  SSECC = 0; break;
12827   case ISD::SETOGT:
12828   case ISD::SETGT:  Swap = true; // Fallthrough
12829   case ISD::SETLT:
12830   case ISD::SETOLT: SSECC = 1; break;
12831   case ISD::SETOGE:
12832   case ISD::SETGE:  Swap = true; // Fallthrough
12833   case ISD::SETLE:
12834   case ISD::SETOLE: SSECC = 2; break;
12835   case ISD::SETUO:  SSECC = 3; break;
12836   case ISD::SETUNE:
12837   case ISD::SETNE:  SSECC = 4; break;
12838   case ISD::SETULE: Swap = true; // Fallthrough
12839   case ISD::SETUGE: SSECC = 5; break;
12840   case ISD::SETULT: Swap = true; // Fallthrough
12841   case ISD::SETUGT: SSECC = 6; break;
12842   case ISD::SETO:   SSECC = 7; break;
12843   case ISD::SETUEQ:
12844   case ISD::SETONE: SSECC = 8; break;
12845   }
12846   if (Swap)
12847     std::swap(Op0, Op1);
12848
12849   return SSECC;
12850 }
12851
12852 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12853 // ones, and then concatenate the result back.
12854 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12855   MVT VT = Op.getSimpleValueType();
12856
12857   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12858          "Unsupported value type for operation");
12859
12860   unsigned NumElems = VT.getVectorNumElements();
12861   SDLoc dl(Op);
12862   SDValue CC = Op.getOperand(2);
12863
12864   // Extract the LHS vectors
12865   SDValue LHS = Op.getOperand(0);
12866   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12867   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12868
12869   // Extract the RHS vectors
12870   SDValue RHS = Op.getOperand(1);
12871   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12872   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12873
12874   // Issue the operation on the smaller types and concatenate the result back
12875   MVT EltVT = VT.getVectorElementType();
12876   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12877   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12878                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12879                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12880 }
12881
12882 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12883                                      const X86Subtarget *Subtarget) {
12884   SDValue Op0 = Op.getOperand(0);
12885   SDValue Op1 = Op.getOperand(1);
12886   SDValue CC = Op.getOperand(2);
12887   MVT VT = Op.getSimpleValueType();
12888   SDLoc dl(Op);
12889
12890   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12891          Op.getValueType().getScalarType() == MVT::i1 &&
12892          "Cannot set masked compare for this operation");
12893
12894   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12895   unsigned  Opc = 0;
12896   bool Unsigned = false;
12897   bool Swap = false;
12898   unsigned SSECC;
12899   switch (SetCCOpcode) {
12900   default: llvm_unreachable("Unexpected SETCC condition");
12901   case ISD::SETNE:  SSECC = 4; break;
12902   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12903   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12904   case ISD::SETLT:  Swap = true; //fall-through
12905   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12906   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12907   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12908   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12909   case ISD::SETULE: Unsigned = true; //fall-through
12910   case ISD::SETLE:  SSECC = 2; break;
12911   }
12912
12913   if (Swap)
12914     std::swap(Op0, Op1);
12915   if (Opc)
12916     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12917   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12918   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12919                      DAG.getConstant(SSECC, MVT::i8));
12920 }
12921
12922 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12923 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12924 /// return an empty value.
12925 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12926 {
12927   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12928   if (!BV)
12929     return SDValue();
12930
12931   MVT VT = Op1.getSimpleValueType();
12932   MVT EVT = VT.getVectorElementType();
12933   unsigned n = VT.getVectorNumElements();
12934   SmallVector<SDValue, 8> ULTOp1;
12935
12936   for (unsigned i = 0; i < n; ++i) {
12937     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12938     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12939       return SDValue();
12940
12941     // Avoid underflow.
12942     APInt Val = Elt->getAPIntValue();
12943     if (Val == 0)
12944       return SDValue();
12945
12946     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12947   }
12948
12949   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12950 }
12951
12952 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12953                            SelectionDAG &DAG) {
12954   SDValue Op0 = Op.getOperand(0);
12955   SDValue Op1 = Op.getOperand(1);
12956   SDValue CC = Op.getOperand(2);
12957   MVT VT = Op.getSimpleValueType();
12958   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12959   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12960   SDLoc dl(Op);
12961
12962   if (isFP) {
12963 #ifndef NDEBUG
12964     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12965     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12966 #endif
12967
12968     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12969     unsigned Opc = X86ISD::CMPP;
12970     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12971       assert(VT.getVectorNumElements() <= 16);
12972       Opc = X86ISD::CMPM;
12973     }
12974     // In the two special cases we can't handle, emit two comparisons.
12975     if (SSECC == 8) {
12976       unsigned CC0, CC1;
12977       unsigned CombineOpc;
12978       if (SetCCOpcode == ISD::SETUEQ) {
12979         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12980       } else {
12981         assert(SetCCOpcode == ISD::SETONE);
12982         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12983       }
12984
12985       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12986                                  DAG.getConstant(CC0, MVT::i8));
12987       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12988                                  DAG.getConstant(CC1, MVT::i8));
12989       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12990     }
12991     // Handle all other FP comparisons here.
12992     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12993                        DAG.getConstant(SSECC, MVT::i8));
12994   }
12995
12996   // Break 256-bit integer vector compare into smaller ones.
12997   if (VT.is256BitVector() && !Subtarget->hasInt256())
12998     return Lower256IntVSETCC(Op, DAG);
12999
13000   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13001   EVT OpVT = Op1.getValueType();
13002   if (Subtarget->hasAVX512()) {
13003     if (Op1.getValueType().is512BitVector() ||
13004         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13005         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13006       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13007
13008     // In AVX-512 architecture setcc returns mask with i1 elements,
13009     // But there is no compare instruction for i8 and i16 elements in KNL.
13010     // We are not talking about 512-bit operands in this case, these
13011     // types are illegal.
13012     if (MaskResult &&
13013         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13014          OpVT.getVectorElementType().getSizeInBits() >= 8))
13015       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13016                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13017   }
13018
13019   // We are handling one of the integer comparisons here.  Since SSE only has
13020   // GT and EQ comparisons for integer, swapping operands and multiple
13021   // operations may be required for some comparisons.
13022   unsigned Opc;
13023   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13024   bool Subus = false;
13025
13026   switch (SetCCOpcode) {
13027   default: llvm_unreachable("Unexpected SETCC condition");
13028   case ISD::SETNE:  Invert = true;
13029   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13030   case ISD::SETLT:  Swap = true;
13031   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13032   case ISD::SETGE:  Swap = true;
13033   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13034                     Invert = true; break;
13035   case ISD::SETULT: Swap = true;
13036   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13037                     FlipSigns = true; break;
13038   case ISD::SETUGE: Swap = true;
13039   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13040                     FlipSigns = true; Invert = true; break;
13041   }
13042
13043   // Special case: Use min/max operations for SETULE/SETUGE
13044   MVT VET = VT.getVectorElementType();
13045   bool hasMinMax =
13046        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13047     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13048
13049   if (hasMinMax) {
13050     switch (SetCCOpcode) {
13051     default: break;
13052     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13053     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13054     }
13055
13056     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13057   }
13058
13059   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13060   if (!MinMax && hasSubus) {
13061     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13062     // Op0 u<= Op1:
13063     //   t = psubus Op0, Op1
13064     //   pcmpeq t, <0..0>
13065     switch (SetCCOpcode) {
13066     default: break;
13067     case ISD::SETULT: {
13068       // If the comparison is against a constant we can turn this into a
13069       // setule.  With psubus, setule does not require a swap.  This is
13070       // beneficial because the constant in the register is no longer
13071       // destructed as the destination so it can be hoisted out of a loop.
13072       // Only do this pre-AVX since vpcmp* is no longer destructive.
13073       if (Subtarget->hasAVX())
13074         break;
13075       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13076       if (ULEOp1.getNode()) {
13077         Op1 = ULEOp1;
13078         Subus = true; Invert = false; Swap = false;
13079       }
13080       break;
13081     }
13082     // Psubus is better than flip-sign because it requires no inversion.
13083     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13084     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13085     }
13086
13087     if (Subus) {
13088       Opc = X86ISD::SUBUS;
13089       FlipSigns = false;
13090     }
13091   }
13092
13093   if (Swap)
13094     std::swap(Op0, Op1);
13095
13096   // Check that the operation in question is available (most are plain SSE2,
13097   // but PCMPGTQ and PCMPEQQ have different requirements).
13098   if (VT == MVT::v2i64) {
13099     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13100       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13101
13102       // First cast everything to the right type.
13103       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13104       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13105
13106       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13107       // bits of the inputs before performing those operations. The lower
13108       // compare is always unsigned.
13109       SDValue SB;
13110       if (FlipSigns) {
13111         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13112       } else {
13113         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13114         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13115         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13116                          Sign, Zero, Sign, Zero);
13117       }
13118       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13119       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13120
13121       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13122       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13123       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13124
13125       // Create masks for only the low parts/high parts of the 64 bit integers.
13126       static const int MaskHi[] = { 1, 1, 3, 3 };
13127       static const int MaskLo[] = { 0, 0, 2, 2 };
13128       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13129       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13130       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13131
13132       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13133       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13134
13135       if (Invert)
13136         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13137
13138       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13139     }
13140
13141     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13142       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13143       // pcmpeqd + pshufd + pand.
13144       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13145
13146       // First cast everything to the right type.
13147       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13148       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13149
13150       // Do the compare.
13151       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13152
13153       // Make sure the lower and upper halves are both all-ones.
13154       static const int Mask[] = { 1, 0, 3, 2 };
13155       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13156       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13157
13158       if (Invert)
13159         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13160
13161       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13162     }
13163   }
13164
13165   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13166   // bits of the inputs before performing those operations.
13167   if (FlipSigns) {
13168     EVT EltVT = VT.getVectorElementType();
13169     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13170     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13171     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13172   }
13173
13174   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13175
13176   // If the logical-not of the result is required, perform that now.
13177   if (Invert)
13178     Result = DAG.getNOT(dl, Result, VT);
13179
13180   if (MinMax)
13181     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13182
13183   if (Subus)
13184     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13185                          getZeroVector(VT, Subtarget, DAG, dl));
13186
13187   return Result;
13188 }
13189
13190 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13191
13192   MVT VT = Op.getSimpleValueType();
13193
13194   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13195
13196   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13197          && "SetCC type must be 8-bit or 1-bit integer");
13198   SDValue Op0 = Op.getOperand(0);
13199   SDValue Op1 = Op.getOperand(1);
13200   SDLoc dl(Op);
13201   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13202
13203   // Optimize to BT if possible.
13204   // Lower (X & (1 << N)) == 0 to BT(X, N).
13205   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13206   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13207   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13208       Op1.getOpcode() == ISD::Constant &&
13209       cast<ConstantSDNode>(Op1)->isNullValue() &&
13210       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13211     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13212     if (NewSetCC.getNode())
13213       return NewSetCC;
13214   }
13215
13216   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13217   // these.
13218   if (Op1.getOpcode() == ISD::Constant &&
13219       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13220        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13221       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13222
13223     // If the input is a setcc, then reuse the input setcc or use a new one with
13224     // the inverted condition.
13225     if (Op0.getOpcode() == X86ISD::SETCC) {
13226       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13227       bool Invert = (CC == ISD::SETNE) ^
13228         cast<ConstantSDNode>(Op1)->isNullValue();
13229       if (!Invert)
13230         return Op0;
13231
13232       CCode = X86::GetOppositeBranchCondition(CCode);
13233       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13234                                   DAG.getConstant(CCode, MVT::i8),
13235                                   Op0.getOperand(1));
13236       if (VT == MVT::i1)
13237         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13238       return SetCC;
13239     }
13240   }
13241   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13242       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13243       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13244
13245     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13246     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13247   }
13248
13249   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13250   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13251   if (X86CC == X86::COND_INVALID)
13252     return SDValue();
13253
13254   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13255   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13256   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13257                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13258   if (VT == MVT::i1)
13259     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13260   return SetCC;
13261 }
13262
13263 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13264 static bool isX86LogicalCmp(SDValue Op) {
13265   unsigned Opc = Op.getNode()->getOpcode();
13266   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13267       Opc == X86ISD::SAHF)
13268     return true;
13269   if (Op.getResNo() == 1 &&
13270       (Opc == X86ISD::ADD ||
13271        Opc == X86ISD::SUB ||
13272        Opc == X86ISD::ADC ||
13273        Opc == X86ISD::SBB ||
13274        Opc == X86ISD::SMUL ||
13275        Opc == X86ISD::UMUL ||
13276        Opc == X86ISD::INC ||
13277        Opc == X86ISD::DEC ||
13278        Opc == X86ISD::OR ||
13279        Opc == X86ISD::XOR ||
13280        Opc == X86ISD::AND))
13281     return true;
13282
13283   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13284     return true;
13285
13286   return false;
13287 }
13288
13289 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13290   if (V.getOpcode() != ISD::TRUNCATE)
13291     return false;
13292
13293   SDValue VOp0 = V.getOperand(0);
13294   unsigned InBits = VOp0.getValueSizeInBits();
13295   unsigned Bits = V.getValueSizeInBits();
13296   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13297 }
13298
13299 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13300   bool addTest = true;
13301   SDValue Cond  = Op.getOperand(0);
13302   SDValue Op1 = Op.getOperand(1);
13303   SDValue Op2 = Op.getOperand(2);
13304   SDLoc DL(Op);
13305   EVT VT = Op1.getValueType();
13306   SDValue CC;
13307
13308   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13309   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13310   // sequence later on.
13311   if (Cond.getOpcode() == ISD::SETCC &&
13312       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13313        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13314       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13315     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13316     int SSECC = translateX86FSETCC(
13317         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13318
13319     if (SSECC != 8) {
13320       if (Subtarget->hasAVX512()) {
13321         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13322                                   DAG.getConstant(SSECC, MVT::i8));
13323         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13324       }
13325       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13326                                 DAG.getConstant(SSECC, MVT::i8));
13327       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13328       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13329       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13330     }
13331   }
13332
13333   if (Cond.getOpcode() == ISD::SETCC) {
13334     SDValue NewCond = LowerSETCC(Cond, DAG);
13335     if (NewCond.getNode())
13336       Cond = NewCond;
13337   }
13338
13339   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13340   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13341   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13342   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13343   if (Cond.getOpcode() == X86ISD::SETCC &&
13344       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13345       isZero(Cond.getOperand(1).getOperand(1))) {
13346     SDValue Cmp = Cond.getOperand(1);
13347
13348     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13349
13350     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13351         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13352       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13353
13354       SDValue CmpOp0 = Cmp.getOperand(0);
13355       // Apply further optimizations for special cases
13356       // (select (x != 0), -1, 0) -> neg & sbb
13357       // (select (x == 0), 0, -1) -> neg & sbb
13358       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13359         if (YC->isNullValue() &&
13360             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13361           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13362           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13363                                     DAG.getConstant(0, CmpOp0.getValueType()),
13364                                     CmpOp0);
13365           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13366                                     DAG.getConstant(X86::COND_B, MVT::i8),
13367                                     SDValue(Neg.getNode(), 1));
13368           return Res;
13369         }
13370
13371       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13372                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13373       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13374
13375       SDValue Res =   // Res = 0 or -1.
13376         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13377                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13378
13379       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13380         Res = DAG.getNOT(DL, Res, Res.getValueType());
13381
13382       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13383       if (!N2C || !N2C->isNullValue())
13384         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13385       return Res;
13386     }
13387   }
13388
13389   // Look past (and (setcc_carry (cmp ...)), 1).
13390   if (Cond.getOpcode() == ISD::AND &&
13391       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13392     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13393     if (C && C->getAPIntValue() == 1)
13394       Cond = Cond.getOperand(0);
13395   }
13396
13397   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13398   // setting operand in place of the X86ISD::SETCC.
13399   unsigned CondOpcode = Cond.getOpcode();
13400   if (CondOpcode == X86ISD::SETCC ||
13401       CondOpcode == X86ISD::SETCC_CARRY) {
13402     CC = Cond.getOperand(0);
13403
13404     SDValue Cmp = Cond.getOperand(1);
13405     unsigned Opc = Cmp.getOpcode();
13406     MVT VT = Op.getSimpleValueType();
13407
13408     bool IllegalFPCMov = false;
13409     if (VT.isFloatingPoint() && !VT.isVector() &&
13410         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13411       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13412
13413     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13414         Opc == X86ISD::BT) { // FIXME
13415       Cond = Cmp;
13416       addTest = false;
13417     }
13418   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13419              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13420              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13421               Cond.getOperand(0).getValueType() != MVT::i8)) {
13422     SDValue LHS = Cond.getOperand(0);
13423     SDValue RHS = Cond.getOperand(1);
13424     unsigned X86Opcode;
13425     unsigned X86Cond;
13426     SDVTList VTs;
13427     switch (CondOpcode) {
13428     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13429     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13430     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13431     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13432     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13433     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13434     default: llvm_unreachable("unexpected overflowing operator");
13435     }
13436     if (CondOpcode == ISD::UMULO)
13437       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13438                           MVT::i32);
13439     else
13440       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13441
13442     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13443
13444     if (CondOpcode == ISD::UMULO)
13445       Cond = X86Op.getValue(2);
13446     else
13447       Cond = X86Op.getValue(1);
13448
13449     CC = DAG.getConstant(X86Cond, MVT::i8);
13450     addTest = false;
13451   }
13452
13453   if (addTest) {
13454     // Look pass the truncate if the high bits are known zero.
13455     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13456         Cond = Cond.getOperand(0);
13457
13458     // We know the result of AND is compared against zero. Try to match
13459     // it to BT.
13460     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13461       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13462       if (NewSetCC.getNode()) {
13463         CC = NewSetCC.getOperand(0);
13464         Cond = NewSetCC.getOperand(1);
13465         addTest = false;
13466       }
13467     }
13468   }
13469
13470   if (addTest) {
13471     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13472     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13473   }
13474
13475   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13476   // a <  b ?  0 : -1 -> RES = setcc_carry
13477   // a >= b ? -1 :  0 -> RES = setcc_carry
13478   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13479   if (Cond.getOpcode() == X86ISD::SUB) {
13480     Cond = ConvertCmpIfNecessary(Cond, DAG);
13481     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13482
13483     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13484         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13485       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13486                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13487       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13488         return DAG.getNOT(DL, Res, Res.getValueType());
13489       return Res;
13490     }
13491   }
13492
13493   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13494   // widen the cmov and push the truncate through. This avoids introducing a new
13495   // branch during isel and doesn't add any extensions.
13496   if (Op.getValueType() == MVT::i8 &&
13497       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13498     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13499     if (T1.getValueType() == T2.getValueType() &&
13500         // Blacklist CopyFromReg to avoid partial register stalls.
13501         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13502       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13503       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13504       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13505     }
13506   }
13507
13508   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13509   // condition is true.
13510   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13511   SDValue Ops[] = { Op2, Op1, CC, Cond };
13512   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13513 }
13514
13515 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13516   MVT VT = Op->getSimpleValueType(0);
13517   SDValue In = Op->getOperand(0);
13518   MVT InVT = In.getSimpleValueType();
13519   SDLoc dl(Op);
13520
13521   unsigned int NumElts = VT.getVectorNumElements();
13522   if (NumElts != 8 && NumElts != 16)
13523     return SDValue();
13524
13525   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13526     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13527
13528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13529   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13530
13531   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13532   Constant *C = ConstantInt::get(*DAG.getContext(),
13533     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13534
13535   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13536   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13537   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13538                           MachinePointerInfo::getConstantPool(),
13539                           false, false, false, Alignment);
13540   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13541   if (VT.is512BitVector())
13542     return Brcst;
13543   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13544 }
13545
13546 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13547                                 SelectionDAG &DAG) {
13548   MVT VT = Op->getSimpleValueType(0);
13549   SDValue In = Op->getOperand(0);
13550   MVT InVT = In.getSimpleValueType();
13551   SDLoc dl(Op);
13552
13553   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13554     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13555
13556   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13557       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13558       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13559     return SDValue();
13560
13561   if (Subtarget->hasInt256())
13562     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13563
13564   // Optimize vectors in AVX mode
13565   // Sign extend  v8i16 to v8i32 and
13566   //              v4i32 to v4i64
13567   //
13568   // Divide input vector into two parts
13569   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13570   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13571   // concat the vectors to original VT
13572
13573   unsigned NumElems = InVT.getVectorNumElements();
13574   SDValue Undef = DAG.getUNDEF(InVT);
13575
13576   SmallVector<int,8> ShufMask1(NumElems, -1);
13577   for (unsigned i = 0; i != NumElems/2; ++i)
13578     ShufMask1[i] = i;
13579
13580   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13581
13582   SmallVector<int,8> ShufMask2(NumElems, -1);
13583   for (unsigned i = 0; i != NumElems/2; ++i)
13584     ShufMask2[i] = i + NumElems/2;
13585
13586   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13587
13588   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13589                                 VT.getVectorNumElements()/2);
13590
13591   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13592   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13593
13594   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13595 }
13596
13597 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13598 // may emit an illegal shuffle but the expansion is still better than scalar
13599 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13600 // we'll emit a shuffle and a arithmetic shift.
13601 // TODO: It is possible to support ZExt by zeroing the undef values during
13602 // the shuffle phase or after the shuffle.
13603 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13604                                  SelectionDAG &DAG) {
13605   MVT RegVT = Op.getSimpleValueType();
13606   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13607   assert(RegVT.isInteger() &&
13608          "We only custom lower integer vector sext loads.");
13609
13610   // Nothing useful we can do without SSE2 shuffles.
13611   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13612
13613   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13614   SDLoc dl(Ld);
13615   EVT MemVT = Ld->getMemoryVT();
13616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13617   unsigned RegSz = RegVT.getSizeInBits();
13618
13619   ISD::LoadExtType Ext = Ld->getExtensionType();
13620
13621   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13622          && "Only anyext and sext are currently implemented.");
13623   assert(MemVT != RegVT && "Cannot extend to the same type");
13624   assert(MemVT.isVector() && "Must load a vector from memory");
13625
13626   unsigned NumElems = RegVT.getVectorNumElements();
13627   unsigned MemSz = MemVT.getSizeInBits();
13628   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13629
13630   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13631     // The only way in which we have a legal 256-bit vector result but not the
13632     // integer 256-bit operations needed to directly lower a sextload is if we
13633     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13634     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13635     // correctly legalized. We do this late to allow the canonical form of
13636     // sextload to persist throughout the rest of the DAG combiner -- it wants
13637     // to fold together any extensions it can, and so will fuse a sign_extend
13638     // of an sextload into a sextload targeting a wider value.
13639     SDValue Load;
13640     if (MemSz == 128) {
13641       // Just switch this to a normal load.
13642       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13643                                        "it must be a legal 128-bit vector "
13644                                        "type!");
13645       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13646                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13647                   Ld->isInvariant(), Ld->getAlignment());
13648     } else {
13649       assert(MemSz < 128 &&
13650              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13651       // Do an sext load to a 128-bit vector type. We want to use the same
13652       // number of elements, but elements half as wide. This will end up being
13653       // recursively lowered by this routine, but will succeed as we definitely
13654       // have all the necessary features if we're using AVX1.
13655       EVT HalfEltVT =
13656           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13657       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13658       Load =
13659           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13660                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13661                          Ld->isNonTemporal(), Ld->isInvariant(),
13662                          Ld->getAlignment());
13663     }
13664
13665     // Replace chain users with the new chain.
13666     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13667     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13668
13669     // Finally, do a normal sign-extend to the desired register.
13670     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13671   }
13672
13673   // All sizes must be a power of two.
13674   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13675          "Non-power-of-two elements are not custom lowered!");
13676
13677   // Attempt to load the original value using scalar loads.
13678   // Find the largest scalar type that divides the total loaded size.
13679   MVT SclrLoadTy = MVT::i8;
13680   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13681        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13682     MVT Tp = (MVT::SimpleValueType)tp;
13683     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13684       SclrLoadTy = Tp;
13685     }
13686   }
13687
13688   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13689   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13690       (64 <= MemSz))
13691     SclrLoadTy = MVT::f64;
13692
13693   // Calculate the number of scalar loads that we need to perform
13694   // in order to load our vector from memory.
13695   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13696
13697   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13698          "Can only lower sext loads with a single scalar load!");
13699
13700   unsigned loadRegZize = RegSz;
13701   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13702     loadRegZize /= 2;
13703
13704   // Represent our vector as a sequence of elements which are the
13705   // largest scalar that we can load.
13706   EVT LoadUnitVecVT = EVT::getVectorVT(
13707       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13708
13709   // Represent the data using the same element type that is stored in
13710   // memory. In practice, we ''widen'' MemVT.
13711   EVT WideVecVT =
13712       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13713                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13714
13715   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13716          "Invalid vector type");
13717
13718   // We can't shuffle using an illegal type.
13719   assert(TLI.isTypeLegal(WideVecVT) &&
13720          "We only lower types that form legal widened vector types");
13721
13722   SmallVector<SDValue, 8> Chains;
13723   SDValue Ptr = Ld->getBasePtr();
13724   SDValue Increment =
13725       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13726   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13727
13728   for (unsigned i = 0; i < NumLoads; ++i) {
13729     // Perform a single load.
13730     SDValue ScalarLoad =
13731         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13732                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13733                     Ld->getAlignment());
13734     Chains.push_back(ScalarLoad.getValue(1));
13735     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13736     // another round of DAGCombining.
13737     if (i == 0)
13738       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13739     else
13740       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13741                         ScalarLoad, DAG.getIntPtrConstant(i));
13742
13743     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13744   }
13745
13746   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13747
13748   // Bitcast the loaded value to a vector of the original element type, in
13749   // the size of the target vector type.
13750   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13751   unsigned SizeRatio = RegSz / MemSz;
13752
13753   if (Ext == ISD::SEXTLOAD) {
13754     // If we have SSE4.1, we can directly emit a VSEXT node.
13755     if (Subtarget->hasSSE41()) {
13756       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13757       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13758       return Sext;
13759     }
13760
13761     // Otherwise we'll shuffle the small elements in the high bits of the
13762     // larger type and perform an arithmetic shift. If the shift is not legal
13763     // it's better to scalarize.
13764     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13765            "We can't implement a sext load without an arithmetic right shift!");
13766
13767     // Redistribute the loaded elements into the different locations.
13768     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13769     for (unsigned i = 0; i != NumElems; ++i)
13770       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13771
13772     SDValue Shuff = DAG.getVectorShuffle(
13773         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13774
13775     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13776
13777     // Build the arithmetic shift.
13778     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13779                    MemVT.getVectorElementType().getSizeInBits();
13780     Shuff =
13781         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13782
13783     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13784     return Shuff;
13785   }
13786
13787   // Redistribute the loaded elements into the different locations.
13788   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13789   for (unsigned i = 0; i != NumElems; ++i)
13790     ShuffleVec[i * SizeRatio] = i;
13791
13792   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13793                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13794
13795   // Bitcast to the requested type.
13796   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13797   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13798   return Shuff;
13799 }
13800
13801 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13802 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13803 // from the AND / OR.
13804 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13805   Opc = Op.getOpcode();
13806   if (Opc != ISD::OR && Opc != ISD::AND)
13807     return false;
13808   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13809           Op.getOperand(0).hasOneUse() &&
13810           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13811           Op.getOperand(1).hasOneUse());
13812 }
13813
13814 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13815 // 1 and that the SETCC node has a single use.
13816 static bool isXor1OfSetCC(SDValue Op) {
13817   if (Op.getOpcode() != ISD::XOR)
13818     return false;
13819   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13820   if (N1C && N1C->getAPIntValue() == 1) {
13821     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13822       Op.getOperand(0).hasOneUse();
13823   }
13824   return false;
13825 }
13826
13827 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13828   bool addTest = true;
13829   SDValue Chain = Op.getOperand(0);
13830   SDValue Cond  = Op.getOperand(1);
13831   SDValue Dest  = Op.getOperand(2);
13832   SDLoc dl(Op);
13833   SDValue CC;
13834   bool Inverted = false;
13835
13836   if (Cond.getOpcode() == ISD::SETCC) {
13837     // Check for setcc([su]{add,sub,mul}o == 0).
13838     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13839         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13840         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13841         Cond.getOperand(0).getResNo() == 1 &&
13842         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13843          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13844          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13845          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13846          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13847          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13848       Inverted = true;
13849       Cond = Cond.getOperand(0);
13850     } else {
13851       SDValue NewCond = LowerSETCC(Cond, DAG);
13852       if (NewCond.getNode())
13853         Cond = NewCond;
13854     }
13855   }
13856 #if 0
13857   // FIXME: LowerXALUO doesn't handle these!!
13858   else if (Cond.getOpcode() == X86ISD::ADD  ||
13859            Cond.getOpcode() == X86ISD::SUB  ||
13860            Cond.getOpcode() == X86ISD::SMUL ||
13861            Cond.getOpcode() == X86ISD::UMUL)
13862     Cond = LowerXALUO(Cond, DAG);
13863 #endif
13864
13865   // Look pass (and (setcc_carry (cmp ...)), 1).
13866   if (Cond.getOpcode() == ISD::AND &&
13867       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13868     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13869     if (C && C->getAPIntValue() == 1)
13870       Cond = Cond.getOperand(0);
13871   }
13872
13873   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13874   // setting operand in place of the X86ISD::SETCC.
13875   unsigned CondOpcode = Cond.getOpcode();
13876   if (CondOpcode == X86ISD::SETCC ||
13877       CondOpcode == X86ISD::SETCC_CARRY) {
13878     CC = Cond.getOperand(0);
13879
13880     SDValue Cmp = Cond.getOperand(1);
13881     unsigned Opc = Cmp.getOpcode();
13882     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13883     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13884       Cond = Cmp;
13885       addTest = false;
13886     } else {
13887       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13888       default: break;
13889       case X86::COND_O:
13890       case X86::COND_B:
13891         // These can only come from an arithmetic instruction with overflow,
13892         // e.g. SADDO, UADDO.
13893         Cond = Cond.getNode()->getOperand(1);
13894         addTest = false;
13895         break;
13896       }
13897     }
13898   }
13899   CondOpcode = Cond.getOpcode();
13900   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13901       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13902       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13903        Cond.getOperand(0).getValueType() != MVT::i8)) {
13904     SDValue LHS = Cond.getOperand(0);
13905     SDValue RHS = Cond.getOperand(1);
13906     unsigned X86Opcode;
13907     unsigned X86Cond;
13908     SDVTList VTs;
13909     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13910     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13911     // X86ISD::INC).
13912     switch (CondOpcode) {
13913     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13914     case ISD::SADDO:
13915       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13916         if (C->isOne()) {
13917           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13918           break;
13919         }
13920       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13921     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13922     case ISD::SSUBO:
13923       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13924         if (C->isOne()) {
13925           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13926           break;
13927         }
13928       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13929     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13930     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13931     default: llvm_unreachable("unexpected overflowing operator");
13932     }
13933     if (Inverted)
13934       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13935     if (CondOpcode == ISD::UMULO)
13936       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13937                           MVT::i32);
13938     else
13939       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13940
13941     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13942
13943     if (CondOpcode == ISD::UMULO)
13944       Cond = X86Op.getValue(2);
13945     else
13946       Cond = X86Op.getValue(1);
13947
13948     CC = DAG.getConstant(X86Cond, MVT::i8);
13949     addTest = false;
13950   } else {
13951     unsigned CondOpc;
13952     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13953       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13954       if (CondOpc == ISD::OR) {
13955         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13956         // two branches instead of an explicit OR instruction with a
13957         // separate test.
13958         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13959             isX86LogicalCmp(Cmp)) {
13960           CC = Cond.getOperand(0).getOperand(0);
13961           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13962                               Chain, Dest, CC, Cmp);
13963           CC = Cond.getOperand(1).getOperand(0);
13964           Cond = Cmp;
13965           addTest = false;
13966         }
13967       } else { // ISD::AND
13968         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13969         // two branches instead of an explicit AND instruction with a
13970         // separate test. However, we only do this if this block doesn't
13971         // have a fall-through edge, because this requires an explicit
13972         // jmp when the condition is false.
13973         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13974             isX86LogicalCmp(Cmp) &&
13975             Op.getNode()->hasOneUse()) {
13976           X86::CondCode CCode =
13977             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13978           CCode = X86::GetOppositeBranchCondition(CCode);
13979           CC = DAG.getConstant(CCode, MVT::i8);
13980           SDNode *User = *Op.getNode()->use_begin();
13981           // Look for an unconditional branch following this conditional branch.
13982           // We need this because we need to reverse the successors in order
13983           // to implement FCMP_OEQ.
13984           if (User->getOpcode() == ISD::BR) {
13985             SDValue FalseBB = User->getOperand(1);
13986             SDNode *NewBR =
13987               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13988             assert(NewBR == User);
13989             (void)NewBR;
13990             Dest = FalseBB;
13991
13992             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13993                                 Chain, Dest, CC, Cmp);
13994             X86::CondCode CCode =
13995               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13996             CCode = X86::GetOppositeBranchCondition(CCode);
13997             CC = DAG.getConstant(CCode, MVT::i8);
13998             Cond = Cmp;
13999             addTest = false;
14000           }
14001         }
14002       }
14003     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14004       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14005       // It should be transformed during dag combiner except when the condition
14006       // is set by a arithmetics with overflow node.
14007       X86::CondCode CCode =
14008         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14009       CCode = X86::GetOppositeBranchCondition(CCode);
14010       CC = DAG.getConstant(CCode, MVT::i8);
14011       Cond = Cond.getOperand(0).getOperand(1);
14012       addTest = false;
14013     } else if (Cond.getOpcode() == ISD::SETCC &&
14014                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14015       // For FCMP_OEQ, we can emit
14016       // two branches instead of an explicit AND instruction with a
14017       // separate test. However, we only do this if this block doesn't
14018       // have a fall-through edge, because this requires an explicit
14019       // jmp when the condition is false.
14020       if (Op.getNode()->hasOneUse()) {
14021         SDNode *User = *Op.getNode()->use_begin();
14022         // Look for an unconditional branch following this conditional branch.
14023         // We need this because we need to reverse the successors in order
14024         // to implement FCMP_OEQ.
14025         if (User->getOpcode() == ISD::BR) {
14026           SDValue FalseBB = User->getOperand(1);
14027           SDNode *NewBR =
14028             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14029           assert(NewBR == User);
14030           (void)NewBR;
14031           Dest = FalseBB;
14032
14033           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14034                                     Cond.getOperand(0), Cond.getOperand(1));
14035           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14036           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14037           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14038                               Chain, Dest, CC, Cmp);
14039           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14040           Cond = Cmp;
14041           addTest = false;
14042         }
14043       }
14044     } else if (Cond.getOpcode() == ISD::SETCC &&
14045                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14046       // For FCMP_UNE, we can emit
14047       // two branches instead of an explicit AND instruction with a
14048       // separate test. However, we only do this if this block doesn't
14049       // have a fall-through edge, because this requires an explicit
14050       // jmp when the condition is false.
14051       if (Op.getNode()->hasOneUse()) {
14052         SDNode *User = *Op.getNode()->use_begin();
14053         // Look for an unconditional branch following this conditional branch.
14054         // We need this because we need to reverse the successors in order
14055         // to implement FCMP_UNE.
14056         if (User->getOpcode() == ISD::BR) {
14057           SDValue FalseBB = User->getOperand(1);
14058           SDNode *NewBR =
14059             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14060           assert(NewBR == User);
14061           (void)NewBR;
14062
14063           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14064                                     Cond.getOperand(0), Cond.getOperand(1));
14065           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14066           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14067           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14068                               Chain, Dest, CC, Cmp);
14069           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14070           Cond = Cmp;
14071           addTest = false;
14072           Dest = FalseBB;
14073         }
14074       }
14075     }
14076   }
14077
14078   if (addTest) {
14079     // Look pass the truncate if the high bits are known zero.
14080     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14081         Cond = Cond.getOperand(0);
14082
14083     // We know the result of AND is compared against zero. Try to match
14084     // it to BT.
14085     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14086       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14087       if (NewSetCC.getNode()) {
14088         CC = NewSetCC.getOperand(0);
14089         Cond = NewSetCC.getOperand(1);
14090         addTest = false;
14091       }
14092     }
14093   }
14094
14095   if (addTest) {
14096     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14097     CC = DAG.getConstant(X86Cond, MVT::i8);
14098     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14099   }
14100   Cond = ConvertCmpIfNecessary(Cond, DAG);
14101   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14102                      Chain, Dest, CC, Cond);
14103 }
14104
14105 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14106 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14107 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14108 // that the guard pages used by the OS virtual memory manager are allocated in
14109 // correct sequence.
14110 SDValue
14111 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14112                                            SelectionDAG &DAG) const {
14113   MachineFunction &MF = DAG.getMachineFunction();
14114   bool SplitStack = MF.shouldSplitStack();
14115   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14116                SplitStack;
14117   SDLoc dl(Op);
14118
14119   if (!Lower) {
14120     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14121     SDNode* Node = Op.getNode();
14122
14123     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14124     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14125         " not tell us which reg is the stack pointer!");
14126     EVT VT = Node->getValueType(0);
14127     SDValue Tmp1 = SDValue(Node, 0);
14128     SDValue Tmp2 = SDValue(Node, 1);
14129     SDValue Tmp3 = Node->getOperand(2);
14130     SDValue Chain = Tmp1.getOperand(0);
14131
14132     // Chain the dynamic stack allocation so that it doesn't modify the stack
14133     // pointer when other instructions are using the stack.
14134     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14135         SDLoc(Node));
14136
14137     SDValue Size = Tmp2.getOperand(1);
14138     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14139     Chain = SP.getValue(1);
14140     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14141     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14142     unsigned StackAlign = TFI.getStackAlignment();
14143     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14144     if (Align > StackAlign)
14145       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14146           DAG.getConstant(-(uint64_t)Align, VT));
14147     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14148
14149     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14150         DAG.getIntPtrConstant(0, true), SDValue(),
14151         SDLoc(Node));
14152
14153     SDValue Ops[2] = { Tmp1, Tmp2 };
14154     return DAG.getMergeValues(Ops, dl);
14155   }
14156
14157   // Get the inputs.
14158   SDValue Chain = Op.getOperand(0);
14159   SDValue Size  = Op.getOperand(1);
14160   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14161   EVT VT = Op.getNode()->getValueType(0);
14162
14163   bool Is64Bit = Subtarget->is64Bit();
14164   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14165
14166   if (SplitStack) {
14167     MachineRegisterInfo &MRI = MF.getRegInfo();
14168
14169     if (Is64Bit) {
14170       // The 64 bit implementation of segmented stacks needs to clobber both r10
14171       // r11. This makes it impossible to use it along with nested parameters.
14172       const Function *F = MF.getFunction();
14173
14174       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14175            I != E; ++I)
14176         if (I->hasNestAttr())
14177           report_fatal_error("Cannot use segmented stacks with functions that "
14178                              "have nested arguments.");
14179     }
14180
14181     const TargetRegisterClass *AddrRegClass =
14182       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14183     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14184     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14185     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14186                                 DAG.getRegister(Vreg, SPTy));
14187     SDValue Ops1[2] = { Value, Chain };
14188     return DAG.getMergeValues(Ops1, dl);
14189   } else {
14190     SDValue Flag;
14191     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14192
14193     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14194     Flag = Chain.getValue(1);
14195     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14196
14197     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14198
14199     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14200         DAG.getSubtarget().getRegisterInfo());
14201     unsigned SPReg = RegInfo->getStackRegister();
14202     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14203     Chain = SP.getValue(1);
14204
14205     if (Align) {
14206       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14207                        DAG.getConstant(-(uint64_t)Align, VT));
14208       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14209     }
14210
14211     SDValue Ops1[2] = { SP, Chain };
14212     return DAG.getMergeValues(Ops1, dl);
14213   }
14214 }
14215
14216 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14217   MachineFunction &MF = DAG.getMachineFunction();
14218   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14219
14220   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14221   SDLoc DL(Op);
14222
14223   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14224     // vastart just stores the address of the VarArgsFrameIndex slot into the
14225     // memory location argument.
14226     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14227                                    getPointerTy());
14228     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14229                         MachinePointerInfo(SV), false, false, 0);
14230   }
14231
14232   // __va_list_tag:
14233   //   gp_offset         (0 - 6 * 8)
14234   //   fp_offset         (48 - 48 + 8 * 16)
14235   //   overflow_arg_area (point to parameters coming in memory).
14236   //   reg_save_area
14237   SmallVector<SDValue, 8> MemOps;
14238   SDValue FIN = Op.getOperand(1);
14239   // Store gp_offset
14240   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14241                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14242                                                MVT::i32),
14243                                FIN, MachinePointerInfo(SV), false, false, 0);
14244   MemOps.push_back(Store);
14245
14246   // Store fp_offset
14247   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14248                     FIN, DAG.getIntPtrConstant(4));
14249   Store = DAG.getStore(Op.getOperand(0), DL,
14250                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14251                                        MVT::i32),
14252                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14253   MemOps.push_back(Store);
14254
14255   // Store ptr to overflow_arg_area
14256   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14257                     FIN, DAG.getIntPtrConstant(4));
14258   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14259                                     getPointerTy());
14260   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14261                        MachinePointerInfo(SV, 8),
14262                        false, false, 0);
14263   MemOps.push_back(Store);
14264
14265   // Store ptr to reg_save_area.
14266   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14267                     FIN, DAG.getIntPtrConstant(8));
14268   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14269                                     getPointerTy());
14270   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14271                        MachinePointerInfo(SV, 16), false, false, 0);
14272   MemOps.push_back(Store);
14273   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14274 }
14275
14276 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14277   assert(Subtarget->is64Bit() &&
14278          "LowerVAARG only handles 64-bit va_arg!");
14279   assert((Subtarget->isTargetLinux() ||
14280           Subtarget->isTargetDarwin()) &&
14281           "Unhandled target in LowerVAARG");
14282   assert(Op.getNode()->getNumOperands() == 4);
14283   SDValue Chain = Op.getOperand(0);
14284   SDValue SrcPtr = Op.getOperand(1);
14285   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14286   unsigned Align = Op.getConstantOperandVal(3);
14287   SDLoc dl(Op);
14288
14289   EVT ArgVT = Op.getNode()->getValueType(0);
14290   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14291   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14292   uint8_t ArgMode;
14293
14294   // Decide which area this value should be read from.
14295   // TODO: Implement the AMD64 ABI in its entirety. This simple
14296   // selection mechanism works only for the basic types.
14297   if (ArgVT == MVT::f80) {
14298     llvm_unreachable("va_arg for f80 not yet implemented");
14299   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14300     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14301   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14302     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14303   } else {
14304     llvm_unreachable("Unhandled argument type in LowerVAARG");
14305   }
14306
14307   if (ArgMode == 2) {
14308     // Sanity Check: Make sure using fp_offset makes sense.
14309     assert(!DAG.getTarget().Options.UseSoftFloat &&
14310            !(DAG.getMachineFunction()
14311                 .getFunction()->getAttributes()
14312                 .hasAttribute(AttributeSet::FunctionIndex,
14313                               Attribute::NoImplicitFloat)) &&
14314            Subtarget->hasSSE1());
14315   }
14316
14317   // Insert VAARG_64 node into the DAG
14318   // VAARG_64 returns two values: Variable Argument Address, Chain
14319   SmallVector<SDValue, 11> InstOps;
14320   InstOps.push_back(Chain);
14321   InstOps.push_back(SrcPtr);
14322   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14323   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14324   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14325   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14326   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14327                                           VTs, InstOps, MVT::i64,
14328                                           MachinePointerInfo(SV),
14329                                           /*Align=*/0,
14330                                           /*Volatile=*/false,
14331                                           /*ReadMem=*/true,
14332                                           /*WriteMem=*/true);
14333   Chain = VAARG.getValue(1);
14334
14335   // Load the next argument and return it
14336   return DAG.getLoad(ArgVT, dl,
14337                      Chain,
14338                      VAARG,
14339                      MachinePointerInfo(),
14340                      false, false, false, 0);
14341 }
14342
14343 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14344                            SelectionDAG &DAG) {
14345   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14346   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14347   SDValue Chain = Op.getOperand(0);
14348   SDValue DstPtr = Op.getOperand(1);
14349   SDValue SrcPtr = Op.getOperand(2);
14350   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14351   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14352   SDLoc DL(Op);
14353
14354   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14355                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14356                        false,
14357                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14358 }
14359
14360 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14361 // amount is a constant. Takes immediate version of shift as input.
14362 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14363                                           SDValue SrcOp, uint64_t ShiftAmt,
14364                                           SelectionDAG &DAG) {
14365   MVT ElementType = VT.getVectorElementType();
14366
14367   // Fold this packed shift into its first operand if ShiftAmt is 0.
14368   if (ShiftAmt == 0)
14369     return SrcOp;
14370
14371   // Check for ShiftAmt >= element width
14372   if (ShiftAmt >= ElementType.getSizeInBits()) {
14373     if (Opc == X86ISD::VSRAI)
14374       ShiftAmt = ElementType.getSizeInBits() - 1;
14375     else
14376       return DAG.getConstant(0, VT);
14377   }
14378
14379   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14380          && "Unknown target vector shift-by-constant node");
14381
14382   // Fold this packed vector shift into a build vector if SrcOp is a
14383   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14384   if (VT == SrcOp.getSimpleValueType() &&
14385       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14386     SmallVector<SDValue, 8> Elts;
14387     unsigned NumElts = SrcOp->getNumOperands();
14388     ConstantSDNode *ND;
14389
14390     switch(Opc) {
14391     default: llvm_unreachable(nullptr);
14392     case X86ISD::VSHLI:
14393       for (unsigned i=0; i!=NumElts; ++i) {
14394         SDValue CurrentOp = SrcOp->getOperand(i);
14395         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14396           Elts.push_back(CurrentOp);
14397           continue;
14398         }
14399         ND = cast<ConstantSDNode>(CurrentOp);
14400         const APInt &C = ND->getAPIntValue();
14401         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14402       }
14403       break;
14404     case X86ISD::VSRLI:
14405       for (unsigned i=0; i!=NumElts; ++i) {
14406         SDValue CurrentOp = SrcOp->getOperand(i);
14407         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14408           Elts.push_back(CurrentOp);
14409           continue;
14410         }
14411         ND = cast<ConstantSDNode>(CurrentOp);
14412         const APInt &C = ND->getAPIntValue();
14413         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14414       }
14415       break;
14416     case X86ISD::VSRAI:
14417       for (unsigned i=0; i!=NumElts; ++i) {
14418         SDValue CurrentOp = SrcOp->getOperand(i);
14419         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14420           Elts.push_back(CurrentOp);
14421           continue;
14422         }
14423         ND = cast<ConstantSDNode>(CurrentOp);
14424         const APInt &C = ND->getAPIntValue();
14425         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14426       }
14427       break;
14428     }
14429
14430     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14431   }
14432
14433   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14434 }
14435
14436 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14437 // may or may not be a constant. Takes immediate version of shift as input.
14438 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14439                                    SDValue SrcOp, SDValue ShAmt,
14440                                    SelectionDAG &DAG) {
14441   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14442
14443   // Catch shift-by-constant.
14444   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14445     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14446                                       CShAmt->getZExtValue(), DAG);
14447
14448   // Change opcode to non-immediate version
14449   switch (Opc) {
14450     default: llvm_unreachable("Unknown target vector shift node");
14451     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14452     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14453     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14454   }
14455
14456   // Need to build a vector containing shift amount
14457   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14458   SDValue ShOps[4];
14459   ShOps[0] = ShAmt;
14460   ShOps[1] = DAG.getConstant(0, MVT::i32);
14461   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14462   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14463
14464   // The return type has to be a 128-bit type with the same element
14465   // type as the input type.
14466   MVT EltVT = VT.getVectorElementType();
14467   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14468
14469   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14470   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14471 }
14472
14473 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14474 /// necessary casting for \p Mask when lowering masking intrinsics.
14475 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14476                                     SDValue PreservedSrc, SelectionDAG &DAG) {
14477     EVT VT = Op.getValueType();
14478     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14479                                   MVT::i1, VT.getVectorNumElements());
14480     SDLoc dl(Op);
14481
14482     assert(MaskVT.isSimple() && "invalid mask type");
14483     return DAG.getNode(ISD::VSELECT, dl, VT,
14484                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14485                        Op, PreservedSrc);
14486 }
14487
14488 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14489     switch (IntNo) {
14490     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14491     case Intrinsic::x86_fma_vfmadd_ps:
14492     case Intrinsic::x86_fma_vfmadd_pd:
14493     case Intrinsic::x86_fma_vfmadd_ps_256:
14494     case Intrinsic::x86_fma_vfmadd_pd_256:
14495     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14496     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14497       return X86ISD::FMADD;
14498     case Intrinsic::x86_fma_vfmsub_ps:
14499     case Intrinsic::x86_fma_vfmsub_pd:
14500     case Intrinsic::x86_fma_vfmsub_ps_256:
14501     case Intrinsic::x86_fma_vfmsub_pd_256:
14502     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14503     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14504       return X86ISD::FMSUB;
14505     case Intrinsic::x86_fma_vfnmadd_ps:
14506     case Intrinsic::x86_fma_vfnmadd_pd:
14507     case Intrinsic::x86_fma_vfnmadd_ps_256:
14508     case Intrinsic::x86_fma_vfnmadd_pd_256:
14509     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14510     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14511       return X86ISD::FNMADD;
14512     case Intrinsic::x86_fma_vfnmsub_ps:
14513     case Intrinsic::x86_fma_vfnmsub_pd:
14514     case Intrinsic::x86_fma_vfnmsub_ps_256:
14515     case Intrinsic::x86_fma_vfnmsub_pd_256:
14516     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14517     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14518       return X86ISD::FNMSUB;
14519     case Intrinsic::x86_fma_vfmaddsub_ps:
14520     case Intrinsic::x86_fma_vfmaddsub_pd:
14521     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14522     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14523     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14524     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14525       return X86ISD::FMADDSUB;
14526     case Intrinsic::x86_fma_vfmsubadd_ps:
14527     case Intrinsic::x86_fma_vfmsubadd_pd:
14528     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14529     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14530     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14531     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14532       return X86ISD::FMSUBADD;
14533     }
14534 }
14535
14536 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14537   SDLoc dl(Op);
14538   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14539
14540   const IntrinsicData* IntrData = GetIntrinsicWithoutChain(IntNo);
14541   if (IntrData) {
14542     switch(IntrData->Type) {
14543     case INTR_TYPE_1OP:
14544       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14545     case INTR_TYPE_2OP:
14546       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14547         Op.getOperand(2));
14548     case INTR_TYPE_3OP:
14549       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14550         Op.getOperand(2), Op.getOperand(3));
14551     case COMI: { // Comparison intrinsics
14552       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14553       SDValue LHS = Op.getOperand(1);
14554       SDValue RHS = Op.getOperand(2);
14555       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14556       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14557       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14558       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14559                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14560       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14561     }
14562     case VSHIFT:
14563       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14564                                  Op.getOperand(1), Op.getOperand(2), DAG);
14565     default:
14566       break;
14567     }
14568   }
14569
14570   switch (IntNo) {
14571   default: return SDValue();    // Don't custom lower most intrinsics.
14572
14573   // Arithmetic intrinsics.
14574   case Intrinsic::x86_sse2_pmulu_dq:
14575   case Intrinsic::x86_avx2_pmulu_dq:
14576     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14577                        Op.getOperand(1), Op.getOperand(2));
14578
14579   case Intrinsic::x86_sse41_pmuldq:
14580   case Intrinsic::x86_avx2_pmul_dq:
14581     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14582                        Op.getOperand(1), Op.getOperand(2));
14583
14584   case Intrinsic::x86_sse2_pmulhu_w:
14585   case Intrinsic::x86_avx2_pmulhu_w:
14586     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14587                        Op.getOperand(1), Op.getOperand(2));
14588
14589   case Intrinsic::x86_sse2_pmulh_w:
14590   case Intrinsic::x86_avx2_pmulh_w:
14591     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14592                        Op.getOperand(1), Op.getOperand(2));
14593
14594   // SSE/SSE2/AVX floating point max/min intrinsics.
14595   case Intrinsic::x86_sse_max_ps:
14596   case Intrinsic::x86_sse2_max_pd:
14597   case Intrinsic::x86_avx_max_ps_256:
14598   case Intrinsic::x86_avx_max_pd_256:
14599   case Intrinsic::x86_sse_min_ps:
14600   case Intrinsic::x86_sse2_min_pd:
14601   case Intrinsic::x86_avx_min_ps_256:
14602   case Intrinsic::x86_avx_min_pd_256: {
14603     unsigned Opcode;
14604     switch (IntNo) {
14605     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14606     case Intrinsic::x86_sse_max_ps:
14607     case Intrinsic::x86_sse2_max_pd:
14608     case Intrinsic::x86_avx_max_ps_256:
14609     case Intrinsic::x86_avx_max_pd_256:
14610       Opcode = X86ISD::FMAX;
14611       break;
14612     case Intrinsic::x86_sse_min_ps:
14613     case Intrinsic::x86_sse2_min_pd:
14614     case Intrinsic::x86_avx_min_ps_256:
14615     case Intrinsic::x86_avx_min_pd_256:
14616       Opcode = X86ISD::FMIN;
14617       break;
14618     }
14619     return DAG.getNode(Opcode, dl, Op.getValueType(),
14620                        Op.getOperand(1), Op.getOperand(2));
14621   }
14622
14623   // AVX2 variable shift intrinsics
14624   case Intrinsic::x86_avx2_psllv_d:
14625   case Intrinsic::x86_avx2_psllv_q:
14626   case Intrinsic::x86_avx2_psllv_d_256:
14627   case Intrinsic::x86_avx2_psllv_q_256:
14628   case Intrinsic::x86_avx2_psrlv_d:
14629   case Intrinsic::x86_avx2_psrlv_q:
14630   case Intrinsic::x86_avx2_psrlv_d_256:
14631   case Intrinsic::x86_avx2_psrlv_q_256:
14632   case Intrinsic::x86_avx2_psrav_d:
14633   case Intrinsic::x86_avx2_psrav_d_256: {
14634     unsigned Opcode;
14635     switch (IntNo) {
14636     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14637     case Intrinsic::x86_avx2_psllv_d:
14638     case Intrinsic::x86_avx2_psllv_q:
14639     case Intrinsic::x86_avx2_psllv_d_256:
14640     case Intrinsic::x86_avx2_psllv_q_256:
14641       Opcode = ISD::SHL;
14642       break;
14643     case Intrinsic::x86_avx2_psrlv_d:
14644     case Intrinsic::x86_avx2_psrlv_q:
14645     case Intrinsic::x86_avx2_psrlv_d_256:
14646     case Intrinsic::x86_avx2_psrlv_q_256:
14647       Opcode = ISD::SRL;
14648       break;
14649     case Intrinsic::x86_avx2_psrav_d:
14650     case Intrinsic::x86_avx2_psrav_d_256:
14651       Opcode = ISD::SRA;
14652       break;
14653     }
14654     return DAG.getNode(Opcode, dl, Op.getValueType(),
14655                        Op.getOperand(1), Op.getOperand(2));
14656   }
14657
14658   case Intrinsic::x86_sse2_packssdw_128:
14659   case Intrinsic::x86_sse2_packsswb_128:
14660   case Intrinsic::x86_avx2_packssdw:
14661   case Intrinsic::x86_avx2_packsswb:
14662     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14663                        Op.getOperand(1), Op.getOperand(2));
14664
14665   case Intrinsic::x86_sse2_packuswb_128:
14666   case Intrinsic::x86_sse41_packusdw:
14667   case Intrinsic::x86_avx2_packuswb:
14668   case Intrinsic::x86_avx2_packusdw:
14669     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14670                        Op.getOperand(1), Op.getOperand(2));
14671
14672   case Intrinsic::x86_ssse3_pshuf_b_128:
14673   case Intrinsic::x86_avx2_pshuf_b:
14674     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14675                        Op.getOperand(1), Op.getOperand(2));
14676
14677   case Intrinsic::x86_sse2_pshuf_d:
14678     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14679                        Op.getOperand(1), Op.getOperand(2));
14680
14681   case Intrinsic::x86_sse2_pshufl_w:
14682     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14683                        Op.getOperand(1), Op.getOperand(2));
14684
14685   case Intrinsic::x86_sse2_pshufh_w:
14686     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14687                        Op.getOperand(1), Op.getOperand(2));
14688
14689   case Intrinsic::x86_ssse3_psign_b_128:
14690   case Intrinsic::x86_ssse3_psign_w_128:
14691   case Intrinsic::x86_ssse3_psign_d_128:
14692   case Intrinsic::x86_avx2_psign_b:
14693   case Intrinsic::x86_avx2_psign_w:
14694   case Intrinsic::x86_avx2_psign_d:
14695     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14696                        Op.getOperand(1), Op.getOperand(2));
14697
14698   case Intrinsic::x86_avx2_permd:
14699   case Intrinsic::x86_avx2_permps:
14700     // Operands intentionally swapped. Mask is last operand to intrinsic,
14701     // but second operand for node/instruction.
14702     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14703                        Op.getOperand(2), Op.getOperand(1));
14704
14705   case Intrinsic::x86_avx512_mask_valign_q_512:
14706   case Intrinsic::x86_avx512_mask_valign_d_512:
14707     // Vector source operands are swapped.
14708     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14709                                             Op.getValueType(), Op.getOperand(2),
14710                                             Op.getOperand(1),
14711                                             Op.getOperand(3)),
14712                                 Op.getOperand(5), Op.getOperand(4), DAG);
14713
14714   // ptest and testp intrinsics. The intrinsic these come from are designed to
14715   // return an integer value, not just an instruction so lower it to the ptest
14716   // or testp pattern and a setcc for the result.
14717   case Intrinsic::x86_sse41_ptestz:
14718   case Intrinsic::x86_sse41_ptestc:
14719   case Intrinsic::x86_sse41_ptestnzc:
14720   case Intrinsic::x86_avx_ptestz_256:
14721   case Intrinsic::x86_avx_ptestc_256:
14722   case Intrinsic::x86_avx_ptestnzc_256:
14723   case Intrinsic::x86_avx_vtestz_ps:
14724   case Intrinsic::x86_avx_vtestc_ps:
14725   case Intrinsic::x86_avx_vtestnzc_ps:
14726   case Intrinsic::x86_avx_vtestz_pd:
14727   case Intrinsic::x86_avx_vtestc_pd:
14728   case Intrinsic::x86_avx_vtestnzc_pd:
14729   case Intrinsic::x86_avx_vtestz_ps_256:
14730   case Intrinsic::x86_avx_vtestc_ps_256:
14731   case Intrinsic::x86_avx_vtestnzc_ps_256:
14732   case Intrinsic::x86_avx_vtestz_pd_256:
14733   case Intrinsic::x86_avx_vtestc_pd_256:
14734   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14735     bool IsTestPacked = false;
14736     unsigned X86CC;
14737     switch (IntNo) {
14738     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14739     case Intrinsic::x86_avx_vtestz_ps:
14740     case Intrinsic::x86_avx_vtestz_pd:
14741     case Intrinsic::x86_avx_vtestz_ps_256:
14742     case Intrinsic::x86_avx_vtestz_pd_256:
14743       IsTestPacked = true; // Fallthrough
14744     case Intrinsic::x86_sse41_ptestz:
14745     case Intrinsic::x86_avx_ptestz_256:
14746       // ZF = 1
14747       X86CC = X86::COND_E;
14748       break;
14749     case Intrinsic::x86_avx_vtestc_ps:
14750     case Intrinsic::x86_avx_vtestc_pd:
14751     case Intrinsic::x86_avx_vtestc_ps_256:
14752     case Intrinsic::x86_avx_vtestc_pd_256:
14753       IsTestPacked = true; // Fallthrough
14754     case Intrinsic::x86_sse41_ptestc:
14755     case Intrinsic::x86_avx_ptestc_256:
14756       // CF = 1
14757       X86CC = X86::COND_B;
14758       break;
14759     case Intrinsic::x86_avx_vtestnzc_ps:
14760     case Intrinsic::x86_avx_vtestnzc_pd:
14761     case Intrinsic::x86_avx_vtestnzc_ps_256:
14762     case Intrinsic::x86_avx_vtestnzc_pd_256:
14763       IsTestPacked = true; // Fallthrough
14764     case Intrinsic::x86_sse41_ptestnzc:
14765     case Intrinsic::x86_avx_ptestnzc_256:
14766       // ZF and CF = 0
14767       X86CC = X86::COND_A;
14768       break;
14769     }
14770
14771     SDValue LHS = Op.getOperand(1);
14772     SDValue RHS = Op.getOperand(2);
14773     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14774     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14775     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14776     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14777     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14778   }
14779   case Intrinsic::x86_avx512_kortestz_w:
14780   case Intrinsic::x86_avx512_kortestc_w: {
14781     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14782     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14783     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14784     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14785     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14786     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14787     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14788   }
14789
14790   case Intrinsic::x86_sse42_pcmpistria128:
14791   case Intrinsic::x86_sse42_pcmpestria128:
14792   case Intrinsic::x86_sse42_pcmpistric128:
14793   case Intrinsic::x86_sse42_pcmpestric128:
14794   case Intrinsic::x86_sse42_pcmpistrio128:
14795   case Intrinsic::x86_sse42_pcmpestrio128:
14796   case Intrinsic::x86_sse42_pcmpistris128:
14797   case Intrinsic::x86_sse42_pcmpestris128:
14798   case Intrinsic::x86_sse42_pcmpistriz128:
14799   case Intrinsic::x86_sse42_pcmpestriz128: {
14800     unsigned Opcode;
14801     unsigned X86CC;
14802     switch (IntNo) {
14803     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14804     case Intrinsic::x86_sse42_pcmpistria128:
14805       Opcode = X86ISD::PCMPISTRI;
14806       X86CC = X86::COND_A;
14807       break;
14808     case Intrinsic::x86_sse42_pcmpestria128:
14809       Opcode = X86ISD::PCMPESTRI;
14810       X86CC = X86::COND_A;
14811       break;
14812     case Intrinsic::x86_sse42_pcmpistric128:
14813       Opcode = X86ISD::PCMPISTRI;
14814       X86CC = X86::COND_B;
14815       break;
14816     case Intrinsic::x86_sse42_pcmpestric128:
14817       Opcode = X86ISD::PCMPESTRI;
14818       X86CC = X86::COND_B;
14819       break;
14820     case Intrinsic::x86_sse42_pcmpistrio128:
14821       Opcode = X86ISD::PCMPISTRI;
14822       X86CC = X86::COND_O;
14823       break;
14824     case Intrinsic::x86_sse42_pcmpestrio128:
14825       Opcode = X86ISD::PCMPESTRI;
14826       X86CC = X86::COND_O;
14827       break;
14828     case Intrinsic::x86_sse42_pcmpistris128:
14829       Opcode = X86ISD::PCMPISTRI;
14830       X86CC = X86::COND_S;
14831       break;
14832     case Intrinsic::x86_sse42_pcmpestris128:
14833       Opcode = X86ISD::PCMPESTRI;
14834       X86CC = X86::COND_S;
14835       break;
14836     case Intrinsic::x86_sse42_pcmpistriz128:
14837       Opcode = X86ISD::PCMPISTRI;
14838       X86CC = X86::COND_E;
14839       break;
14840     case Intrinsic::x86_sse42_pcmpestriz128:
14841       Opcode = X86ISD::PCMPESTRI;
14842       X86CC = X86::COND_E;
14843       break;
14844     }
14845     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14846     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14847     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14848     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14849                                 DAG.getConstant(X86CC, MVT::i8),
14850                                 SDValue(PCMP.getNode(), 1));
14851     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14852   }
14853
14854   case Intrinsic::x86_sse42_pcmpistri128:
14855   case Intrinsic::x86_sse42_pcmpestri128: {
14856     unsigned Opcode;
14857     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14858       Opcode = X86ISD::PCMPISTRI;
14859     else
14860       Opcode = X86ISD::PCMPESTRI;
14861
14862     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14863     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14864     return DAG.getNode(Opcode, dl, VTs, NewOps);
14865   }
14866
14867   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14868   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14869   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14870   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14871   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14872   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14873   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14874   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14875   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14876   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14877   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14878   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
14879     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
14880     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
14881       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
14882                                               dl, Op.getValueType(),
14883                                               Op.getOperand(1),
14884                                               Op.getOperand(2),
14885                                               Op.getOperand(3)),
14886                                   Op.getOperand(4), Op.getOperand(1), DAG);
14887     else
14888       return SDValue();
14889   }
14890
14891   case Intrinsic::x86_fma_vfmadd_ps:
14892   case Intrinsic::x86_fma_vfmadd_pd:
14893   case Intrinsic::x86_fma_vfmsub_ps:
14894   case Intrinsic::x86_fma_vfmsub_pd:
14895   case Intrinsic::x86_fma_vfnmadd_ps:
14896   case Intrinsic::x86_fma_vfnmadd_pd:
14897   case Intrinsic::x86_fma_vfnmsub_ps:
14898   case Intrinsic::x86_fma_vfnmsub_pd:
14899   case Intrinsic::x86_fma_vfmaddsub_ps:
14900   case Intrinsic::x86_fma_vfmaddsub_pd:
14901   case Intrinsic::x86_fma_vfmsubadd_ps:
14902   case Intrinsic::x86_fma_vfmsubadd_pd:
14903   case Intrinsic::x86_fma_vfmadd_ps_256:
14904   case Intrinsic::x86_fma_vfmadd_pd_256:
14905   case Intrinsic::x86_fma_vfmsub_ps_256:
14906   case Intrinsic::x86_fma_vfmsub_pd_256:
14907   case Intrinsic::x86_fma_vfnmadd_ps_256:
14908   case Intrinsic::x86_fma_vfnmadd_pd_256:
14909   case Intrinsic::x86_fma_vfnmsub_ps_256:
14910   case Intrinsic::x86_fma_vfnmsub_pd_256:
14911   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14912   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14913   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14914   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14915     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
14916                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14917   }
14918 }
14919
14920 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14921                               SDValue Src, SDValue Mask, SDValue Base,
14922                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14923                               const X86Subtarget * Subtarget) {
14924   SDLoc dl(Op);
14925   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14926   assert(C && "Invalid scale type");
14927   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14928   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14929                              Index.getSimpleValueType().getVectorNumElements());
14930   SDValue MaskInReg;
14931   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14932   if (MaskC)
14933     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14934   else
14935     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14936   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14937   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14938   SDValue Segment = DAG.getRegister(0, MVT::i32);
14939   if (Src.getOpcode() == ISD::UNDEF)
14940     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14941   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14942   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14943   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14944   return DAG.getMergeValues(RetOps, dl);
14945 }
14946
14947 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14948                                SDValue Src, SDValue Mask, SDValue Base,
14949                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14950   SDLoc dl(Op);
14951   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14952   assert(C && "Invalid scale type");
14953   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14954   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14955   SDValue Segment = DAG.getRegister(0, MVT::i32);
14956   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14957                              Index.getSimpleValueType().getVectorNumElements());
14958   SDValue MaskInReg;
14959   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14960   if (MaskC)
14961     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14962   else
14963     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14964   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14965   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14966   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14967   return SDValue(Res, 1);
14968 }
14969
14970 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14971                                SDValue Mask, SDValue Base, SDValue Index,
14972                                SDValue ScaleOp, SDValue Chain) {
14973   SDLoc dl(Op);
14974   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14975   assert(C && "Invalid scale type");
14976   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14977   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14978   SDValue Segment = DAG.getRegister(0, MVT::i32);
14979   EVT MaskVT =
14980     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14981   SDValue MaskInReg;
14982   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14983   if (MaskC)
14984     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14985   else
14986     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14987   //SDVTList VTs = DAG.getVTList(MVT::Other);
14988   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14989   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14990   return SDValue(Res, 0);
14991 }
14992
14993 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14994 // read performance monitor counters (x86_rdpmc).
14995 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14996                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14997                               SmallVectorImpl<SDValue> &Results) {
14998   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14999   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15000   SDValue LO, HI;
15001
15002   // The ECX register is used to select the index of the performance counter
15003   // to read.
15004   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15005                                    N->getOperand(2));
15006   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15007
15008   // Reads the content of a 64-bit performance counter and returns it in the
15009   // registers EDX:EAX.
15010   if (Subtarget->is64Bit()) {
15011     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15012     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15013                             LO.getValue(2));
15014   } else {
15015     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15016     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15017                             LO.getValue(2));
15018   }
15019   Chain = HI.getValue(1);
15020
15021   if (Subtarget->is64Bit()) {
15022     // The EAX register is loaded with the low-order 32 bits. The EDX register
15023     // is loaded with the supported high-order bits of the counter.
15024     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15025                               DAG.getConstant(32, MVT::i8));
15026     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15027     Results.push_back(Chain);
15028     return;
15029   }
15030
15031   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15032   SDValue Ops[] = { LO, HI };
15033   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15034   Results.push_back(Pair);
15035   Results.push_back(Chain);
15036 }
15037
15038 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15039 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15040 // also used to custom lower READCYCLECOUNTER nodes.
15041 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15042                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15043                               SmallVectorImpl<SDValue> &Results) {
15044   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15045   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15046   SDValue LO, HI;
15047
15048   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15049   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15050   // and the EAX register is loaded with the low-order 32 bits.
15051   if (Subtarget->is64Bit()) {
15052     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15053     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15054                             LO.getValue(2));
15055   } else {
15056     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15057     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15058                             LO.getValue(2));
15059   }
15060   SDValue Chain = HI.getValue(1);
15061
15062   if (Opcode == X86ISD::RDTSCP_DAG) {
15063     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15064
15065     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15066     // the ECX register. Add 'ecx' explicitly to the chain.
15067     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15068                                      HI.getValue(2));
15069     // Explicitly store the content of ECX at the location passed in input
15070     // to the 'rdtscp' intrinsic.
15071     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15072                          MachinePointerInfo(), false, false, 0);
15073   }
15074
15075   if (Subtarget->is64Bit()) {
15076     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15077     // the EAX register is loaded with the low-order 32 bits.
15078     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15079                               DAG.getConstant(32, MVT::i8));
15080     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15081     Results.push_back(Chain);
15082     return;
15083   }
15084
15085   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15086   SDValue Ops[] = { LO, HI };
15087   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15088   Results.push_back(Pair);
15089   Results.push_back(Chain);
15090 }
15091
15092 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15093                                      SelectionDAG &DAG) {
15094   SmallVector<SDValue, 2> Results;
15095   SDLoc DL(Op);
15096   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15097                           Results);
15098   return DAG.getMergeValues(Results, DL);
15099 }
15100
15101
15102 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15103                                       SelectionDAG &DAG) {
15104   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15105
15106   const IntrinsicData* IntrData = GetIntrinsicWithChain(IntNo);
15107   if (!IntrData)
15108     return SDValue();
15109
15110   SDLoc dl(Op);
15111   switch(IntrData->Type) {
15112   default:
15113     llvm_unreachable("Unknown Intrinsic Type");
15114     break;    
15115   case RDSEED:
15116   case RDRAND: {
15117     // Emit the node with the right value type.
15118     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15119     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15120
15121     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15122     // Otherwise return the value from Rand, which is always 0, casted to i32.
15123     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15124                       DAG.getConstant(1, Op->getValueType(1)),
15125                       DAG.getConstant(X86::COND_B, MVT::i32),
15126                       SDValue(Result.getNode(), 1) };
15127     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15128                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15129                                   Ops);
15130
15131     // Return { result, isValid, chain }.
15132     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15133                        SDValue(Result.getNode(), 2));
15134   }
15135   case GATHER: {
15136   //gather(v1, mask, index, base, scale);
15137     SDValue Chain = Op.getOperand(0);
15138     SDValue Src   = Op.getOperand(2);
15139     SDValue Base  = Op.getOperand(3);
15140     SDValue Index = Op.getOperand(4);
15141     SDValue Mask  = Op.getOperand(5);
15142     SDValue Scale = Op.getOperand(6);
15143     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15144                           Subtarget);
15145   }
15146   case SCATTER: {
15147   //scatter(base, mask, index, v1, scale);
15148     SDValue Chain = Op.getOperand(0);
15149     SDValue Base  = Op.getOperand(2);
15150     SDValue Mask  = Op.getOperand(3);
15151     SDValue Index = Op.getOperand(4);
15152     SDValue Src   = Op.getOperand(5);
15153     SDValue Scale = Op.getOperand(6);
15154     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15155   }
15156   case PREFETCH: {
15157     SDValue Hint = Op.getOperand(6);
15158     unsigned HintVal;
15159     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15160         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15161       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15162     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15163     SDValue Chain = Op.getOperand(0);
15164     SDValue Mask  = Op.getOperand(2);
15165     SDValue Index = Op.getOperand(3);
15166     SDValue Base  = Op.getOperand(4);
15167     SDValue Scale = Op.getOperand(5);
15168     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15169   }
15170   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15171   case RDTSC: {
15172     SmallVector<SDValue, 2> Results;
15173     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15174     return DAG.getMergeValues(Results, dl);
15175   }
15176   // Read Performance Monitoring Counters.
15177   case RDPMC: {
15178     SmallVector<SDValue, 2> Results;
15179     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15180     return DAG.getMergeValues(Results, dl);
15181   }
15182   // XTEST intrinsics.
15183   case XTEST: {
15184     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15185     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15186     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15187                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15188                                 InTrans);
15189     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15190     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15191                        Ret, SDValue(InTrans.getNode(), 1));
15192   }
15193   // ADC/ADCX/SBB
15194   case ADX: {
15195     SmallVector<SDValue, 2> Results;
15196     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15197     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15198     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15199                                 DAG.getConstant(-1, MVT::i8));
15200     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15201                               Op.getOperand(4), GenCF.getValue(1));
15202     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15203                                  Op.getOperand(5), MachinePointerInfo(),
15204                                  false, false, 0);
15205     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15206                                 DAG.getConstant(X86::COND_B, MVT::i8),
15207                                 Res.getValue(1));
15208     Results.push_back(SetCC);
15209     Results.push_back(Store);
15210     return DAG.getMergeValues(Results, dl);
15211   }
15212   }
15213 }
15214
15215 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15216                                            SelectionDAG &DAG) const {
15217   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15218   MFI->setReturnAddressIsTaken(true);
15219
15220   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15221     return SDValue();
15222
15223   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15224   SDLoc dl(Op);
15225   EVT PtrVT = getPointerTy();
15226
15227   if (Depth > 0) {
15228     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15229     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15230         DAG.getSubtarget().getRegisterInfo());
15231     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15232     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15233                        DAG.getNode(ISD::ADD, dl, PtrVT,
15234                                    FrameAddr, Offset),
15235                        MachinePointerInfo(), false, false, false, 0);
15236   }
15237
15238   // Just load the return address.
15239   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15240   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15241                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15242 }
15243
15244 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15245   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15246   MFI->setFrameAddressIsTaken(true);
15247
15248   EVT VT = Op.getValueType();
15249   SDLoc dl(Op);  // FIXME probably not meaningful
15250   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15251   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15252       DAG.getSubtarget().getRegisterInfo());
15253   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15254   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15255           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15256          "Invalid Frame Register!");
15257   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15258   while (Depth--)
15259     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15260                             MachinePointerInfo(),
15261                             false, false, false, 0);
15262   return FrameAddr;
15263 }
15264
15265 // FIXME? Maybe this could be a TableGen attribute on some registers and
15266 // this table could be generated automatically from RegInfo.
15267 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15268                                               EVT VT) const {
15269   unsigned Reg = StringSwitch<unsigned>(RegName)
15270                        .Case("esp", X86::ESP)
15271                        .Case("rsp", X86::RSP)
15272                        .Default(0);
15273   if (Reg)
15274     return Reg;
15275   report_fatal_error("Invalid register name global variable");
15276 }
15277
15278 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15279                                                      SelectionDAG &DAG) const {
15280   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15281       DAG.getSubtarget().getRegisterInfo());
15282   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15283 }
15284
15285 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15286   SDValue Chain     = Op.getOperand(0);
15287   SDValue Offset    = Op.getOperand(1);
15288   SDValue Handler   = Op.getOperand(2);
15289   SDLoc dl      (Op);
15290
15291   EVT PtrVT = getPointerTy();
15292   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15293       DAG.getSubtarget().getRegisterInfo());
15294   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15295   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15296           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15297          "Invalid Frame Register!");
15298   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15299   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15300
15301   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15302                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15303   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15304   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15305                        false, false, 0);
15306   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15307
15308   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15309                      DAG.getRegister(StoreAddrReg, PtrVT));
15310 }
15311
15312 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15313                                                SelectionDAG &DAG) const {
15314   SDLoc DL(Op);
15315   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15316                      DAG.getVTList(MVT::i32, MVT::Other),
15317                      Op.getOperand(0), Op.getOperand(1));
15318 }
15319
15320 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15321                                                 SelectionDAG &DAG) const {
15322   SDLoc DL(Op);
15323   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15324                      Op.getOperand(0), Op.getOperand(1));
15325 }
15326
15327 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15328   return Op.getOperand(0);
15329 }
15330
15331 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15332                                                 SelectionDAG &DAG) const {
15333   SDValue Root = Op.getOperand(0);
15334   SDValue Trmp = Op.getOperand(1); // trampoline
15335   SDValue FPtr = Op.getOperand(2); // nested function
15336   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15337   SDLoc dl (Op);
15338
15339   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15340   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15341
15342   if (Subtarget->is64Bit()) {
15343     SDValue OutChains[6];
15344
15345     // Large code-model.
15346     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15347     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15348
15349     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15350     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15351
15352     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15353
15354     // Load the pointer to the nested function into R11.
15355     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15356     SDValue Addr = Trmp;
15357     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15358                                 Addr, MachinePointerInfo(TrmpAddr),
15359                                 false, false, 0);
15360
15361     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15362                        DAG.getConstant(2, MVT::i64));
15363     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15364                                 MachinePointerInfo(TrmpAddr, 2),
15365                                 false, false, 2);
15366
15367     // Load the 'nest' parameter value into R10.
15368     // R10 is specified in X86CallingConv.td
15369     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15370     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15371                        DAG.getConstant(10, MVT::i64));
15372     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15373                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15374                                 false, false, 0);
15375
15376     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15377                        DAG.getConstant(12, MVT::i64));
15378     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15379                                 MachinePointerInfo(TrmpAddr, 12),
15380                                 false, false, 2);
15381
15382     // Jump to the nested function.
15383     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15384     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15385                        DAG.getConstant(20, MVT::i64));
15386     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15387                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15388                                 false, false, 0);
15389
15390     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15391     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15392                        DAG.getConstant(22, MVT::i64));
15393     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15394                                 MachinePointerInfo(TrmpAddr, 22),
15395                                 false, false, 0);
15396
15397     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15398   } else {
15399     const Function *Func =
15400       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15401     CallingConv::ID CC = Func->getCallingConv();
15402     unsigned NestReg;
15403
15404     switch (CC) {
15405     default:
15406       llvm_unreachable("Unsupported calling convention");
15407     case CallingConv::C:
15408     case CallingConv::X86_StdCall: {
15409       // Pass 'nest' parameter in ECX.
15410       // Must be kept in sync with X86CallingConv.td
15411       NestReg = X86::ECX;
15412
15413       // Check that ECX wasn't needed by an 'inreg' parameter.
15414       FunctionType *FTy = Func->getFunctionType();
15415       const AttributeSet &Attrs = Func->getAttributes();
15416
15417       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15418         unsigned InRegCount = 0;
15419         unsigned Idx = 1;
15420
15421         for (FunctionType::param_iterator I = FTy->param_begin(),
15422              E = FTy->param_end(); I != E; ++I, ++Idx)
15423           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15424             // FIXME: should only count parameters that are lowered to integers.
15425             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15426
15427         if (InRegCount > 2) {
15428           report_fatal_error("Nest register in use - reduce number of inreg"
15429                              " parameters!");
15430         }
15431       }
15432       break;
15433     }
15434     case CallingConv::X86_FastCall:
15435     case CallingConv::X86_ThisCall:
15436     case CallingConv::Fast:
15437       // Pass 'nest' parameter in EAX.
15438       // Must be kept in sync with X86CallingConv.td
15439       NestReg = X86::EAX;
15440       break;
15441     }
15442
15443     SDValue OutChains[4];
15444     SDValue Addr, Disp;
15445
15446     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15447                        DAG.getConstant(10, MVT::i32));
15448     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15449
15450     // This is storing the opcode for MOV32ri.
15451     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15452     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15453     OutChains[0] = DAG.getStore(Root, dl,
15454                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15455                                 Trmp, MachinePointerInfo(TrmpAddr),
15456                                 false, false, 0);
15457
15458     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15459                        DAG.getConstant(1, MVT::i32));
15460     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15461                                 MachinePointerInfo(TrmpAddr, 1),
15462                                 false, false, 1);
15463
15464     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15465     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15466                        DAG.getConstant(5, MVT::i32));
15467     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15468                                 MachinePointerInfo(TrmpAddr, 5),
15469                                 false, false, 1);
15470
15471     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15472                        DAG.getConstant(6, MVT::i32));
15473     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15474                                 MachinePointerInfo(TrmpAddr, 6),
15475                                 false, false, 1);
15476
15477     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15478   }
15479 }
15480
15481 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15482                                             SelectionDAG &DAG) const {
15483   /*
15484    The rounding mode is in bits 11:10 of FPSR, and has the following
15485    settings:
15486      00 Round to nearest
15487      01 Round to -inf
15488      10 Round to +inf
15489      11 Round to 0
15490
15491   FLT_ROUNDS, on the other hand, expects the following:
15492     -1 Undefined
15493      0 Round to 0
15494      1 Round to nearest
15495      2 Round to +inf
15496      3 Round to -inf
15497
15498   To perform the conversion, we do:
15499     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15500   */
15501
15502   MachineFunction &MF = DAG.getMachineFunction();
15503   const TargetMachine &TM = MF.getTarget();
15504   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15505   unsigned StackAlignment = TFI.getStackAlignment();
15506   MVT VT = Op.getSimpleValueType();
15507   SDLoc DL(Op);
15508
15509   // Save FP Control Word to stack slot
15510   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15511   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15512
15513   MachineMemOperand *MMO =
15514    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15515                            MachineMemOperand::MOStore, 2, 2);
15516
15517   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15518   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15519                                           DAG.getVTList(MVT::Other),
15520                                           Ops, MVT::i16, MMO);
15521
15522   // Load FP Control Word from stack slot
15523   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15524                             MachinePointerInfo(), false, false, false, 0);
15525
15526   // Transform as necessary
15527   SDValue CWD1 =
15528     DAG.getNode(ISD::SRL, DL, MVT::i16,
15529                 DAG.getNode(ISD::AND, DL, MVT::i16,
15530                             CWD, DAG.getConstant(0x800, MVT::i16)),
15531                 DAG.getConstant(11, MVT::i8));
15532   SDValue CWD2 =
15533     DAG.getNode(ISD::SRL, DL, MVT::i16,
15534                 DAG.getNode(ISD::AND, DL, MVT::i16,
15535                             CWD, DAG.getConstant(0x400, MVT::i16)),
15536                 DAG.getConstant(9, MVT::i8));
15537
15538   SDValue RetVal =
15539     DAG.getNode(ISD::AND, DL, MVT::i16,
15540                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15541                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15542                             DAG.getConstant(1, MVT::i16)),
15543                 DAG.getConstant(3, MVT::i16));
15544
15545   return DAG.getNode((VT.getSizeInBits() < 16 ?
15546                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15547 }
15548
15549 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15550   MVT VT = Op.getSimpleValueType();
15551   EVT OpVT = VT;
15552   unsigned NumBits = VT.getSizeInBits();
15553   SDLoc dl(Op);
15554
15555   Op = Op.getOperand(0);
15556   if (VT == MVT::i8) {
15557     // Zero extend to i32 since there is not an i8 bsr.
15558     OpVT = MVT::i32;
15559     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15560   }
15561
15562   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15563   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15564   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15565
15566   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15567   SDValue Ops[] = {
15568     Op,
15569     DAG.getConstant(NumBits+NumBits-1, OpVT),
15570     DAG.getConstant(X86::COND_E, MVT::i8),
15571     Op.getValue(1)
15572   };
15573   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15574
15575   // Finally xor with NumBits-1.
15576   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15577
15578   if (VT == MVT::i8)
15579     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15580   return Op;
15581 }
15582
15583 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15584   MVT VT = Op.getSimpleValueType();
15585   EVT OpVT = VT;
15586   unsigned NumBits = VT.getSizeInBits();
15587   SDLoc dl(Op);
15588
15589   Op = Op.getOperand(0);
15590   if (VT == MVT::i8) {
15591     // Zero extend to i32 since there is not an i8 bsr.
15592     OpVT = MVT::i32;
15593     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15594   }
15595
15596   // Issue a bsr (scan bits in reverse).
15597   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15598   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15599
15600   // And xor with NumBits-1.
15601   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15602
15603   if (VT == MVT::i8)
15604     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15605   return Op;
15606 }
15607
15608 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15609   MVT VT = Op.getSimpleValueType();
15610   unsigned NumBits = VT.getSizeInBits();
15611   SDLoc dl(Op);
15612   Op = Op.getOperand(0);
15613
15614   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15615   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15616   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15617
15618   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15619   SDValue Ops[] = {
15620     Op,
15621     DAG.getConstant(NumBits, VT),
15622     DAG.getConstant(X86::COND_E, MVT::i8),
15623     Op.getValue(1)
15624   };
15625   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15626 }
15627
15628 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15629 // ones, and then concatenate the result back.
15630 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15631   MVT VT = Op.getSimpleValueType();
15632
15633   assert(VT.is256BitVector() && VT.isInteger() &&
15634          "Unsupported value type for operation");
15635
15636   unsigned NumElems = VT.getVectorNumElements();
15637   SDLoc dl(Op);
15638
15639   // Extract the LHS vectors
15640   SDValue LHS = Op.getOperand(0);
15641   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15642   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15643
15644   // Extract the RHS vectors
15645   SDValue RHS = Op.getOperand(1);
15646   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15647   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15648
15649   MVT EltVT = VT.getVectorElementType();
15650   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15651
15652   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15653                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15654                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15655 }
15656
15657 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15658   assert(Op.getSimpleValueType().is256BitVector() &&
15659          Op.getSimpleValueType().isInteger() &&
15660          "Only handle AVX 256-bit vector integer operation");
15661   return Lower256IntArith(Op, DAG);
15662 }
15663
15664 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15665   assert(Op.getSimpleValueType().is256BitVector() &&
15666          Op.getSimpleValueType().isInteger() &&
15667          "Only handle AVX 256-bit vector integer operation");
15668   return Lower256IntArith(Op, DAG);
15669 }
15670
15671 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15672                         SelectionDAG &DAG) {
15673   SDLoc dl(Op);
15674   MVT VT = Op.getSimpleValueType();
15675
15676   // Decompose 256-bit ops into smaller 128-bit ops.
15677   if (VT.is256BitVector() && !Subtarget->hasInt256())
15678     return Lower256IntArith(Op, DAG);
15679
15680   SDValue A = Op.getOperand(0);
15681   SDValue B = Op.getOperand(1);
15682
15683   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15684   if (VT == MVT::v4i32) {
15685     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15686            "Should not custom lower when pmuldq is available!");
15687
15688     // Extract the odd parts.
15689     static const int UnpackMask[] = { 1, -1, 3, -1 };
15690     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15691     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15692
15693     // Multiply the even parts.
15694     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15695     // Now multiply odd parts.
15696     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15697
15698     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15699     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15700
15701     // Merge the two vectors back together with a shuffle. This expands into 2
15702     // shuffles.
15703     static const int ShufMask[] = { 0, 4, 2, 6 };
15704     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15705   }
15706
15707   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15708          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15709
15710   //  Ahi = psrlqi(a, 32);
15711   //  Bhi = psrlqi(b, 32);
15712   //
15713   //  AloBlo = pmuludq(a, b);
15714   //  AloBhi = pmuludq(a, Bhi);
15715   //  AhiBlo = pmuludq(Ahi, b);
15716
15717   //  AloBhi = psllqi(AloBhi, 32);
15718   //  AhiBlo = psllqi(AhiBlo, 32);
15719   //  return AloBlo + AloBhi + AhiBlo;
15720
15721   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15722   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15723
15724   // Bit cast to 32-bit vectors for MULUDQ
15725   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15726                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15727   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15728   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15729   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15730   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15731
15732   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15733   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15734   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15735
15736   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15737   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15738
15739   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15740   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15741 }
15742
15743 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15744   assert(Subtarget->isTargetWin64() && "Unexpected target");
15745   EVT VT = Op.getValueType();
15746   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15747          "Unexpected return type for lowering");
15748
15749   RTLIB::Libcall LC;
15750   bool isSigned;
15751   switch (Op->getOpcode()) {
15752   default: llvm_unreachable("Unexpected request for libcall!");
15753   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15754   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15755   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15756   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15757   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15758   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15759   }
15760
15761   SDLoc dl(Op);
15762   SDValue InChain = DAG.getEntryNode();
15763
15764   TargetLowering::ArgListTy Args;
15765   TargetLowering::ArgListEntry Entry;
15766   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15767     EVT ArgVT = Op->getOperand(i).getValueType();
15768     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15769            "Unexpected argument type for lowering");
15770     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15771     Entry.Node = StackPtr;
15772     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15773                            false, false, 16);
15774     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15775     Entry.Ty = PointerType::get(ArgTy,0);
15776     Entry.isSExt = false;
15777     Entry.isZExt = false;
15778     Args.push_back(Entry);
15779   }
15780
15781   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15782                                          getPointerTy());
15783
15784   TargetLowering::CallLoweringInfo CLI(DAG);
15785   CLI.setDebugLoc(dl).setChain(InChain)
15786     .setCallee(getLibcallCallingConv(LC),
15787                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15788                Callee, std::move(Args), 0)
15789     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15790
15791   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15792   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15793 }
15794
15795 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15796                              SelectionDAG &DAG) {
15797   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15798   EVT VT = Op0.getValueType();
15799   SDLoc dl(Op);
15800
15801   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15802          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15803
15804   // PMULxD operations multiply each even value (starting at 0) of LHS with
15805   // the related value of RHS and produce a widen result.
15806   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15807   // => <2 x i64> <ae|cg>
15808   //
15809   // In other word, to have all the results, we need to perform two PMULxD:
15810   // 1. one with the even values.
15811   // 2. one with the odd values.
15812   // To achieve #2, with need to place the odd values at an even position.
15813   //
15814   // Place the odd value at an even position (basically, shift all values 1
15815   // step to the left):
15816   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15817   // <a|b|c|d> => <b|undef|d|undef>
15818   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15819   // <e|f|g|h> => <f|undef|h|undef>
15820   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15821
15822   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15823   // ints.
15824   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15825   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15826   unsigned Opcode =
15827       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15828   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15829   // => <2 x i64> <ae|cg>
15830   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15831                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15832   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15833   // => <2 x i64> <bf|dh>
15834   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15835                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15836
15837   // Shuffle it back into the right order.
15838   SDValue Highs, Lows;
15839   if (VT == MVT::v8i32) {
15840     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15841     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15842     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15843     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15844   } else {
15845     const int HighMask[] = {1, 5, 3, 7};
15846     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15847     const int LowMask[] = {0, 4, 2, 6};
15848     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15849   }
15850
15851   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15852   // unsigned multiply.
15853   if (IsSigned && !Subtarget->hasSSE41()) {
15854     SDValue ShAmt =
15855         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15856     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15857                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15858     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15859                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15860
15861     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15862     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15863   }
15864
15865   // The first result of MUL_LOHI is actually the low value, followed by the
15866   // high value.
15867   SDValue Ops[] = {Lows, Highs};
15868   return DAG.getMergeValues(Ops, dl);
15869 }
15870
15871 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15872                                          const X86Subtarget *Subtarget) {
15873   MVT VT = Op.getSimpleValueType();
15874   SDLoc dl(Op);
15875   SDValue R = Op.getOperand(0);
15876   SDValue Amt = Op.getOperand(1);
15877
15878   // Optimize shl/srl/sra with constant shift amount.
15879   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15880     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15881       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15882
15883       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15884           (Subtarget->hasInt256() &&
15885            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15886           (Subtarget->hasAVX512() &&
15887            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15888         if (Op.getOpcode() == ISD::SHL)
15889           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15890                                             DAG);
15891         if (Op.getOpcode() == ISD::SRL)
15892           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15893                                             DAG);
15894         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15895           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15896                                             DAG);
15897       }
15898
15899       if (VT == MVT::v16i8) {
15900         if (Op.getOpcode() == ISD::SHL) {
15901           // Make a large shift.
15902           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15903                                                    MVT::v8i16, R, ShiftAmt,
15904                                                    DAG);
15905           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15906           // Zero out the rightmost bits.
15907           SmallVector<SDValue, 16> V(16,
15908                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15909                                                      MVT::i8));
15910           return DAG.getNode(ISD::AND, dl, VT, SHL,
15911                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15912         }
15913         if (Op.getOpcode() == ISD::SRL) {
15914           // Make a large shift.
15915           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15916                                                    MVT::v8i16, R, ShiftAmt,
15917                                                    DAG);
15918           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15919           // Zero out the leftmost bits.
15920           SmallVector<SDValue, 16> V(16,
15921                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15922                                                      MVT::i8));
15923           return DAG.getNode(ISD::AND, dl, VT, SRL,
15924                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15925         }
15926         if (Op.getOpcode() == ISD::SRA) {
15927           if (ShiftAmt == 7) {
15928             // R s>> 7  ===  R s< 0
15929             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15930             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15931           }
15932
15933           // R s>> a === ((R u>> a) ^ m) - m
15934           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15935           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15936                                                          MVT::i8));
15937           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15938           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15939           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15940           return Res;
15941         }
15942         llvm_unreachable("Unknown shift opcode.");
15943       }
15944
15945       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15946         if (Op.getOpcode() == ISD::SHL) {
15947           // Make a large shift.
15948           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15949                                                    MVT::v16i16, R, ShiftAmt,
15950                                                    DAG);
15951           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15952           // Zero out the rightmost bits.
15953           SmallVector<SDValue, 32> V(32,
15954                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15955                                                      MVT::i8));
15956           return DAG.getNode(ISD::AND, dl, VT, SHL,
15957                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15958         }
15959         if (Op.getOpcode() == ISD::SRL) {
15960           // Make a large shift.
15961           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15962                                                    MVT::v16i16, R, ShiftAmt,
15963                                                    DAG);
15964           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15965           // Zero out the leftmost bits.
15966           SmallVector<SDValue, 32> V(32,
15967                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15968                                                      MVT::i8));
15969           return DAG.getNode(ISD::AND, dl, VT, SRL,
15970                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15971         }
15972         if (Op.getOpcode() == ISD::SRA) {
15973           if (ShiftAmt == 7) {
15974             // R s>> 7  ===  R s< 0
15975             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15976             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15977           }
15978
15979           // R s>> a === ((R u>> a) ^ m) - m
15980           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15981           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15982                                                          MVT::i8));
15983           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15984           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15985           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15986           return Res;
15987         }
15988         llvm_unreachable("Unknown shift opcode.");
15989       }
15990     }
15991   }
15992
15993   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15994   if (!Subtarget->is64Bit() &&
15995       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15996       Amt.getOpcode() == ISD::BITCAST &&
15997       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15998     Amt = Amt.getOperand(0);
15999     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16000                      VT.getVectorNumElements();
16001     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16002     uint64_t ShiftAmt = 0;
16003     for (unsigned i = 0; i != Ratio; ++i) {
16004       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16005       if (!C)
16006         return SDValue();
16007       // 6 == Log2(64)
16008       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16009     }
16010     // Check remaining shift amounts.
16011     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16012       uint64_t ShAmt = 0;
16013       for (unsigned j = 0; j != Ratio; ++j) {
16014         ConstantSDNode *C =
16015           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16016         if (!C)
16017           return SDValue();
16018         // 6 == Log2(64)
16019         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16020       }
16021       if (ShAmt != ShiftAmt)
16022         return SDValue();
16023     }
16024     switch (Op.getOpcode()) {
16025     default:
16026       llvm_unreachable("Unknown shift opcode!");
16027     case ISD::SHL:
16028       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16029                                         DAG);
16030     case ISD::SRL:
16031       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16032                                         DAG);
16033     case ISD::SRA:
16034       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16035                                         DAG);
16036     }
16037   }
16038
16039   return SDValue();
16040 }
16041
16042 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16043                                         const X86Subtarget* Subtarget) {
16044   MVT VT = Op.getSimpleValueType();
16045   SDLoc dl(Op);
16046   SDValue R = Op.getOperand(0);
16047   SDValue Amt = Op.getOperand(1);
16048
16049   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16050       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16051       (Subtarget->hasInt256() &&
16052        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16053         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16054        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16055     SDValue BaseShAmt;
16056     EVT EltVT = VT.getVectorElementType();
16057
16058     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16059       unsigned NumElts = VT.getVectorNumElements();
16060       unsigned i, j;
16061       for (i = 0; i != NumElts; ++i) {
16062         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16063           continue;
16064         break;
16065       }
16066       for (j = i; j != NumElts; ++j) {
16067         SDValue Arg = Amt.getOperand(j);
16068         if (Arg.getOpcode() == ISD::UNDEF) continue;
16069         if (Arg != Amt.getOperand(i))
16070           break;
16071       }
16072       if (i != NumElts && j == NumElts)
16073         BaseShAmt = Amt.getOperand(i);
16074     } else {
16075       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16076         Amt = Amt.getOperand(0);
16077       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16078                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16079         SDValue InVec = Amt.getOperand(0);
16080         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16081           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16082           unsigned i = 0;
16083           for (; i != NumElts; ++i) {
16084             SDValue Arg = InVec.getOperand(i);
16085             if (Arg.getOpcode() == ISD::UNDEF) continue;
16086             BaseShAmt = Arg;
16087             break;
16088           }
16089         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16090            if (ConstantSDNode *C =
16091                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16092              unsigned SplatIdx =
16093                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16094              if (C->getZExtValue() == SplatIdx)
16095                BaseShAmt = InVec.getOperand(1);
16096            }
16097         }
16098         if (!BaseShAmt.getNode())
16099           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16100                                   DAG.getIntPtrConstant(0));
16101       }
16102     }
16103
16104     if (BaseShAmt.getNode()) {
16105       if (EltVT.bitsGT(MVT::i32))
16106         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16107       else if (EltVT.bitsLT(MVT::i32))
16108         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16109
16110       switch (Op.getOpcode()) {
16111       default:
16112         llvm_unreachable("Unknown shift opcode!");
16113       case ISD::SHL:
16114         switch (VT.SimpleTy) {
16115         default: return SDValue();
16116         case MVT::v2i64:
16117         case MVT::v4i32:
16118         case MVT::v8i16:
16119         case MVT::v4i64:
16120         case MVT::v8i32:
16121         case MVT::v16i16:
16122         case MVT::v16i32:
16123         case MVT::v8i64:
16124           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16125         }
16126       case ISD::SRA:
16127         switch (VT.SimpleTy) {
16128         default: return SDValue();
16129         case MVT::v4i32:
16130         case MVT::v8i16:
16131         case MVT::v8i32:
16132         case MVT::v16i16:
16133         case MVT::v16i32:
16134         case MVT::v8i64:
16135           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16136         }
16137       case ISD::SRL:
16138         switch (VT.SimpleTy) {
16139         default: return SDValue();
16140         case MVT::v2i64:
16141         case MVT::v4i32:
16142         case MVT::v8i16:
16143         case MVT::v4i64:
16144         case MVT::v8i32:
16145         case MVT::v16i16:
16146         case MVT::v16i32:
16147         case MVT::v8i64:
16148           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16149         }
16150       }
16151     }
16152   }
16153
16154   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16155   if (!Subtarget->is64Bit() &&
16156       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16157       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16158       Amt.getOpcode() == ISD::BITCAST &&
16159       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16160     Amt = Amt.getOperand(0);
16161     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16162                      VT.getVectorNumElements();
16163     std::vector<SDValue> Vals(Ratio);
16164     for (unsigned i = 0; i != Ratio; ++i)
16165       Vals[i] = Amt.getOperand(i);
16166     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16167       for (unsigned j = 0; j != Ratio; ++j)
16168         if (Vals[j] != Amt.getOperand(i + j))
16169           return SDValue();
16170     }
16171     switch (Op.getOpcode()) {
16172     default:
16173       llvm_unreachable("Unknown shift opcode!");
16174     case ISD::SHL:
16175       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16176     case ISD::SRL:
16177       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16178     case ISD::SRA:
16179       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16180     }
16181   }
16182
16183   return SDValue();
16184 }
16185
16186 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16187                           SelectionDAG &DAG) {
16188   MVT VT = Op.getSimpleValueType();
16189   SDLoc dl(Op);
16190   SDValue R = Op.getOperand(0);
16191   SDValue Amt = Op.getOperand(1);
16192   SDValue V;
16193
16194   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16195   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16196
16197   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16198   if (V.getNode())
16199     return V;
16200
16201   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16202   if (V.getNode())
16203       return V;
16204
16205   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16206     return Op;
16207   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16208   if (Subtarget->hasInt256()) {
16209     if (Op.getOpcode() == ISD::SRL &&
16210         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16211          VT == MVT::v4i64 || VT == MVT::v8i32))
16212       return Op;
16213     if (Op.getOpcode() == ISD::SHL &&
16214         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16215          VT == MVT::v4i64 || VT == MVT::v8i32))
16216       return Op;
16217     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16218       return Op;
16219   }
16220
16221   // If possible, lower this packed shift into a vector multiply instead of
16222   // expanding it into a sequence of scalar shifts.
16223   // Do this only if the vector shift count is a constant build_vector.
16224   if (Op.getOpcode() == ISD::SHL && 
16225       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16226        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16227       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16228     SmallVector<SDValue, 8> Elts;
16229     EVT SVT = VT.getScalarType();
16230     unsigned SVTBits = SVT.getSizeInBits();
16231     const APInt &One = APInt(SVTBits, 1);
16232     unsigned NumElems = VT.getVectorNumElements();
16233
16234     for (unsigned i=0; i !=NumElems; ++i) {
16235       SDValue Op = Amt->getOperand(i);
16236       if (Op->getOpcode() == ISD::UNDEF) {
16237         Elts.push_back(Op);
16238         continue;
16239       }
16240
16241       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16242       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16243       uint64_t ShAmt = C.getZExtValue();
16244       if (ShAmt >= SVTBits) {
16245         Elts.push_back(DAG.getUNDEF(SVT));
16246         continue;
16247       }
16248       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16249     }
16250     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16251     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16252   }
16253
16254   // Lower SHL with variable shift amount.
16255   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16256     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16257
16258     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16259     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16260     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16261     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16262   }
16263
16264   // If possible, lower this shift as a sequence of two shifts by
16265   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16266   // Example:
16267   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16268   //
16269   // Could be rewritten as:
16270   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16271   //
16272   // The advantage is that the two shifts from the example would be
16273   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16274   // the vector shift into four scalar shifts plus four pairs of vector
16275   // insert/extract.
16276   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16277       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16278     unsigned TargetOpcode = X86ISD::MOVSS;
16279     bool CanBeSimplified;
16280     // The splat value for the first packed shift (the 'X' from the example).
16281     SDValue Amt1 = Amt->getOperand(0);
16282     // The splat value for the second packed shift (the 'Y' from the example).
16283     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16284                                         Amt->getOperand(2);
16285
16286     // See if it is possible to replace this node with a sequence of
16287     // two shifts followed by a MOVSS/MOVSD
16288     if (VT == MVT::v4i32) {
16289       // Check if it is legal to use a MOVSS.
16290       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16291                         Amt2 == Amt->getOperand(3);
16292       if (!CanBeSimplified) {
16293         // Otherwise, check if we can still simplify this node using a MOVSD.
16294         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16295                           Amt->getOperand(2) == Amt->getOperand(3);
16296         TargetOpcode = X86ISD::MOVSD;
16297         Amt2 = Amt->getOperand(2);
16298       }
16299     } else {
16300       // Do similar checks for the case where the machine value type
16301       // is MVT::v8i16.
16302       CanBeSimplified = Amt1 == Amt->getOperand(1);
16303       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16304         CanBeSimplified = Amt2 == Amt->getOperand(i);
16305
16306       if (!CanBeSimplified) {
16307         TargetOpcode = X86ISD::MOVSD;
16308         CanBeSimplified = true;
16309         Amt2 = Amt->getOperand(4);
16310         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16311           CanBeSimplified = Amt1 == Amt->getOperand(i);
16312         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16313           CanBeSimplified = Amt2 == Amt->getOperand(j);
16314       }
16315     }
16316     
16317     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16318         isa<ConstantSDNode>(Amt2)) {
16319       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16320       EVT CastVT = MVT::v4i32;
16321       SDValue Splat1 = 
16322         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16323       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16324       SDValue Splat2 = 
16325         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16326       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16327       if (TargetOpcode == X86ISD::MOVSD)
16328         CastVT = MVT::v2i64;
16329       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16330       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16331       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16332                                             BitCast1, DAG);
16333       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16334     }
16335   }
16336
16337   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16338     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16339
16340     // a = a << 5;
16341     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16342     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16343
16344     // Turn 'a' into a mask suitable for VSELECT
16345     SDValue VSelM = DAG.getConstant(0x80, VT);
16346     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16347     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16348
16349     SDValue CM1 = DAG.getConstant(0x0f, VT);
16350     SDValue CM2 = DAG.getConstant(0x3f, VT);
16351
16352     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16353     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16354     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16355     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16356     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16357
16358     // a += a
16359     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16360     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16361     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16362
16363     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16364     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16365     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16366     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16367     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16368
16369     // a += a
16370     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16371     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16372     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16373
16374     // return VSELECT(r, r+r, a);
16375     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16376                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16377     return R;
16378   }
16379
16380   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16381   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16382   // solution better.
16383   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16384     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16385     unsigned ExtOpc =
16386         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16387     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16388     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16389     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16390                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16391     }
16392
16393   // Decompose 256-bit shifts into smaller 128-bit shifts.
16394   if (VT.is256BitVector()) {
16395     unsigned NumElems = VT.getVectorNumElements();
16396     MVT EltVT = VT.getVectorElementType();
16397     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16398
16399     // Extract the two vectors
16400     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16401     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16402
16403     // Recreate the shift amount vectors
16404     SDValue Amt1, Amt2;
16405     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16406       // Constant shift amount
16407       SmallVector<SDValue, 4> Amt1Csts;
16408       SmallVector<SDValue, 4> Amt2Csts;
16409       for (unsigned i = 0; i != NumElems/2; ++i)
16410         Amt1Csts.push_back(Amt->getOperand(i));
16411       for (unsigned i = NumElems/2; i != NumElems; ++i)
16412         Amt2Csts.push_back(Amt->getOperand(i));
16413
16414       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16415       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16416     } else {
16417       // Variable shift amount
16418       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16419       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16420     }
16421
16422     // Issue new vector shifts for the smaller types
16423     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16424     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16425
16426     // Concatenate the result back
16427     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16428   }
16429
16430   return SDValue();
16431 }
16432
16433 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16434   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16435   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16436   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16437   // has only one use.
16438   SDNode *N = Op.getNode();
16439   SDValue LHS = N->getOperand(0);
16440   SDValue RHS = N->getOperand(1);
16441   unsigned BaseOp = 0;
16442   unsigned Cond = 0;
16443   SDLoc DL(Op);
16444   switch (Op.getOpcode()) {
16445   default: llvm_unreachable("Unknown ovf instruction!");
16446   case ISD::SADDO:
16447     // A subtract of one will be selected as a INC. Note that INC doesn't
16448     // set CF, so we can't do this for UADDO.
16449     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16450       if (C->isOne()) {
16451         BaseOp = X86ISD::INC;
16452         Cond = X86::COND_O;
16453         break;
16454       }
16455     BaseOp = X86ISD::ADD;
16456     Cond = X86::COND_O;
16457     break;
16458   case ISD::UADDO:
16459     BaseOp = X86ISD::ADD;
16460     Cond = X86::COND_B;
16461     break;
16462   case ISD::SSUBO:
16463     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16464     // set CF, so we can't do this for USUBO.
16465     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16466       if (C->isOne()) {
16467         BaseOp = X86ISD::DEC;
16468         Cond = X86::COND_O;
16469         break;
16470       }
16471     BaseOp = X86ISD::SUB;
16472     Cond = X86::COND_O;
16473     break;
16474   case ISD::USUBO:
16475     BaseOp = X86ISD::SUB;
16476     Cond = X86::COND_B;
16477     break;
16478   case ISD::SMULO:
16479     BaseOp = X86ISD::SMUL;
16480     Cond = X86::COND_O;
16481     break;
16482   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16483     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16484                                  MVT::i32);
16485     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16486
16487     SDValue SetCC =
16488       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16489                   DAG.getConstant(X86::COND_O, MVT::i32),
16490                   SDValue(Sum.getNode(), 2));
16491
16492     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16493   }
16494   }
16495
16496   // Also sets EFLAGS.
16497   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16498   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16499
16500   SDValue SetCC =
16501     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16502                 DAG.getConstant(Cond, MVT::i32),
16503                 SDValue(Sum.getNode(), 1));
16504
16505   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16506 }
16507
16508 // Sign extension of the low part of vector elements. This may be used either
16509 // when sign extend instructions are not available or if the vector element
16510 // sizes already match the sign-extended size. If the vector elements are in
16511 // their pre-extended size and sign extend instructions are available, that will
16512 // be handled by LowerSIGN_EXTEND.
16513 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16514                                                   SelectionDAG &DAG) const {
16515   SDLoc dl(Op);
16516   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16517   MVT VT = Op.getSimpleValueType();
16518
16519   if (!Subtarget->hasSSE2() || !VT.isVector())
16520     return SDValue();
16521
16522   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16523                       ExtraVT.getScalarType().getSizeInBits();
16524
16525   switch (VT.SimpleTy) {
16526     default: return SDValue();
16527     case MVT::v8i32:
16528     case MVT::v16i16:
16529       if (!Subtarget->hasFp256())
16530         return SDValue();
16531       if (!Subtarget->hasInt256()) {
16532         // needs to be split
16533         unsigned NumElems = VT.getVectorNumElements();
16534
16535         // Extract the LHS vectors
16536         SDValue LHS = Op.getOperand(0);
16537         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16538         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16539
16540         MVT EltVT = VT.getVectorElementType();
16541         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16542
16543         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16544         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16545         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16546                                    ExtraNumElems/2);
16547         SDValue Extra = DAG.getValueType(ExtraVT);
16548
16549         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16550         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16551
16552         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16553       }
16554       // fall through
16555     case MVT::v4i32:
16556     case MVT::v8i16: {
16557       SDValue Op0 = Op.getOperand(0);
16558
16559       // This is a sign extension of some low part of vector elements without
16560       // changing the size of the vector elements themselves:
16561       // Shift-Left + Shift-Right-Algebraic.
16562       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
16563                                                BitsDiff, DAG);
16564       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
16565                                         DAG);
16566     }
16567   }
16568 }
16569
16570 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16571                                  SelectionDAG &DAG) {
16572   SDLoc dl(Op);
16573   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16574     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16575   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16576     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16577
16578   // The only fence that needs an instruction is a sequentially-consistent
16579   // cross-thread fence.
16580   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16581     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16582     // no-sse2). There isn't any reason to disable it if the target processor
16583     // supports it.
16584     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16585       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16586
16587     SDValue Chain = Op.getOperand(0);
16588     SDValue Zero = DAG.getConstant(0, MVT::i32);
16589     SDValue Ops[] = {
16590       DAG.getRegister(X86::ESP, MVT::i32), // Base
16591       DAG.getTargetConstant(1, MVT::i8),   // Scale
16592       DAG.getRegister(0, MVT::i32),        // Index
16593       DAG.getTargetConstant(0, MVT::i32),  // Disp
16594       DAG.getRegister(0, MVT::i32),        // Segment.
16595       Zero,
16596       Chain
16597     };
16598     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16599     return SDValue(Res, 0);
16600   }
16601
16602   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16603   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16604 }
16605
16606 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16607                              SelectionDAG &DAG) {
16608   MVT T = Op.getSimpleValueType();
16609   SDLoc DL(Op);
16610   unsigned Reg = 0;
16611   unsigned size = 0;
16612   switch(T.SimpleTy) {
16613   default: llvm_unreachable("Invalid value type!");
16614   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16615   case MVT::i16: Reg = X86::AX;  size = 2; break;
16616   case MVT::i32: Reg = X86::EAX; size = 4; break;
16617   case MVT::i64:
16618     assert(Subtarget->is64Bit() && "Node not type legal!");
16619     Reg = X86::RAX; size = 8;
16620     break;
16621   }
16622   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16623                                   Op.getOperand(2), SDValue());
16624   SDValue Ops[] = { cpIn.getValue(0),
16625                     Op.getOperand(1),
16626                     Op.getOperand(3),
16627                     DAG.getTargetConstant(size, MVT::i8),
16628                     cpIn.getValue(1) };
16629   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16630   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16631   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16632                                            Ops, T, MMO);
16633
16634   SDValue cpOut =
16635     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16636   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16637                                       MVT::i32, cpOut.getValue(2));
16638   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16639                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16640
16641   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16642   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16643   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16644   return SDValue();
16645 }
16646
16647 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16648                             SelectionDAG &DAG) {
16649   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16650   MVT DstVT = Op.getSimpleValueType();
16651
16652   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16653     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16654     if (DstVT != MVT::f64)
16655       // This conversion needs to be expanded.
16656       return SDValue();
16657
16658     SDValue InVec = Op->getOperand(0);
16659     SDLoc dl(Op);
16660     unsigned NumElts = SrcVT.getVectorNumElements();
16661     EVT SVT = SrcVT.getVectorElementType();
16662
16663     // Widen the vector in input in the case of MVT::v2i32.
16664     // Example: from MVT::v2i32 to MVT::v4i32.
16665     SmallVector<SDValue, 16> Elts;
16666     for (unsigned i = 0, e = NumElts; i != e; ++i)
16667       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16668                                  DAG.getIntPtrConstant(i)));
16669
16670     // Explicitly mark the extra elements as Undef.
16671     SDValue Undef = DAG.getUNDEF(SVT);
16672     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16673       Elts.push_back(Undef);
16674
16675     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16676     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16677     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16678     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16679                        DAG.getIntPtrConstant(0));
16680   }
16681
16682   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16683          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16684   assert((DstVT == MVT::i64 ||
16685           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16686          "Unexpected custom BITCAST");
16687   // i64 <=> MMX conversions are Legal.
16688   if (SrcVT==MVT::i64 && DstVT.isVector())
16689     return Op;
16690   if (DstVT==MVT::i64 && SrcVT.isVector())
16691     return Op;
16692   // MMX <=> MMX conversions are Legal.
16693   if (SrcVT.isVector() && DstVT.isVector())
16694     return Op;
16695   // All other conversions need to be expanded.
16696   return SDValue();
16697 }
16698
16699 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16700   SDNode *Node = Op.getNode();
16701   SDLoc dl(Node);
16702   EVT T = Node->getValueType(0);
16703   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16704                               DAG.getConstant(0, T), Node->getOperand(2));
16705   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16706                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16707                        Node->getOperand(0),
16708                        Node->getOperand(1), negOp,
16709                        cast<AtomicSDNode>(Node)->getMemOperand(),
16710                        cast<AtomicSDNode>(Node)->getOrdering(),
16711                        cast<AtomicSDNode>(Node)->getSynchScope());
16712 }
16713
16714 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16715   SDNode *Node = Op.getNode();
16716   SDLoc dl(Node);
16717   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16718
16719   // Convert seq_cst store -> xchg
16720   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16721   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16722   //        (The only way to get a 16-byte store is cmpxchg16b)
16723   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16724   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16725       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16726     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16727                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16728                                  Node->getOperand(0),
16729                                  Node->getOperand(1), Node->getOperand(2),
16730                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16731                                  cast<AtomicSDNode>(Node)->getOrdering(),
16732                                  cast<AtomicSDNode>(Node)->getSynchScope());
16733     return Swap.getValue(1);
16734   }
16735   // Other atomic stores have a simple pattern.
16736   return Op;
16737 }
16738
16739 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16740   EVT VT = Op.getNode()->getSimpleValueType(0);
16741
16742   // Let legalize expand this if it isn't a legal type yet.
16743   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16744     return SDValue();
16745
16746   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16747
16748   unsigned Opc;
16749   bool ExtraOp = false;
16750   switch (Op.getOpcode()) {
16751   default: llvm_unreachable("Invalid code");
16752   case ISD::ADDC: Opc = X86ISD::ADD; break;
16753   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16754   case ISD::SUBC: Opc = X86ISD::SUB; break;
16755   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16756   }
16757
16758   if (!ExtraOp)
16759     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16760                        Op.getOperand(1));
16761   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16762                      Op.getOperand(1), Op.getOperand(2));
16763 }
16764
16765 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16766                             SelectionDAG &DAG) {
16767   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16768
16769   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16770   // which returns the values as { float, float } (in XMM0) or
16771   // { double, double } (which is returned in XMM0, XMM1).
16772   SDLoc dl(Op);
16773   SDValue Arg = Op.getOperand(0);
16774   EVT ArgVT = Arg.getValueType();
16775   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16776
16777   TargetLowering::ArgListTy Args;
16778   TargetLowering::ArgListEntry Entry;
16779
16780   Entry.Node = Arg;
16781   Entry.Ty = ArgTy;
16782   Entry.isSExt = false;
16783   Entry.isZExt = false;
16784   Args.push_back(Entry);
16785
16786   bool isF64 = ArgVT == MVT::f64;
16787   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16788   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16789   // the results are returned via SRet in memory.
16790   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16792   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16793
16794   Type *RetTy = isF64
16795     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16796     : (Type*)VectorType::get(ArgTy, 4);
16797
16798   TargetLowering::CallLoweringInfo CLI(DAG);
16799   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16800     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16801
16802   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16803
16804   if (isF64)
16805     // Returned in xmm0 and xmm1.
16806     return CallResult.first;
16807
16808   // Returned in bits 0:31 and 32:64 xmm0.
16809   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16810                                CallResult.first, DAG.getIntPtrConstant(0));
16811   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16812                                CallResult.first, DAG.getIntPtrConstant(1));
16813   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16814   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16815 }
16816
16817 /// LowerOperation - Provide custom lowering hooks for some operations.
16818 ///
16819 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16820   switch (Op.getOpcode()) {
16821   default: llvm_unreachable("Should not custom lower this!");
16822   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16823   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16824   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16825     return LowerCMP_SWAP(Op, Subtarget, DAG);
16826   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16827   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16828   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16829   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16830   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16831   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16832   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16833   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16834   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16835   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16836   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16837   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16838   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16839   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16840   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16841   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16842   case ISD::SHL_PARTS:
16843   case ISD::SRA_PARTS:
16844   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16845   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16846   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16847   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16848   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16849   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16850   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16851   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16852   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16853   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16854   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16855   case ISD::FABS:               return LowerFABS(Op, DAG);
16856   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16857   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16858   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16859   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16860   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16861   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16862   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16863   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16864   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16865   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16866   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16867   case ISD::INTRINSIC_VOID:
16868   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16869   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16870   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16871   case ISD::FRAME_TO_ARGS_OFFSET:
16872                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16873   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16874   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16875   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16876   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16877   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16878   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16879   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16880   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16881   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16882   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16883   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16884   case ISD::UMUL_LOHI:
16885   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16886   case ISD::SRA:
16887   case ISD::SRL:
16888   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16889   case ISD::SADDO:
16890   case ISD::UADDO:
16891   case ISD::SSUBO:
16892   case ISD::USUBO:
16893   case ISD::SMULO:
16894   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16895   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16896   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16897   case ISD::ADDC:
16898   case ISD::ADDE:
16899   case ISD::SUBC:
16900   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16901   case ISD::ADD:                return LowerADD(Op, DAG);
16902   case ISD::SUB:                return LowerSUB(Op, DAG);
16903   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16904   }
16905 }
16906
16907 static void ReplaceATOMIC_LOAD(SDNode *Node,
16908                                SmallVectorImpl<SDValue> &Results,
16909                                SelectionDAG &DAG) {
16910   SDLoc dl(Node);
16911   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16912
16913   // Convert wide load -> cmpxchg8b/cmpxchg16b
16914   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16915   //        (The only way to get a 16-byte load is cmpxchg16b)
16916   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16917   SDValue Zero = DAG.getConstant(0, VT);
16918   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16919   SDValue Swap =
16920       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16921                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16922                            cast<AtomicSDNode>(Node)->getMemOperand(),
16923                            cast<AtomicSDNode>(Node)->getOrdering(),
16924                            cast<AtomicSDNode>(Node)->getOrdering(),
16925                            cast<AtomicSDNode>(Node)->getSynchScope());
16926   Results.push_back(Swap.getValue(0));
16927   Results.push_back(Swap.getValue(2));
16928 }
16929
16930 /// ReplaceNodeResults - Replace a node with an illegal result type
16931 /// with a new node built out of custom code.
16932 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16933                                            SmallVectorImpl<SDValue>&Results,
16934                                            SelectionDAG &DAG) const {
16935   SDLoc dl(N);
16936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16937   switch (N->getOpcode()) {
16938   default:
16939     llvm_unreachable("Do not know how to custom type legalize this operation!");
16940   case ISD::SIGN_EXTEND_INREG:
16941   case ISD::ADDC:
16942   case ISD::ADDE:
16943   case ISD::SUBC:
16944   case ISD::SUBE:
16945     // We don't want to expand or promote these.
16946     return;
16947   case ISD::SDIV:
16948   case ISD::UDIV:
16949   case ISD::SREM:
16950   case ISD::UREM:
16951   case ISD::SDIVREM:
16952   case ISD::UDIVREM: {
16953     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16954     Results.push_back(V);
16955     return;
16956   }
16957   case ISD::FP_TO_SINT:
16958   case ISD::FP_TO_UINT: {
16959     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16960
16961     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16962       return;
16963
16964     std::pair<SDValue,SDValue> Vals =
16965         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16966     SDValue FIST = Vals.first, StackSlot = Vals.second;
16967     if (FIST.getNode()) {
16968       EVT VT = N->getValueType(0);
16969       // Return a load from the stack slot.
16970       if (StackSlot.getNode())
16971         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16972                                       MachinePointerInfo(),
16973                                       false, false, false, 0));
16974       else
16975         Results.push_back(FIST);
16976     }
16977     return;
16978   }
16979   case ISD::UINT_TO_FP: {
16980     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16981     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16982         N->getValueType(0) != MVT::v2f32)
16983       return;
16984     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16985                                  N->getOperand(0));
16986     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16987                                      MVT::f64);
16988     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16989     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16990                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16991     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16992     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16993     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16994     return;
16995   }
16996   case ISD::FP_ROUND: {
16997     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16998         return;
16999     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17000     Results.push_back(V);
17001     return;
17002   }
17003   case ISD::INTRINSIC_W_CHAIN: {
17004     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17005     switch (IntNo) {
17006     default : llvm_unreachable("Do not know how to custom type "
17007                                "legalize this intrinsic operation!");
17008     case Intrinsic::x86_rdtsc:
17009       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17010                                      Results);
17011     case Intrinsic::x86_rdtscp:
17012       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17013                                      Results);
17014     case Intrinsic::x86_rdpmc:
17015       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17016     }
17017   }
17018   case ISD::READCYCLECOUNTER: {
17019     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17020                                    Results);
17021   }
17022   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17023     EVT T = N->getValueType(0);
17024     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17025     bool Regs64bit = T == MVT::i128;
17026     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17027     SDValue cpInL, cpInH;
17028     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17029                         DAG.getConstant(0, HalfT));
17030     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17031                         DAG.getConstant(1, HalfT));
17032     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17033                              Regs64bit ? X86::RAX : X86::EAX,
17034                              cpInL, SDValue());
17035     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17036                              Regs64bit ? X86::RDX : X86::EDX,
17037                              cpInH, cpInL.getValue(1));
17038     SDValue swapInL, swapInH;
17039     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17040                           DAG.getConstant(0, HalfT));
17041     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17042                           DAG.getConstant(1, HalfT));
17043     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17044                                Regs64bit ? X86::RBX : X86::EBX,
17045                                swapInL, cpInH.getValue(1));
17046     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17047                                Regs64bit ? X86::RCX : X86::ECX,
17048                                swapInH, swapInL.getValue(1));
17049     SDValue Ops[] = { swapInH.getValue(0),
17050                       N->getOperand(1),
17051                       swapInH.getValue(1) };
17052     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17053     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17054     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17055                                   X86ISD::LCMPXCHG8_DAG;
17056     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17057     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17058                                         Regs64bit ? X86::RAX : X86::EAX,
17059                                         HalfT, Result.getValue(1));
17060     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17061                                         Regs64bit ? X86::RDX : X86::EDX,
17062                                         HalfT, cpOutL.getValue(2));
17063     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17064
17065     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17066                                         MVT::i32, cpOutH.getValue(2));
17067     SDValue Success =
17068         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17069                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17070     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17071
17072     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17073     Results.push_back(Success);
17074     Results.push_back(EFLAGS.getValue(1));
17075     return;
17076   }
17077   case ISD::ATOMIC_SWAP:
17078   case ISD::ATOMIC_LOAD_ADD:
17079   case ISD::ATOMIC_LOAD_SUB:
17080   case ISD::ATOMIC_LOAD_AND:
17081   case ISD::ATOMIC_LOAD_OR:
17082   case ISD::ATOMIC_LOAD_XOR:
17083   case ISD::ATOMIC_LOAD_NAND:
17084   case ISD::ATOMIC_LOAD_MIN:
17085   case ISD::ATOMIC_LOAD_MAX:
17086   case ISD::ATOMIC_LOAD_UMIN:
17087   case ISD::ATOMIC_LOAD_UMAX:
17088     // Delegate to generic TypeLegalization. Situations we can really handle
17089     // should have already been dealt with by X86AtomicExpandPass.cpp.
17090     break;
17091   case ISD::ATOMIC_LOAD: {
17092     ReplaceATOMIC_LOAD(N, Results, DAG);
17093     return;
17094   }
17095   case ISD::BITCAST: {
17096     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17097     EVT DstVT = N->getValueType(0);
17098     EVT SrcVT = N->getOperand(0)->getValueType(0);
17099
17100     if (SrcVT != MVT::f64 ||
17101         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17102       return;
17103
17104     unsigned NumElts = DstVT.getVectorNumElements();
17105     EVT SVT = DstVT.getVectorElementType();
17106     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17107     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17108                                    MVT::v2f64, N->getOperand(0));
17109     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17110
17111     if (ExperimentalVectorWideningLegalization) {
17112       // If we are legalizing vectors by widening, we already have the desired
17113       // legal vector type, just return it.
17114       Results.push_back(ToVecInt);
17115       return;
17116     }
17117
17118     SmallVector<SDValue, 8> Elts;
17119     for (unsigned i = 0, e = NumElts; i != e; ++i)
17120       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17121                                    ToVecInt, DAG.getIntPtrConstant(i)));
17122
17123     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17124   }
17125   }
17126 }
17127
17128 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17129   switch (Opcode) {
17130   default: return nullptr;
17131   case X86ISD::BSF:                return "X86ISD::BSF";
17132   case X86ISD::BSR:                return "X86ISD::BSR";
17133   case X86ISD::SHLD:               return "X86ISD::SHLD";
17134   case X86ISD::SHRD:               return "X86ISD::SHRD";
17135   case X86ISD::FAND:               return "X86ISD::FAND";
17136   case X86ISD::FANDN:              return "X86ISD::FANDN";
17137   case X86ISD::FOR:                return "X86ISD::FOR";
17138   case X86ISD::FXOR:               return "X86ISD::FXOR";
17139   case X86ISD::FSRL:               return "X86ISD::FSRL";
17140   case X86ISD::FILD:               return "X86ISD::FILD";
17141   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17142   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17143   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17144   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17145   case X86ISD::FLD:                return "X86ISD::FLD";
17146   case X86ISD::FST:                return "X86ISD::FST";
17147   case X86ISD::CALL:               return "X86ISD::CALL";
17148   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17149   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17150   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17151   case X86ISD::BT:                 return "X86ISD::BT";
17152   case X86ISD::CMP:                return "X86ISD::CMP";
17153   case X86ISD::COMI:               return "X86ISD::COMI";
17154   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17155   case X86ISD::CMPM:               return "X86ISD::CMPM";
17156   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17157   case X86ISD::SETCC:              return "X86ISD::SETCC";
17158   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17159   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17160   case X86ISD::CMOV:               return "X86ISD::CMOV";
17161   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17162   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17163   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17164   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17165   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17166   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17167   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17168   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17169   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17170   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17171   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17172   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17173   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17174   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17175   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17176   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17177   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17178   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17179   case X86ISD::HADD:               return "X86ISD::HADD";
17180   case X86ISD::HSUB:               return "X86ISD::HSUB";
17181   case X86ISD::FHADD:              return "X86ISD::FHADD";
17182   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17183   case X86ISD::UMAX:               return "X86ISD::UMAX";
17184   case X86ISD::UMIN:               return "X86ISD::UMIN";
17185   case X86ISD::SMAX:               return "X86ISD::SMAX";
17186   case X86ISD::SMIN:               return "X86ISD::SMIN";
17187   case X86ISD::FMAX:               return "X86ISD::FMAX";
17188   case X86ISD::FMIN:               return "X86ISD::FMIN";
17189   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17190   case X86ISD::FMINC:              return "X86ISD::FMINC";
17191   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17192   case X86ISD::FRCP:               return "X86ISD::FRCP";
17193   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17194   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17195   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17196   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17197   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17198   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17199   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17200   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17201   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17202   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17203   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17204   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17205   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17206   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17207   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17208   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17209   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17210   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17211   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17212   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17213   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17214   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17215   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17216   case X86ISD::VSHL:               return "X86ISD::VSHL";
17217   case X86ISD::VSRL:               return "X86ISD::VSRL";
17218   case X86ISD::VSRA:               return "X86ISD::VSRA";
17219   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17220   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17221   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17222   case X86ISD::CMPP:               return "X86ISD::CMPP";
17223   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17224   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17225   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17226   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17227   case X86ISD::ADD:                return "X86ISD::ADD";
17228   case X86ISD::SUB:                return "X86ISD::SUB";
17229   case X86ISD::ADC:                return "X86ISD::ADC";
17230   case X86ISD::SBB:                return "X86ISD::SBB";
17231   case X86ISD::SMUL:               return "X86ISD::SMUL";
17232   case X86ISD::UMUL:               return "X86ISD::UMUL";
17233   case X86ISD::INC:                return "X86ISD::INC";
17234   case X86ISD::DEC:                return "X86ISD::DEC";
17235   case X86ISD::OR:                 return "X86ISD::OR";
17236   case X86ISD::XOR:                return "X86ISD::XOR";
17237   case X86ISD::AND:                return "X86ISD::AND";
17238   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17239   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17240   case X86ISD::PTEST:              return "X86ISD::PTEST";
17241   case X86ISD::TESTP:              return "X86ISD::TESTP";
17242   case X86ISD::TESTM:              return "X86ISD::TESTM";
17243   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17244   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17245   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17246   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17247   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17248   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17249   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17250   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17251   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17252   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17253   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17254   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17255   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17256   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17257   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17258   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17259   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17260   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17261   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17262   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17263   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17264   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17265   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17266   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17267   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17268   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17269   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17270   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17271   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17272   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17273   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17274   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17275   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17276   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17277   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17278   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17279   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17280   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17281   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17282   case X86ISD::SAHF:               return "X86ISD::SAHF";
17283   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17284   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17285   case X86ISD::FMADD:              return "X86ISD::FMADD";
17286   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17287   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17288   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17289   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17290   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17291   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17292   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17293   case X86ISD::XTEST:              return "X86ISD::XTEST";
17294   }
17295 }
17296
17297 // isLegalAddressingMode - Return true if the addressing mode represented
17298 // by AM is legal for this target, for a load/store of the specified type.
17299 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17300                                               Type *Ty) const {
17301   // X86 supports extremely general addressing modes.
17302   CodeModel::Model M = getTargetMachine().getCodeModel();
17303   Reloc::Model R = getTargetMachine().getRelocationModel();
17304
17305   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17306   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17307     return false;
17308
17309   if (AM.BaseGV) {
17310     unsigned GVFlags =
17311       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17312
17313     // If a reference to this global requires an extra load, we can't fold it.
17314     if (isGlobalStubReference(GVFlags))
17315       return false;
17316
17317     // If BaseGV requires a register for the PIC base, we cannot also have a
17318     // BaseReg specified.
17319     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17320       return false;
17321
17322     // If lower 4G is not available, then we must use rip-relative addressing.
17323     if ((M != CodeModel::Small || R != Reloc::Static) &&
17324         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17325       return false;
17326   }
17327
17328   switch (AM.Scale) {
17329   case 0:
17330   case 1:
17331   case 2:
17332   case 4:
17333   case 8:
17334     // These scales always work.
17335     break;
17336   case 3:
17337   case 5:
17338   case 9:
17339     // These scales are formed with basereg+scalereg.  Only accept if there is
17340     // no basereg yet.
17341     if (AM.HasBaseReg)
17342       return false;
17343     break;
17344   default:  // Other stuff never works.
17345     return false;
17346   }
17347
17348   return true;
17349 }
17350
17351 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17352   unsigned Bits = Ty->getScalarSizeInBits();
17353
17354   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17355   // particularly cheaper than those without.
17356   if (Bits == 8)
17357     return false;
17358
17359   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17360   // variable shifts just as cheap as scalar ones.
17361   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17362     return false;
17363
17364   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17365   // fully general vector.
17366   return true;
17367 }
17368
17369 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17370   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17371     return false;
17372   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17373   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17374   return NumBits1 > NumBits2;
17375 }
17376
17377 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17378   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17379     return false;
17380
17381   if (!isTypeLegal(EVT::getEVT(Ty1)))
17382     return false;
17383
17384   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17385
17386   // Assuming the caller doesn't have a zeroext or signext return parameter,
17387   // truncation all the way down to i1 is valid.
17388   return true;
17389 }
17390
17391 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17392   return isInt<32>(Imm);
17393 }
17394
17395 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17396   // Can also use sub to handle negated immediates.
17397   return isInt<32>(Imm);
17398 }
17399
17400 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17401   if (!VT1.isInteger() || !VT2.isInteger())
17402     return false;
17403   unsigned NumBits1 = VT1.getSizeInBits();
17404   unsigned NumBits2 = VT2.getSizeInBits();
17405   return NumBits1 > NumBits2;
17406 }
17407
17408 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17409   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17410   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17411 }
17412
17413 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17414   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17415   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17416 }
17417
17418 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17419   EVT VT1 = Val.getValueType();
17420   if (isZExtFree(VT1, VT2))
17421     return true;
17422
17423   if (Val.getOpcode() != ISD::LOAD)
17424     return false;
17425
17426   if (!VT1.isSimple() || !VT1.isInteger() ||
17427       !VT2.isSimple() || !VT2.isInteger())
17428     return false;
17429
17430   switch (VT1.getSimpleVT().SimpleTy) {
17431   default: break;
17432   case MVT::i8:
17433   case MVT::i16:
17434   case MVT::i32:
17435     // X86 has 8, 16, and 32-bit zero-extending loads.
17436     return true;
17437   }
17438
17439   return false;
17440 }
17441
17442 bool
17443 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17444   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17445     return false;
17446
17447   VT = VT.getScalarType();
17448
17449   if (!VT.isSimple())
17450     return false;
17451
17452   switch (VT.getSimpleVT().SimpleTy) {
17453   case MVT::f32:
17454   case MVT::f64:
17455     return true;
17456   default:
17457     break;
17458   }
17459
17460   return false;
17461 }
17462
17463 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17464   // i16 instructions are longer (0x66 prefix) and potentially slower.
17465   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17466 }
17467
17468 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17469 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17470 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17471 /// are assumed to be legal.
17472 bool
17473 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17474                                       EVT VT) const {
17475   if (!VT.isSimple())
17476     return false;
17477
17478   MVT SVT = VT.getSimpleVT();
17479
17480   // Very little shuffling can be done for 64-bit vectors right now.
17481   if (VT.getSizeInBits() == 64)
17482     return false;
17483
17484   // If this is a single-input shuffle with no 128 bit lane crossings we can
17485   // lower it into pshufb.
17486   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17487       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17488     bool isLegal = true;
17489     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17490       if (M[I] >= (int)SVT.getVectorNumElements() ||
17491           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17492         isLegal = false;
17493         break;
17494       }
17495     }
17496     if (isLegal)
17497       return true;
17498   }
17499
17500   // FIXME: blends, shifts.
17501   return (SVT.getVectorNumElements() == 2 ||
17502           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17503           isMOVLMask(M, SVT) ||
17504           isMOVHLPSMask(M, SVT) ||
17505           isSHUFPMask(M, SVT) ||
17506           isPSHUFDMask(M, SVT) ||
17507           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17508           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17509           isPALIGNRMask(M, SVT, Subtarget) ||
17510           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17511           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17512           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17513           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17514           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17515 }
17516
17517 bool
17518 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17519                                           EVT VT) const {
17520   if (!VT.isSimple())
17521     return false;
17522
17523   MVT SVT = VT.getSimpleVT();
17524   unsigned NumElts = SVT.getVectorNumElements();
17525   // FIXME: This collection of masks seems suspect.
17526   if (NumElts == 2)
17527     return true;
17528   if (NumElts == 4 && SVT.is128BitVector()) {
17529     return (isMOVLMask(Mask, SVT)  ||
17530             isCommutedMOVLMask(Mask, SVT, true) ||
17531             isSHUFPMask(Mask, SVT) ||
17532             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17533   }
17534   return false;
17535 }
17536
17537 //===----------------------------------------------------------------------===//
17538 //                           X86 Scheduler Hooks
17539 //===----------------------------------------------------------------------===//
17540
17541 /// Utility function to emit xbegin specifying the start of an RTM region.
17542 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17543                                      const TargetInstrInfo *TII) {
17544   DebugLoc DL = MI->getDebugLoc();
17545
17546   const BasicBlock *BB = MBB->getBasicBlock();
17547   MachineFunction::iterator I = MBB;
17548   ++I;
17549
17550   // For the v = xbegin(), we generate
17551   //
17552   // thisMBB:
17553   //  xbegin sinkMBB
17554   //
17555   // mainMBB:
17556   //  eax = -1
17557   //
17558   // sinkMBB:
17559   //  v = eax
17560
17561   MachineBasicBlock *thisMBB = MBB;
17562   MachineFunction *MF = MBB->getParent();
17563   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17564   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17565   MF->insert(I, mainMBB);
17566   MF->insert(I, sinkMBB);
17567
17568   // Transfer the remainder of BB and its successor edges to sinkMBB.
17569   sinkMBB->splice(sinkMBB->begin(), MBB,
17570                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17571   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17572
17573   // thisMBB:
17574   //  xbegin sinkMBB
17575   //  # fallthrough to mainMBB
17576   //  # abortion to sinkMBB
17577   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17578   thisMBB->addSuccessor(mainMBB);
17579   thisMBB->addSuccessor(sinkMBB);
17580
17581   // mainMBB:
17582   //  EAX = -1
17583   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17584   mainMBB->addSuccessor(sinkMBB);
17585
17586   // sinkMBB:
17587   // EAX is live into the sinkMBB
17588   sinkMBB->addLiveIn(X86::EAX);
17589   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17590           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17591     .addReg(X86::EAX);
17592
17593   MI->eraseFromParent();
17594   return sinkMBB;
17595 }
17596
17597 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17598 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17599 // in the .td file.
17600 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17601                                        const TargetInstrInfo *TII) {
17602   unsigned Opc;
17603   switch (MI->getOpcode()) {
17604   default: llvm_unreachable("illegal opcode!");
17605   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17606   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17607   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17608   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17609   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17610   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17611   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17612   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17613   }
17614
17615   DebugLoc dl = MI->getDebugLoc();
17616   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17617
17618   unsigned NumArgs = MI->getNumOperands();
17619   for (unsigned i = 1; i < NumArgs; ++i) {
17620     MachineOperand &Op = MI->getOperand(i);
17621     if (!(Op.isReg() && Op.isImplicit()))
17622       MIB.addOperand(Op);
17623   }
17624   if (MI->hasOneMemOperand())
17625     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17626
17627   BuildMI(*BB, MI, dl,
17628     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17629     .addReg(X86::XMM0);
17630
17631   MI->eraseFromParent();
17632   return BB;
17633 }
17634
17635 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17636 // defs in an instruction pattern
17637 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17638                                        const TargetInstrInfo *TII) {
17639   unsigned Opc;
17640   switch (MI->getOpcode()) {
17641   default: llvm_unreachable("illegal opcode!");
17642   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17643   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17644   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17645   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17646   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17647   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17648   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17649   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17650   }
17651
17652   DebugLoc dl = MI->getDebugLoc();
17653   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17654
17655   unsigned NumArgs = MI->getNumOperands(); // remove the results
17656   for (unsigned i = 1; i < NumArgs; ++i) {
17657     MachineOperand &Op = MI->getOperand(i);
17658     if (!(Op.isReg() && Op.isImplicit()))
17659       MIB.addOperand(Op);
17660   }
17661   if (MI->hasOneMemOperand())
17662     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17663
17664   BuildMI(*BB, MI, dl,
17665     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17666     .addReg(X86::ECX);
17667
17668   MI->eraseFromParent();
17669   return BB;
17670 }
17671
17672 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17673                                        const TargetInstrInfo *TII,
17674                                        const X86Subtarget* Subtarget) {
17675   DebugLoc dl = MI->getDebugLoc();
17676
17677   // Address into RAX/EAX, other two args into ECX, EDX.
17678   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17679   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17680   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17681   for (int i = 0; i < X86::AddrNumOperands; ++i)
17682     MIB.addOperand(MI->getOperand(i));
17683
17684   unsigned ValOps = X86::AddrNumOperands;
17685   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17686     .addReg(MI->getOperand(ValOps).getReg());
17687   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17688     .addReg(MI->getOperand(ValOps+1).getReg());
17689
17690   // The instruction doesn't actually take any operands though.
17691   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17692
17693   MI->eraseFromParent(); // The pseudo is gone now.
17694   return BB;
17695 }
17696
17697 MachineBasicBlock *
17698 X86TargetLowering::EmitVAARG64WithCustomInserter(
17699                    MachineInstr *MI,
17700                    MachineBasicBlock *MBB) const {
17701   // Emit va_arg instruction on X86-64.
17702
17703   // Operands to this pseudo-instruction:
17704   // 0  ) Output        : destination address (reg)
17705   // 1-5) Input         : va_list address (addr, i64mem)
17706   // 6  ) ArgSize       : Size (in bytes) of vararg type
17707   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17708   // 8  ) Align         : Alignment of type
17709   // 9  ) EFLAGS (implicit-def)
17710
17711   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17712   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17713
17714   unsigned DestReg = MI->getOperand(0).getReg();
17715   MachineOperand &Base = MI->getOperand(1);
17716   MachineOperand &Scale = MI->getOperand(2);
17717   MachineOperand &Index = MI->getOperand(3);
17718   MachineOperand &Disp = MI->getOperand(4);
17719   MachineOperand &Segment = MI->getOperand(5);
17720   unsigned ArgSize = MI->getOperand(6).getImm();
17721   unsigned ArgMode = MI->getOperand(7).getImm();
17722   unsigned Align = MI->getOperand(8).getImm();
17723
17724   // Memory Reference
17725   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17726   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17727   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17728
17729   // Machine Information
17730   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17731   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17732   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17733   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17734   DebugLoc DL = MI->getDebugLoc();
17735
17736   // struct va_list {
17737   //   i32   gp_offset
17738   //   i32   fp_offset
17739   //   i64   overflow_area (address)
17740   //   i64   reg_save_area (address)
17741   // }
17742   // sizeof(va_list) = 24
17743   // alignment(va_list) = 8
17744
17745   unsigned TotalNumIntRegs = 6;
17746   unsigned TotalNumXMMRegs = 8;
17747   bool UseGPOffset = (ArgMode == 1);
17748   bool UseFPOffset = (ArgMode == 2);
17749   unsigned MaxOffset = TotalNumIntRegs * 8 +
17750                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17751
17752   /* Align ArgSize to a multiple of 8 */
17753   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17754   bool NeedsAlign = (Align > 8);
17755
17756   MachineBasicBlock *thisMBB = MBB;
17757   MachineBasicBlock *overflowMBB;
17758   MachineBasicBlock *offsetMBB;
17759   MachineBasicBlock *endMBB;
17760
17761   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17762   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17763   unsigned OffsetReg = 0;
17764
17765   if (!UseGPOffset && !UseFPOffset) {
17766     // If we only pull from the overflow region, we don't create a branch.
17767     // We don't need to alter control flow.
17768     OffsetDestReg = 0; // unused
17769     OverflowDestReg = DestReg;
17770
17771     offsetMBB = nullptr;
17772     overflowMBB = thisMBB;
17773     endMBB = thisMBB;
17774   } else {
17775     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17776     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17777     // If not, pull from overflow_area. (branch to overflowMBB)
17778     //
17779     //       thisMBB
17780     //         |     .
17781     //         |        .
17782     //     offsetMBB   overflowMBB
17783     //         |        .
17784     //         |     .
17785     //        endMBB
17786
17787     // Registers for the PHI in endMBB
17788     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17789     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17790
17791     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17792     MachineFunction *MF = MBB->getParent();
17793     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17794     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17795     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17796
17797     MachineFunction::iterator MBBIter = MBB;
17798     ++MBBIter;
17799
17800     // Insert the new basic blocks
17801     MF->insert(MBBIter, offsetMBB);
17802     MF->insert(MBBIter, overflowMBB);
17803     MF->insert(MBBIter, endMBB);
17804
17805     // Transfer the remainder of MBB and its successor edges to endMBB.
17806     endMBB->splice(endMBB->begin(), thisMBB,
17807                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17808     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17809
17810     // Make offsetMBB and overflowMBB successors of thisMBB
17811     thisMBB->addSuccessor(offsetMBB);
17812     thisMBB->addSuccessor(overflowMBB);
17813
17814     // endMBB is a successor of both offsetMBB and overflowMBB
17815     offsetMBB->addSuccessor(endMBB);
17816     overflowMBB->addSuccessor(endMBB);
17817
17818     // Load the offset value into a register
17819     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17820     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17821       .addOperand(Base)
17822       .addOperand(Scale)
17823       .addOperand(Index)
17824       .addDisp(Disp, UseFPOffset ? 4 : 0)
17825       .addOperand(Segment)
17826       .setMemRefs(MMOBegin, MMOEnd);
17827
17828     // Check if there is enough room left to pull this argument.
17829     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17830       .addReg(OffsetReg)
17831       .addImm(MaxOffset + 8 - ArgSizeA8);
17832
17833     // Branch to "overflowMBB" if offset >= max
17834     // Fall through to "offsetMBB" otherwise
17835     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17836       .addMBB(overflowMBB);
17837   }
17838
17839   // In offsetMBB, emit code to use the reg_save_area.
17840   if (offsetMBB) {
17841     assert(OffsetReg != 0);
17842
17843     // Read the reg_save_area address.
17844     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17845     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17846       .addOperand(Base)
17847       .addOperand(Scale)
17848       .addOperand(Index)
17849       .addDisp(Disp, 16)
17850       .addOperand(Segment)
17851       .setMemRefs(MMOBegin, MMOEnd);
17852
17853     // Zero-extend the offset
17854     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17855       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17856         .addImm(0)
17857         .addReg(OffsetReg)
17858         .addImm(X86::sub_32bit);
17859
17860     // Add the offset to the reg_save_area to get the final address.
17861     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17862       .addReg(OffsetReg64)
17863       .addReg(RegSaveReg);
17864
17865     // Compute the offset for the next argument
17866     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17867     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17868       .addReg(OffsetReg)
17869       .addImm(UseFPOffset ? 16 : 8);
17870
17871     // Store it back into the va_list.
17872     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17873       .addOperand(Base)
17874       .addOperand(Scale)
17875       .addOperand(Index)
17876       .addDisp(Disp, UseFPOffset ? 4 : 0)
17877       .addOperand(Segment)
17878       .addReg(NextOffsetReg)
17879       .setMemRefs(MMOBegin, MMOEnd);
17880
17881     // Jump to endMBB
17882     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17883       .addMBB(endMBB);
17884   }
17885
17886   //
17887   // Emit code to use overflow area
17888   //
17889
17890   // Load the overflow_area address into a register.
17891   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17892   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17893     .addOperand(Base)
17894     .addOperand(Scale)
17895     .addOperand(Index)
17896     .addDisp(Disp, 8)
17897     .addOperand(Segment)
17898     .setMemRefs(MMOBegin, MMOEnd);
17899
17900   // If we need to align it, do so. Otherwise, just copy the address
17901   // to OverflowDestReg.
17902   if (NeedsAlign) {
17903     // Align the overflow address
17904     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17905     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17906
17907     // aligned_addr = (addr + (align-1)) & ~(align-1)
17908     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17909       .addReg(OverflowAddrReg)
17910       .addImm(Align-1);
17911
17912     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17913       .addReg(TmpReg)
17914       .addImm(~(uint64_t)(Align-1));
17915   } else {
17916     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17917       .addReg(OverflowAddrReg);
17918   }
17919
17920   // Compute the next overflow address after this argument.
17921   // (the overflow address should be kept 8-byte aligned)
17922   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17923   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17924     .addReg(OverflowDestReg)
17925     .addImm(ArgSizeA8);
17926
17927   // Store the new overflow address.
17928   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17929     .addOperand(Base)
17930     .addOperand(Scale)
17931     .addOperand(Index)
17932     .addDisp(Disp, 8)
17933     .addOperand(Segment)
17934     .addReg(NextAddrReg)
17935     .setMemRefs(MMOBegin, MMOEnd);
17936
17937   // If we branched, emit the PHI to the front of endMBB.
17938   if (offsetMBB) {
17939     BuildMI(*endMBB, endMBB->begin(), DL,
17940             TII->get(X86::PHI), DestReg)
17941       .addReg(OffsetDestReg).addMBB(offsetMBB)
17942       .addReg(OverflowDestReg).addMBB(overflowMBB);
17943   }
17944
17945   // Erase the pseudo instruction
17946   MI->eraseFromParent();
17947
17948   return endMBB;
17949 }
17950
17951 MachineBasicBlock *
17952 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17953                                                  MachineInstr *MI,
17954                                                  MachineBasicBlock *MBB) const {
17955   // Emit code to save XMM registers to the stack. The ABI says that the
17956   // number of registers to save is given in %al, so it's theoretically
17957   // possible to do an indirect jump trick to avoid saving all of them,
17958   // however this code takes a simpler approach and just executes all
17959   // of the stores if %al is non-zero. It's less code, and it's probably
17960   // easier on the hardware branch predictor, and stores aren't all that
17961   // expensive anyway.
17962
17963   // Create the new basic blocks. One block contains all the XMM stores,
17964   // and one block is the final destination regardless of whether any
17965   // stores were performed.
17966   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17967   MachineFunction *F = MBB->getParent();
17968   MachineFunction::iterator MBBIter = MBB;
17969   ++MBBIter;
17970   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17971   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17972   F->insert(MBBIter, XMMSaveMBB);
17973   F->insert(MBBIter, EndMBB);
17974
17975   // Transfer the remainder of MBB and its successor edges to EndMBB.
17976   EndMBB->splice(EndMBB->begin(), MBB,
17977                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17978   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17979
17980   // The original block will now fall through to the XMM save block.
17981   MBB->addSuccessor(XMMSaveMBB);
17982   // The XMMSaveMBB will fall through to the end block.
17983   XMMSaveMBB->addSuccessor(EndMBB);
17984
17985   // Now add the instructions.
17986   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17987   DebugLoc DL = MI->getDebugLoc();
17988
17989   unsigned CountReg = MI->getOperand(0).getReg();
17990   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17991   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17992
17993   if (!Subtarget->isTargetWin64()) {
17994     // If %al is 0, branch around the XMM save block.
17995     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17996     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17997     MBB->addSuccessor(EndMBB);
17998   }
17999
18000   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18001   // that was just emitted, but clearly shouldn't be "saved".
18002   assert((MI->getNumOperands() <= 3 ||
18003           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18004           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18005          && "Expected last argument to be EFLAGS");
18006   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18007   // In the XMM save block, save all the XMM argument registers.
18008   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18009     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18010     MachineMemOperand *MMO =
18011       F->getMachineMemOperand(
18012           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18013         MachineMemOperand::MOStore,
18014         /*Size=*/16, /*Align=*/16);
18015     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18016       .addFrameIndex(RegSaveFrameIndex)
18017       .addImm(/*Scale=*/1)
18018       .addReg(/*IndexReg=*/0)
18019       .addImm(/*Disp=*/Offset)
18020       .addReg(/*Segment=*/0)
18021       .addReg(MI->getOperand(i).getReg())
18022       .addMemOperand(MMO);
18023   }
18024
18025   MI->eraseFromParent();   // The pseudo instruction is gone now.
18026
18027   return EndMBB;
18028 }
18029
18030 // The EFLAGS operand of SelectItr might be missing a kill marker
18031 // because there were multiple uses of EFLAGS, and ISel didn't know
18032 // which to mark. Figure out whether SelectItr should have had a
18033 // kill marker, and set it if it should. Returns the correct kill
18034 // marker value.
18035 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18036                                      MachineBasicBlock* BB,
18037                                      const TargetRegisterInfo* TRI) {
18038   // Scan forward through BB for a use/def of EFLAGS.
18039   MachineBasicBlock::iterator miI(std::next(SelectItr));
18040   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18041     const MachineInstr& mi = *miI;
18042     if (mi.readsRegister(X86::EFLAGS))
18043       return false;
18044     if (mi.definesRegister(X86::EFLAGS))
18045       break; // Should have kill-flag - update below.
18046   }
18047
18048   // If we hit the end of the block, check whether EFLAGS is live into a
18049   // successor.
18050   if (miI == BB->end()) {
18051     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18052                                           sEnd = BB->succ_end();
18053          sItr != sEnd; ++sItr) {
18054       MachineBasicBlock* succ = *sItr;
18055       if (succ->isLiveIn(X86::EFLAGS))
18056         return false;
18057     }
18058   }
18059
18060   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18061   // out. SelectMI should have a kill flag on EFLAGS.
18062   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18063   return true;
18064 }
18065
18066 MachineBasicBlock *
18067 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18068                                      MachineBasicBlock *BB) const {
18069   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18070   DebugLoc DL = MI->getDebugLoc();
18071
18072   // To "insert" a SELECT_CC instruction, we actually have to insert the
18073   // diamond control-flow pattern.  The incoming instruction knows the
18074   // destination vreg to set, the condition code register to branch on, the
18075   // true/false values to select between, and a branch opcode to use.
18076   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18077   MachineFunction::iterator It = BB;
18078   ++It;
18079
18080   //  thisMBB:
18081   //  ...
18082   //   TrueVal = ...
18083   //   cmpTY ccX, r1, r2
18084   //   bCC copy1MBB
18085   //   fallthrough --> copy0MBB
18086   MachineBasicBlock *thisMBB = BB;
18087   MachineFunction *F = BB->getParent();
18088   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18089   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18090   F->insert(It, copy0MBB);
18091   F->insert(It, sinkMBB);
18092
18093   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18094   // live into the sink and copy blocks.
18095   const TargetRegisterInfo *TRI =
18096       BB->getParent()->getSubtarget().getRegisterInfo();
18097   if (!MI->killsRegister(X86::EFLAGS) &&
18098       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18099     copy0MBB->addLiveIn(X86::EFLAGS);
18100     sinkMBB->addLiveIn(X86::EFLAGS);
18101   }
18102
18103   // Transfer the remainder of BB and its successor edges to sinkMBB.
18104   sinkMBB->splice(sinkMBB->begin(), BB,
18105                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18106   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18107
18108   // Add the true and fallthrough blocks as its successors.
18109   BB->addSuccessor(copy0MBB);
18110   BB->addSuccessor(sinkMBB);
18111
18112   // Create the conditional branch instruction.
18113   unsigned Opc =
18114     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18115   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18116
18117   //  copy0MBB:
18118   //   %FalseValue = ...
18119   //   # fallthrough to sinkMBB
18120   copy0MBB->addSuccessor(sinkMBB);
18121
18122   //  sinkMBB:
18123   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18124   //  ...
18125   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18126           TII->get(X86::PHI), MI->getOperand(0).getReg())
18127     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18128     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18129
18130   MI->eraseFromParent();   // The pseudo instruction is gone now.
18131   return sinkMBB;
18132 }
18133
18134 MachineBasicBlock *
18135 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18136                                         bool Is64Bit) const {
18137   MachineFunction *MF = BB->getParent();
18138   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18139   DebugLoc DL = MI->getDebugLoc();
18140   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18141
18142   assert(MF->shouldSplitStack());
18143
18144   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18145   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18146
18147   // BB:
18148   //  ... [Till the alloca]
18149   // If stacklet is not large enough, jump to mallocMBB
18150   //
18151   // bumpMBB:
18152   //  Allocate by subtracting from RSP
18153   //  Jump to continueMBB
18154   //
18155   // mallocMBB:
18156   //  Allocate by call to runtime
18157   //
18158   // continueMBB:
18159   //  ...
18160   //  [rest of original BB]
18161   //
18162
18163   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18164   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18165   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18166
18167   MachineRegisterInfo &MRI = MF->getRegInfo();
18168   const TargetRegisterClass *AddrRegClass =
18169     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18170
18171   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18172     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18173     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18174     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18175     sizeVReg = MI->getOperand(1).getReg(),
18176     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18177
18178   MachineFunction::iterator MBBIter = BB;
18179   ++MBBIter;
18180
18181   MF->insert(MBBIter, bumpMBB);
18182   MF->insert(MBBIter, mallocMBB);
18183   MF->insert(MBBIter, continueMBB);
18184
18185   continueMBB->splice(continueMBB->begin(), BB,
18186                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18187   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18188
18189   // Add code to the main basic block to check if the stack limit has been hit,
18190   // and if so, jump to mallocMBB otherwise to bumpMBB.
18191   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18192   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18193     .addReg(tmpSPVReg).addReg(sizeVReg);
18194   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18195     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18196     .addReg(SPLimitVReg);
18197   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18198
18199   // bumpMBB simply decreases the stack pointer, since we know the current
18200   // stacklet has enough space.
18201   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18202     .addReg(SPLimitVReg);
18203   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18204     .addReg(SPLimitVReg);
18205   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18206
18207   // Calls into a routine in libgcc to allocate more space from the heap.
18208   const uint32_t *RegMask = MF->getTarget()
18209                                 .getSubtargetImpl()
18210                                 ->getRegisterInfo()
18211                                 ->getCallPreservedMask(CallingConv::C);
18212   if (Is64Bit) {
18213     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18214       .addReg(sizeVReg);
18215     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18216       .addExternalSymbol("__morestack_allocate_stack_space")
18217       .addRegMask(RegMask)
18218       .addReg(X86::RDI, RegState::Implicit)
18219       .addReg(X86::RAX, RegState::ImplicitDefine);
18220   } else {
18221     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18222       .addImm(12);
18223     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18224     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18225       .addExternalSymbol("__morestack_allocate_stack_space")
18226       .addRegMask(RegMask)
18227       .addReg(X86::EAX, RegState::ImplicitDefine);
18228   }
18229
18230   if (!Is64Bit)
18231     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18232       .addImm(16);
18233
18234   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18235     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18236   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18237
18238   // Set up the CFG correctly.
18239   BB->addSuccessor(bumpMBB);
18240   BB->addSuccessor(mallocMBB);
18241   mallocMBB->addSuccessor(continueMBB);
18242   bumpMBB->addSuccessor(continueMBB);
18243
18244   // Take care of the PHI nodes.
18245   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18246           MI->getOperand(0).getReg())
18247     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18248     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18249
18250   // Delete the original pseudo instruction.
18251   MI->eraseFromParent();
18252
18253   // And we're done.
18254   return continueMBB;
18255 }
18256
18257 MachineBasicBlock *
18258 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18259                                         MachineBasicBlock *BB) const {
18260   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18261   DebugLoc DL = MI->getDebugLoc();
18262
18263   assert(!Subtarget->isTargetMacho());
18264
18265   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18266   // non-trivial part is impdef of ESP.
18267
18268   if (Subtarget->isTargetWin64()) {
18269     if (Subtarget->isTargetCygMing()) {
18270       // ___chkstk(Mingw64):
18271       // Clobbers R10, R11, RAX and EFLAGS.
18272       // Updates RSP.
18273       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18274         .addExternalSymbol("___chkstk")
18275         .addReg(X86::RAX, RegState::Implicit)
18276         .addReg(X86::RSP, RegState::Implicit)
18277         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18278         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18279         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18280     } else {
18281       // __chkstk(MSVCRT): does not update stack pointer.
18282       // Clobbers R10, R11 and EFLAGS.
18283       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18284         .addExternalSymbol("__chkstk")
18285         .addReg(X86::RAX, RegState::Implicit)
18286         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18287       // RAX has the offset to be subtracted from RSP.
18288       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18289         .addReg(X86::RSP)
18290         .addReg(X86::RAX);
18291     }
18292   } else {
18293     const char *StackProbeSymbol =
18294       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18295
18296     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18297       .addExternalSymbol(StackProbeSymbol)
18298       .addReg(X86::EAX, RegState::Implicit)
18299       .addReg(X86::ESP, RegState::Implicit)
18300       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18301       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18302       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18303   }
18304
18305   MI->eraseFromParent();   // The pseudo instruction is gone now.
18306   return BB;
18307 }
18308
18309 MachineBasicBlock *
18310 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18311                                       MachineBasicBlock *BB) const {
18312   // This is pretty easy.  We're taking the value that we received from
18313   // our load from the relocation, sticking it in either RDI (x86-64)
18314   // or EAX and doing an indirect call.  The return value will then
18315   // be in the normal return register.
18316   MachineFunction *F = BB->getParent();
18317   const X86InstrInfo *TII =
18318       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18319   DebugLoc DL = MI->getDebugLoc();
18320
18321   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18322   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18323
18324   // Get a register mask for the lowered call.
18325   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18326   // proper register mask.
18327   const uint32_t *RegMask = F->getTarget()
18328                                 .getSubtargetImpl()
18329                                 ->getRegisterInfo()
18330                                 ->getCallPreservedMask(CallingConv::C);
18331   if (Subtarget->is64Bit()) {
18332     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18333                                       TII->get(X86::MOV64rm), X86::RDI)
18334     .addReg(X86::RIP)
18335     .addImm(0).addReg(0)
18336     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18337                       MI->getOperand(3).getTargetFlags())
18338     .addReg(0);
18339     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18340     addDirectMem(MIB, X86::RDI);
18341     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18342   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18343     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18344                                       TII->get(X86::MOV32rm), X86::EAX)
18345     .addReg(0)
18346     .addImm(0).addReg(0)
18347     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18348                       MI->getOperand(3).getTargetFlags())
18349     .addReg(0);
18350     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18351     addDirectMem(MIB, X86::EAX);
18352     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18353   } else {
18354     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18355                                       TII->get(X86::MOV32rm), X86::EAX)
18356     .addReg(TII->getGlobalBaseReg(F))
18357     .addImm(0).addReg(0)
18358     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18359                       MI->getOperand(3).getTargetFlags())
18360     .addReg(0);
18361     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18362     addDirectMem(MIB, X86::EAX);
18363     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18364   }
18365
18366   MI->eraseFromParent(); // The pseudo instruction is gone now.
18367   return BB;
18368 }
18369
18370 MachineBasicBlock *
18371 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18372                                     MachineBasicBlock *MBB) const {
18373   DebugLoc DL = MI->getDebugLoc();
18374   MachineFunction *MF = MBB->getParent();
18375   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18376   MachineRegisterInfo &MRI = MF->getRegInfo();
18377
18378   const BasicBlock *BB = MBB->getBasicBlock();
18379   MachineFunction::iterator I = MBB;
18380   ++I;
18381
18382   // Memory Reference
18383   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18384   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18385
18386   unsigned DstReg;
18387   unsigned MemOpndSlot = 0;
18388
18389   unsigned CurOp = 0;
18390
18391   DstReg = MI->getOperand(CurOp++).getReg();
18392   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18393   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18394   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18395   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18396
18397   MemOpndSlot = CurOp;
18398
18399   MVT PVT = getPointerTy();
18400   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18401          "Invalid Pointer Size!");
18402
18403   // For v = setjmp(buf), we generate
18404   //
18405   // thisMBB:
18406   //  buf[LabelOffset] = restoreMBB
18407   //  SjLjSetup restoreMBB
18408   //
18409   // mainMBB:
18410   //  v_main = 0
18411   //
18412   // sinkMBB:
18413   //  v = phi(main, restore)
18414   //
18415   // restoreMBB:
18416   //  v_restore = 1
18417
18418   MachineBasicBlock *thisMBB = MBB;
18419   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18420   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18421   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18422   MF->insert(I, mainMBB);
18423   MF->insert(I, sinkMBB);
18424   MF->push_back(restoreMBB);
18425
18426   MachineInstrBuilder MIB;
18427
18428   // Transfer the remainder of BB and its successor edges to sinkMBB.
18429   sinkMBB->splice(sinkMBB->begin(), MBB,
18430                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18431   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18432
18433   // thisMBB:
18434   unsigned PtrStoreOpc = 0;
18435   unsigned LabelReg = 0;
18436   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18437   Reloc::Model RM = MF->getTarget().getRelocationModel();
18438   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18439                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18440
18441   // Prepare IP either in reg or imm.
18442   if (!UseImmLabel) {
18443     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18444     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18445     LabelReg = MRI.createVirtualRegister(PtrRC);
18446     if (Subtarget->is64Bit()) {
18447       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18448               .addReg(X86::RIP)
18449               .addImm(0)
18450               .addReg(0)
18451               .addMBB(restoreMBB)
18452               .addReg(0);
18453     } else {
18454       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18455       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18456               .addReg(XII->getGlobalBaseReg(MF))
18457               .addImm(0)
18458               .addReg(0)
18459               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18460               .addReg(0);
18461     }
18462   } else
18463     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18464   // Store IP
18465   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18466   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18467     if (i == X86::AddrDisp)
18468       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18469     else
18470       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18471   }
18472   if (!UseImmLabel)
18473     MIB.addReg(LabelReg);
18474   else
18475     MIB.addMBB(restoreMBB);
18476   MIB.setMemRefs(MMOBegin, MMOEnd);
18477   // Setup
18478   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18479           .addMBB(restoreMBB);
18480
18481   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18482       MF->getSubtarget().getRegisterInfo());
18483   MIB.addRegMask(RegInfo->getNoPreservedMask());
18484   thisMBB->addSuccessor(mainMBB);
18485   thisMBB->addSuccessor(restoreMBB);
18486
18487   // mainMBB:
18488   //  EAX = 0
18489   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18490   mainMBB->addSuccessor(sinkMBB);
18491
18492   // sinkMBB:
18493   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18494           TII->get(X86::PHI), DstReg)
18495     .addReg(mainDstReg).addMBB(mainMBB)
18496     .addReg(restoreDstReg).addMBB(restoreMBB);
18497
18498   // restoreMBB:
18499   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18500   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18501   restoreMBB->addSuccessor(sinkMBB);
18502
18503   MI->eraseFromParent();
18504   return sinkMBB;
18505 }
18506
18507 MachineBasicBlock *
18508 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18509                                      MachineBasicBlock *MBB) const {
18510   DebugLoc DL = MI->getDebugLoc();
18511   MachineFunction *MF = MBB->getParent();
18512   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18513   MachineRegisterInfo &MRI = MF->getRegInfo();
18514
18515   // Memory Reference
18516   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18517   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18518
18519   MVT PVT = getPointerTy();
18520   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18521          "Invalid Pointer Size!");
18522
18523   const TargetRegisterClass *RC =
18524     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18525   unsigned Tmp = MRI.createVirtualRegister(RC);
18526   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18527   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18528       MF->getSubtarget().getRegisterInfo());
18529   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18530   unsigned SP = RegInfo->getStackRegister();
18531
18532   MachineInstrBuilder MIB;
18533
18534   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18535   const int64_t SPOffset = 2 * PVT.getStoreSize();
18536
18537   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18538   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18539
18540   // Reload FP
18541   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18542   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18543     MIB.addOperand(MI->getOperand(i));
18544   MIB.setMemRefs(MMOBegin, MMOEnd);
18545   // Reload IP
18546   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18547   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18548     if (i == X86::AddrDisp)
18549       MIB.addDisp(MI->getOperand(i), LabelOffset);
18550     else
18551       MIB.addOperand(MI->getOperand(i));
18552   }
18553   MIB.setMemRefs(MMOBegin, MMOEnd);
18554   // Reload SP
18555   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18556   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18557     if (i == X86::AddrDisp)
18558       MIB.addDisp(MI->getOperand(i), SPOffset);
18559     else
18560       MIB.addOperand(MI->getOperand(i));
18561   }
18562   MIB.setMemRefs(MMOBegin, MMOEnd);
18563   // Jump
18564   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18565
18566   MI->eraseFromParent();
18567   return MBB;
18568 }
18569
18570 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18571 // accumulator loops. Writing back to the accumulator allows the coalescer
18572 // to remove extra copies in the loop.   
18573 MachineBasicBlock *
18574 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18575                                  MachineBasicBlock *MBB) const {
18576   MachineOperand &AddendOp = MI->getOperand(3);
18577
18578   // Bail out early if the addend isn't a register - we can't switch these.
18579   if (!AddendOp.isReg())
18580     return MBB;
18581
18582   MachineFunction &MF = *MBB->getParent();
18583   MachineRegisterInfo &MRI = MF.getRegInfo();
18584
18585   // Check whether the addend is defined by a PHI:
18586   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18587   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18588   if (!AddendDef.isPHI())
18589     return MBB;
18590
18591   // Look for the following pattern:
18592   // loop:
18593   //   %addend = phi [%entry, 0], [%loop, %result]
18594   //   ...
18595   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18596
18597   // Replace with:
18598   //   loop:
18599   //   %addend = phi [%entry, 0], [%loop, %result]
18600   //   ...
18601   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18602
18603   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18604     assert(AddendDef.getOperand(i).isReg());
18605     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18606     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18607     if (&PHISrcInst == MI) {
18608       // Found a matching instruction.
18609       unsigned NewFMAOpc = 0;
18610       switch (MI->getOpcode()) {
18611         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18612         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18613         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18614         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18615         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18616         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18617         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18618         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18619         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18620         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18621         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18622         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18623         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18624         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18625         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18626         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18627         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18628         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18629         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18630         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18631         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18632         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18633         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18634         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18635         default: llvm_unreachable("Unrecognized FMA variant.");
18636       }
18637
18638       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18639       MachineInstrBuilder MIB =
18640         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18641         .addOperand(MI->getOperand(0))
18642         .addOperand(MI->getOperand(3))
18643         .addOperand(MI->getOperand(2))
18644         .addOperand(MI->getOperand(1));
18645       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18646       MI->eraseFromParent();
18647     }
18648   }
18649
18650   return MBB;
18651 }
18652
18653 MachineBasicBlock *
18654 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18655                                                MachineBasicBlock *BB) const {
18656   switch (MI->getOpcode()) {
18657   default: llvm_unreachable("Unexpected instr type to insert");
18658   case X86::TAILJMPd64:
18659   case X86::TAILJMPr64:
18660   case X86::TAILJMPm64:
18661     llvm_unreachable("TAILJMP64 would not be touched here.");
18662   case X86::TCRETURNdi64:
18663   case X86::TCRETURNri64:
18664   case X86::TCRETURNmi64:
18665     return BB;
18666   case X86::WIN_ALLOCA:
18667     return EmitLoweredWinAlloca(MI, BB);
18668   case X86::SEG_ALLOCA_32:
18669     return EmitLoweredSegAlloca(MI, BB, false);
18670   case X86::SEG_ALLOCA_64:
18671     return EmitLoweredSegAlloca(MI, BB, true);
18672   case X86::TLSCall_32:
18673   case X86::TLSCall_64:
18674     return EmitLoweredTLSCall(MI, BB);
18675   case X86::CMOV_GR8:
18676   case X86::CMOV_FR32:
18677   case X86::CMOV_FR64:
18678   case X86::CMOV_V4F32:
18679   case X86::CMOV_V2F64:
18680   case X86::CMOV_V2I64:
18681   case X86::CMOV_V8F32:
18682   case X86::CMOV_V4F64:
18683   case X86::CMOV_V4I64:
18684   case X86::CMOV_V16F32:
18685   case X86::CMOV_V8F64:
18686   case X86::CMOV_V8I64:
18687   case X86::CMOV_GR16:
18688   case X86::CMOV_GR32:
18689   case X86::CMOV_RFP32:
18690   case X86::CMOV_RFP64:
18691   case X86::CMOV_RFP80:
18692     return EmitLoweredSelect(MI, BB);
18693
18694   case X86::FP32_TO_INT16_IN_MEM:
18695   case X86::FP32_TO_INT32_IN_MEM:
18696   case X86::FP32_TO_INT64_IN_MEM:
18697   case X86::FP64_TO_INT16_IN_MEM:
18698   case X86::FP64_TO_INT32_IN_MEM:
18699   case X86::FP64_TO_INT64_IN_MEM:
18700   case X86::FP80_TO_INT16_IN_MEM:
18701   case X86::FP80_TO_INT32_IN_MEM:
18702   case X86::FP80_TO_INT64_IN_MEM: {
18703     MachineFunction *F = BB->getParent();
18704     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18705     DebugLoc DL = MI->getDebugLoc();
18706
18707     // Change the floating point control register to use "round towards zero"
18708     // mode when truncating to an integer value.
18709     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18710     addFrameReference(BuildMI(*BB, MI, DL,
18711                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18712
18713     // Load the old value of the high byte of the control word...
18714     unsigned OldCW =
18715       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18716     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18717                       CWFrameIdx);
18718
18719     // Set the high part to be round to zero...
18720     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18721       .addImm(0xC7F);
18722
18723     // Reload the modified control word now...
18724     addFrameReference(BuildMI(*BB, MI, DL,
18725                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18726
18727     // Restore the memory image of control word to original value
18728     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18729       .addReg(OldCW);
18730
18731     // Get the X86 opcode to use.
18732     unsigned Opc;
18733     switch (MI->getOpcode()) {
18734     default: llvm_unreachable("illegal opcode!");
18735     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18736     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18737     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18738     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18739     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18740     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18741     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18742     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18743     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18744     }
18745
18746     X86AddressMode AM;
18747     MachineOperand &Op = MI->getOperand(0);
18748     if (Op.isReg()) {
18749       AM.BaseType = X86AddressMode::RegBase;
18750       AM.Base.Reg = Op.getReg();
18751     } else {
18752       AM.BaseType = X86AddressMode::FrameIndexBase;
18753       AM.Base.FrameIndex = Op.getIndex();
18754     }
18755     Op = MI->getOperand(1);
18756     if (Op.isImm())
18757       AM.Scale = Op.getImm();
18758     Op = MI->getOperand(2);
18759     if (Op.isImm())
18760       AM.IndexReg = Op.getImm();
18761     Op = MI->getOperand(3);
18762     if (Op.isGlobal()) {
18763       AM.GV = Op.getGlobal();
18764     } else {
18765       AM.Disp = Op.getImm();
18766     }
18767     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18768                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18769
18770     // Reload the original control word now.
18771     addFrameReference(BuildMI(*BB, MI, DL,
18772                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18773
18774     MI->eraseFromParent();   // The pseudo instruction is gone now.
18775     return BB;
18776   }
18777     // String/text processing lowering.
18778   case X86::PCMPISTRM128REG:
18779   case X86::VPCMPISTRM128REG:
18780   case X86::PCMPISTRM128MEM:
18781   case X86::VPCMPISTRM128MEM:
18782   case X86::PCMPESTRM128REG:
18783   case X86::VPCMPESTRM128REG:
18784   case X86::PCMPESTRM128MEM:
18785   case X86::VPCMPESTRM128MEM:
18786     assert(Subtarget->hasSSE42() &&
18787            "Target must have SSE4.2 or AVX features enabled");
18788     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18789
18790   // String/text processing lowering.
18791   case X86::PCMPISTRIREG:
18792   case X86::VPCMPISTRIREG:
18793   case X86::PCMPISTRIMEM:
18794   case X86::VPCMPISTRIMEM:
18795   case X86::PCMPESTRIREG:
18796   case X86::VPCMPESTRIREG:
18797   case X86::PCMPESTRIMEM:
18798   case X86::VPCMPESTRIMEM:
18799     assert(Subtarget->hasSSE42() &&
18800            "Target must have SSE4.2 or AVX features enabled");
18801     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18802
18803   // Thread synchronization.
18804   case X86::MONITOR:
18805     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18806                        Subtarget);
18807
18808   // xbegin
18809   case X86::XBEGIN:
18810     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18811
18812   case X86::VASTART_SAVE_XMM_REGS:
18813     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18814
18815   case X86::VAARG_64:
18816     return EmitVAARG64WithCustomInserter(MI, BB);
18817
18818   case X86::EH_SjLj_SetJmp32:
18819   case X86::EH_SjLj_SetJmp64:
18820     return emitEHSjLjSetJmp(MI, BB);
18821
18822   case X86::EH_SjLj_LongJmp32:
18823   case X86::EH_SjLj_LongJmp64:
18824     return emitEHSjLjLongJmp(MI, BB);
18825
18826   case TargetOpcode::STACKMAP:
18827   case TargetOpcode::PATCHPOINT:
18828     return emitPatchPoint(MI, BB);
18829
18830   case X86::VFMADDPDr213r:
18831   case X86::VFMADDPSr213r:
18832   case X86::VFMADDSDr213r:
18833   case X86::VFMADDSSr213r:
18834   case X86::VFMSUBPDr213r:
18835   case X86::VFMSUBPSr213r:
18836   case X86::VFMSUBSDr213r:
18837   case X86::VFMSUBSSr213r:
18838   case X86::VFNMADDPDr213r:
18839   case X86::VFNMADDPSr213r:
18840   case X86::VFNMADDSDr213r:
18841   case X86::VFNMADDSSr213r:
18842   case X86::VFNMSUBPDr213r:
18843   case X86::VFNMSUBPSr213r:
18844   case X86::VFNMSUBSDr213r:
18845   case X86::VFNMSUBSSr213r:
18846   case X86::VFMADDPDr213rY:
18847   case X86::VFMADDPSr213rY:
18848   case X86::VFMSUBPDr213rY:
18849   case X86::VFMSUBPSr213rY:
18850   case X86::VFNMADDPDr213rY:
18851   case X86::VFNMADDPSr213rY:
18852   case X86::VFNMSUBPDr213rY:
18853   case X86::VFNMSUBPSr213rY:
18854     return emitFMA3Instr(MI, BB);
18855   }
18856 }
18857
18858 //===----------------------------------------------------------------------===//
18859 //                           X86 Optimization Hooks
18860 //===----------------------------------------------------------------------===//
18861
18862 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18863                                                       APInt &KnownZero,
18864                                                       APInt &KnownOne,
18865                                                       const SelectionDAG &DAG,
18866                                                       unsigned Depth) const {
18867   unsigned BitWidth = KnownZero.getBitWidth();
18868   unsigned Opc = Op.getOpcode();
18869   assert((Opc >= ISD::BUILTIN_OP_END ||
18870           Opc == ISD::INTRINSIC_WO_CHAIN ||
18871           Opc == ISD::INTRINSIC_W_CHAIN ||
18872           Opc == ISD::INTRINSIC_VOID) &&
18873          "Should use MaskedValueIsZero if you don't know whether Op"
18874          " is a target node!");
18875
18876   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18877   switch (Opc) {
18878   default: break;
18879   case X86ISD::ADD:
18880   case X86ISD::SUB:
18881   case X86ISD::ADC:
18882   case X86ISD::SBB:
18883   case X86ISD::SMUL:
18884   case X86ISD::UMUL:
18885   case X86ISD::INC:
18886   case X86ISD::DEC:
18887   case X86ISD::OR:
18888   case X86ISD::XOR:
18889   case X86ISD::AND:
18890     // These nodes' second result is a boolean.
18891     if (Op.getResNo() == 0)
18892       break;
18893     // Fallthrough
18894   case X86ISD::SETCC:
18895     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18896     break;
18897   case ISD::INTRINSIC_WO_CHAIN: {
18898     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18899     unsigned NumLoBits = 0;
18900     switch (IntId) {
18901     default: break;
18902     case Intrinsic::x86_sse_movmsk_ps:
18903     case Intrinsic::x86_avx_movmsk_ps_256:
18904     case Intrinsic::x86_sse2_movmsk_pd:
18905     case Intrinsic::x86_avx_movmsk_pd_256:
18906     case Intrinsic::x86_mmx_pmovmskb:
18907     case Intrinsic::x86_sse2_pmovmskb_128:
18908     case Intrinsic::x86_avx2_pmovmskb: {
18909       // High bits of movmskp{s|d}, pmovmskb are known zero.
18910       switch (IntId) {
18911         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18912         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18913         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18914         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18915         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18916         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18917         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18918         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18919       }
18920       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18921       break;
18922     }
18923     }
18924     break;
18925   }
18926   }
18927 }
18928
18929 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18930   SDValue Op,
18931   const SelectionDAG &,
18932   unsigned Depth) const {
18933   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18934   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18935     return Op.getValueType().getScalarType().getSizeInBits();
18936
18937   // Fallback case.
18938   return 1;
18939 }
18940
18941 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18942 /// node is a GlobalAddress + offset.
18943 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18944                                        const GlobalValue* &GA,
18945                                        int64_t &Offset) const {
18946   if (N->getOpcode() == X86ISD::Wrapper) {
18947     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18948       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18949       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18950       return true;
18951     }
18952   }
18953   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18954 }
18955
18956 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18957 /// same as extracting the high 128-bit part of 256-bit vector and then
18958 /// inserting the result into the low part of a new 256-bit vector
18959 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18960   EVT VT = SVOp->getValueType(0);
18961   unsigned NumElems = VT.getVectorNumElements();
18962
18963   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18964   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18965     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18966         SVOp->getMaskElt(j) >= 0)
18967       return false;
18968
18969   return true;
18970 }
18971
18972 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18973 /// same as extracting the low 128-bit part of 256-bit vector and then
18974 /// inserting the result into the high part of a new 256-bit vector
18975 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18976   EVT VT = SVOp->getValueType(0);
18977   unsigned NumElems = VT.getVectorNumElements();
18978
18979   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18980   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18981     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18982         SVOp->getMaskElt(j) >= 0)
18983       return false;
18984
18985   return true;
18986 }
18987
18988 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18989 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18990                                         TargetLowering::DAGCombinerInfo &DCI,
18991                                         const X86Subtarget* Subtarget) {
18992   SDLoc dl(N);
18993   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18994   SDValue V1 = SVOp->getOperand(0);
18995   SDValue V2 = SVOp->getOperand(1);
18996   EVT VT = SVOp->getValueType(0);
18997   unsigned NumElems = VT.getVectorNumElements();
18998
18999   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19000       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19001     //
19002     //                   0,0,0,...
19003     //                      |
19004     //    V      UNDEF    BUILD_VECTOR    UNDEF
19005     //     \      /           \           /
19006     //  CONCAT_VECTOR         CONCAT_VECTOR
19007     //         \                  /
19008     //          \                /
19009     //          RESULT: V + zero extended
19010     //
19011     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19012         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19013         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19014       return SDValue();
19015
19016     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19017       return SDValue();
19018
19019     // To match the shuffle mask, the first half of the mask should
19020     // be exactly the first vector, and all the rest a splat with the
19021     // first element of the second one.
19022     for (unsigned i = 0; i != NumElems/2; ++i)
19023       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19024           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19025         return SDValue();
19026
19027     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19028     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19029       if (Ld->hasNUsesOfValue(1, 0)) {
19030         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19031         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19032         SDValue ResNode =
19033           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19034                                   Ld->getMemoryVT(),
19035                                   Ld->getPointerInfo(),
19036                                   Ld->getAlignment(),
19037                                   false/*isVolatile*/, true/*ReadMem*/,
19038                                   false/*WriteMem*/);
19039
19040         // Make sure the newly-created LOAD is in the same position as Ld in
19041         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19042         // and update uses of Ld's output chain to use the TokenFactor.
19043         if (Ld->hasAnyUseOfValue(1)) {
19044           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19045                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19046           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19047           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19048                                  SDValue(ResNode.getNode(), 1));
19049         }
19050
19051         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19052       }
19053     }
19054
19055     // Emit a zeroed vector and insert the desired subvector on its
19056     // first half.
19057     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19058     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19059     return DCI.CombineTo(N, InsV);
19060   }
19061
19062   //===--------------------------------------------------------------------===//
19063   // Combine some shuffles into subvector extracts and inserts:
19064   //
19065
19066   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19067   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19068     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19069     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19070     return DCI.CombineTo(N, InsV);
19071   }
19072
19073   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19074   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19075     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19076     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19077     return DCI.CombineTo(N, InsV);
19078   }
19079
19080   return SDValue();
19081 }
19082
19083 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19084 /// possible.
19085 ///
19086 /// This is the leaf of the recursive combinine below. When we have found some
19087 /// chain of single-use x86 shuffle instructions and accumulated the combined
19088 /// shuffle mask represented by them, this will try to pattern match that mask
19089 /// into either a single instruction if there is a special purpose instruction
19090 /// for this operation, or into a PSHUFB instruction which is a fully general
19091 /// instruction but should only be used to replace chains over a certain depth.
19092 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19093                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19094                                    TargetLowering::DAGCombinerInfo &DCI,
19095                                    const X86Subtarget *Subtarget) {
19096   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19097
19098   // Find the operand that enters the chain. Note that multiple uses are OK
19099   // here, we're not going to remove the operand we find.
19100   SDValue Input = Op.getOperand(0);
19101   while (Input.getOpcode() == ISD::BITCAST)
19102     Input = Input.getOperand(0);
19103
19104   MVT VT = Input.getSimpleValueType();
19105   MVT RootVT = Root.getSimpleValueType();
19106   SDLoc DL(Root);
19107
19108   // Just remove no-op shuffle masks.
19109   if (Mask.size() == 1) {
19110     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19111                   /*AddTo*/ true);
19112     return true;
19113   }
19114
19115   // Use the float domain if the operand type is a floating point type.
19116   bool FloatDomain = VT.isFloatingPoint();
19117
19118   // If we don't have access to VEX encodings, the generic PSHUF instructions
19119   // are preferable to some of the specialized forms despite requiring one more
19120   // byte to encode because they can implicitly copy.
19121   //
19122   // IF we *do* have VEX encodings, than we can use shorter, more specific
19123   // shuffle instructions freely as they can copy due to the extra register
19124   // operand.
19125   if (Subtarget->hasAVX()) {
19126     // We have both floating point and integer variants of shuffles that dup
19127     // either the low or high half of the vector.
19128     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19129       bool Lo = Mask.equals(0, 0);
19130       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19131                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19132       if (Depth == 1 && Root->getOpcode() == Shuffle)
19133         return false; // Nothing to do!
19134       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19135       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19136       DCI.AddToWorklist(Op.getNode());
19137       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19138       DCI.AddToWorklist(Op.getNode());
19139       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19140                     /*AddTo*/ true);
19141       return true;
19142     }
19143
19144     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19145
19146     // For the integer domain we have specialized instructions for duplicating
19147     // any element size from the low or high half.
19148     if (!FloatDomain &&
19149         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19150          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19151          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19152          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19153          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19154                      15))) {
19155       bool Lo = Mask[0] == 0;
19156       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19157       if (Depth == 1 && Root->getOpcode() == Shuffle)
19158         return false; // Nothing to do!
19159       MVT ShuffleVT;
19160       switch (Mask.size()) {
19161       case 4: ShuffleVT = MVT::v4i32; break;
19162       case 8: ShuffleVT = MVT::v8i16; break;
19163       case 16: ShuffleVT = MVT::v16i8; break;
19164       };
19165       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19166       DCI.AddToWorklist(Op.getNode());
19167       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19168       DCI.AddToWorklist(Op.getNode());
19169       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19170                     /*AddTo*/ true);
19171       return true;
19172     }
19173   }
19174
19175   // Don't try to re-form single instruction chains under any circumstances now
19176   // that we've done encoding canonicalization for them.
19177   if (Depth < 2)
19178     return false;
19179
19180   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19181   // can replace them with a single PSHUFB instruction profitably. Intel's
19182   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19183   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19184   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19185     SmallVector<SDValue, 16> PSHUFBMask;
19186     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19187     int Ratio = 16 / Mask.size();
19188     for (unsigned i = 0; i < 16; ++i) {
19189       int M = Mask[i / Ratio] != SM_SentinelZero
19190                   ? Ratio * Mask[i / Ratio] + i % Ratio
19191                   : 255;
19192       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19193     }
19194     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19195     DCI.AddToWorklist(Op.getNode());
19196     SDValue PSHUFBMaskOp =
19197         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19198     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19199     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19200     DCI.AddToWorklist(Op.getNode());
19201     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19202                   /*AddTo*/ true);
19203     return true;
19204   }
19205
19206   // Failed to find any combines.
19207   return false;
19208 }
19209
19210 /// \brief Fully generic combining of x86 shuffle instructions.
19211 ///
19212 /// This should be the last combine run over the x86 shuffle instructions. Once
19213 /// they have been fully optimized, this will recursively consider all chains
19214 /// of single-use shuffle instructions, build a generic model of the cumulative
19215 /// shuffle operation, and check for simpler instructions which implement this
19216 /// operation. We use this primarily for two purposes:
19217 ///
19218 /// 1) Collapse generic shuffles to specialized single instructions when
19219 ///    equivalent. In most cases, this is just an encoding size win, but
19220 ///    sometimes we will collapse multiple generic shuffles into a single
19221 ///    special-purpose shuffle.
19222 /// 2) Look for sequences of shuffle instructions with 3 or more total
19223 ///    instructions, and replace them with the slightly more expensive SSSE3
19224 ///    PSHUFB instruction if available. We do this as the last combining step
19225 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19226 ///    a suitable short sequence of other instructions. The PHUFB will either
19227 ///    use a register or have to read from memory and so is slightly (but only
19228 ///    slightly) more expensive than the other shuffle instructions.
19229 ///
19230 /// Because this is inherently a quadratic operation (for each shuffle in
19231 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19232 /// This should never be an issue in practice as the shuffle lowering doesn't
19233 /// produce sequences of more than 8 instructions.
19234 ///
19235 /// FIXME: We will currently miss some cases where the redundant shuffling
19236 /// would simplify under the threshold for PSHUFB formation because of
19237 /// combine-ordering. To fix this, we should do the redundant instruction
19238 /// combining in this recursive walk.
19239 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19240                                           ArrayRef<int> RootMask,
19241                                           int Depth, bool HasPSHUFB,
19242                                           SelectionDAG &DAG,
19243                                           TargetLowering::DAGCombinerInfo &DCI,
19244                                           const X86Subtarget *Subtarget) {
19245   // Bound the depth of our recursive combine because this is ultimately
19246   // quadratic in nature.
19247   if (Depth > 8)
19248     return false;
19249
19250   // Directly rip through bitcasts to find the underlying operand.
19251   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19252     Op = Op.getOperand(0);
19253
19254   MVT VT = Op.getSimpleValueType();
19255   if (!VT.isVector())
19256     return false; // Bail if we hit a non-vector.
19257   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19258   // version should be added.
19259   if (VT.getSizeInBits() != 128)
19260     return false;
19261
19262   assert(Root.getSimpleValueType().isVector() &&
19263          "Shuffles operate on vector types!");
19264   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19265          "Can only combine shuffles of the same vector register size.");
19266
19267   if (!isTargetShuffle(Op.getOpcode()))
19268     return false;
19269   SmallVector<int, 16> OpMask;
19270   bool IsUnary;
19271   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19272   // We only can combine unary shuffles which we can decode the mask for.
19273   if (!HaveMask || !IsUnary)
19274     return false;
19275
19276   assert(VT.getVectorNumElements() == OpMask.size() &&
19277          "Different mask size from vector size!");
19278   assert(((RootMask.size() > OpMask.size() &&
19279            RootMask.size() % OpMask.size() == 0) ||
19280           (OpMask.size() > RootMask.size() &&
19281            OpMask.size() % RootMask.size() == 0) ||
19282           OpMask.size() == RootMask.size()) &&
19283          "The smaller number of elements must divide the larger.");
19284   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19285   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19286   assert(((RootRatio == 1 && OpRatio == 1) ||
19287           (RootRatio == 1) != (OpRatio == 1)) &&
19288          "Must not have a ratio for both incoming and op masks!");
19289
19290   SmallVector<int, 16> Mask;
19291   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19292
19293   // Merge this shuffle operation's mask into our accumulated mask. Note that
19294   // this shuffle's mask will be the first applied to the input, followed by the
19295   // root mask to get us all the way to the root value arrangement. The reason
19296   // for this order is that we are recursing up the operation chain.
19297   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19298     int RootIdx = i / RootRatio;
19299     if (RootMask[RootIdx] == SM_SentinelZero) {
19300       // This is a zero-ed lane, we're done.
19301       Mask.push_back(SM_SentinelZero);
19302       continue;
19303     }
19304
19305     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19306     int OpIdx = RootMaskedIdx / OpRatio;
19307     if (OpMask[OpIdx] == SM_SentinelZero) {
19308       // The incoming lanes are zero, it doesn't matter which ones we are using.
19309       Mask.push_back(SM_SentinelZero);
19310       continue;
19311     }
19312
19313     // Ok, we have non-zero lanes, map them through.
19314     Mask.push_back(OpMask[OpIdx] * OpRatio +
19315                    RootMaskedIdx % OpRatio);
19316   }
19317
19318   // See if we can recurse into the operand to combine more things.
19319   switch (Op.getOpcode()) {
19320     case X86ISD::PSHUFB:
19321       HasPSHUFB = true;
19322     case X86ISD::PSHUFD:
19323     case X86ISD::PSHUFHW:
19324     case X86ISD::PSHUFLW:
19325       if (Op.getOperand(0).hasOneUse() &&
19326           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19327                                         HasPSHUFB, DAG, DCI, Subtarget))
19328         return true;
19329       break;
19330
19331     case X86ISD::UNPCKL:
19332     case X86ISD::UNPCKH:
19333       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19334       // We can't check for single use, we have to check that this shuffle is the only user.
19335       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19336           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19337                                         HasPSHUFB, DAG, DCI, Subtarget))
19338           return true;
19339       break;
19340   }
19341
19342   // Minor canonicalization of the accumulated shuffle mask to make it easier
19343   // to match below. All this does is detect masks with squential pairs of
19344   // elements, and shrink them to the half-width mask. It does this in a loop
19345   // so it will reduce the size of the mask to the minimal width mask which
19346   // performs an equivalent shuffle.
19347   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19348     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19349       Mask[i] = Mask[2 * i] / 2;
19350     Mask.resize(Mask.size() / 2);
19351   }
19352
19353   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19354                                 Subtarget);
19355 }
19356
19357 /// \brief Get the PSHUF-style mask from PSHUF node.
19358 ///
19359 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19360 /// PSHUF-style masks that can be reused with such instructions.
19361 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19362   SmallVector<int, 4> Mask;
19363   bool IsUnary;
19364   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19365   (void)HaveMask;
19366   assert(HaveMask);
19367
19368   switch (N.getOpcode()) {
19369   case X86ISD::PSHUFD:
19370     return Mask;
19371   case X86ISD::PSHUFLW:
19372     Mask.resize(4);
19373     return Mask;
19374   case X86ISD::PSHUFHW:
19375     Mask.erase(Mask.begin(), Mask.begin() + 4);
19376     for (int &M : Mask)
19377       M -= 4;
19378     return Mask;
19379   default:
19380     llvm_unreachable("No valid shuffle instruction found!");
19381   }
19382 }
19383
19384 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19385 ///
19386 /// We walk up the chain and look for a combinable shuffle, skipping over
19387 /// shuffles that we could hoist this shuffle's transformation past without
19388 /// altering anything.
19389 static SDValue
19390 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19391                              SelectionDAG &DAG,
19392                              TargetLowering::DAGCombinerInfo &DCI) {
19393   assert(N.getOpcode() == X86ISD::PSHUFD &&
19394          "Called with something other than an x86 128-bit half shuffle!");
19395   SDLoc DL(N);
19396
19397   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19398   // of the shuffles in the chain so that we can form a fresh chain to replace
19399   // this one.
19400   SmallVector<SDValue, 8> Chain;
19401   SDValue V = N.getOperand(0);
19402   for (; V.hasOneUse(); V = V.getOperand(0)) {
19403     switch (V.getOpcode()) {
19404     default:
19405       return SDValue(); // Nothing combined!
19406
19407     case ISD::BITCAST:
19408       // Skip bitcasts as we always know the type for the target specific
19409       // instructions.
19410       continue;
19411
19412     case X86ISD::PSHUFD:
19413       // Found another dword shuffle.
19414       break;
19415
19416     case X86ISD::PSHUFLW:
19417       // Check that the low words (being shuffled) are the identity in the
19418       // dword shuffle, and the high words are self-contained.
19419       if (Mask[0] != 0 || Mask[1] != 1 ||
19420           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19421         return SDValue();
19422
19423       Chain.push_back(V);
19424       continue;
19425
19426     case X86ISD::PSHUFHW:
19427       // Check that the high words (being shuffled) are the identity in the
19428       // dword shuffle, and the low words are self-contained.
19429       if (Mask[2] != 2 || Mask[3] != 3 ||
19430           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19431         return SDValue();
19432
19433       Chain.push_back(V);
19434       continue;
19435
19436     case X86ISD::UNPCKL:
19437     case X86ISD::UNPCKH:
19438       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19439       // shuffle into a preceding word shuffle.
19440       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19441         return SDValue();
19442
19443       // Search for a half-shuffle which we can combine with.
19444       unsigned CombineOp =
19445           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19446       if (V.getOperand(0) != V.getOperand(1) ||
19447           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19448         return SDValue();
19449       Chain.push_back(V);
19450       V = V.getOperand(0);
19451       do {
19452         switch (V.getOpcode()) {
19453         default:
19454           return SDValue(); // Nothing to combine.
19455
19456         case X86ISD::PSHUFLW:
19457         case X86ISD::PSHUFHW:
19458           if (V.getOpcode() == CombineOp)
19459             break;
19460
19461           Chain.push_back(V);
19462
19463           // Fallthrough!
19464         case ISD::BITCAST:
19465           V = V.getOperand(0);
19466           continue;
19467         }
19468         break;
19469       } while (V.hasOneUse());
19470       break;
19471     }
19472     // Break out of the loop if we break out of the switch.
19473     break;
19474   }
19475
19476   if (!V.hasOneUse())
19477     // We fell out of the loop without finding a viable combining instruction.
19478     return SDValue();
19479
19480   // Merge this node's mask and our incoming mask.
19481   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19482   for (int &M : Mask)
19483     M = VMask[M];
19484   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19485                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19486
19487   // Rebuild the chain around this new shuffle.
19488   while (!Chain.empty()) {
19489     SDValue W = Chain.pop_back_val();
19490
19491     if (V.getValueType() != W.getOperand(0).getValueType())
19492       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19493
19494     switch (W.getOpcode()) {
19495     default:
19496       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19497
19498     case X86ISD::UNPCKL:
19499     case X86ISD::UNPCKH:
19500       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19501       break;
19502
19503     case X86ISD::PSHUFD:
19504     case X86ISD::PSHUFLW:
19505     case X86ISD::PSHUFHW:
19506       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19507       break;
19508     }
19509   }
19510   if (V.getValueType() != N.getValueType())
19511     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19512
19513   // Return the new chain to replace N.
19514   return V;
19515 }
19516
19517 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19518 ///
19519 /// We walk up the chain, skipping shuffles of the other half and looking
19520 /// through shuffles which switch halves trying to find a shuffle of the same
19521 /// pair of dwords.
19522 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19523                                         SelectionDAG &DAG,
19524                                         TargetLowering::DAGCombinerInfo &DCI) {
19525   assert(
19526       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19527       "Called with something other than an x86 128-bit half shuffle!");
19528   SDLoc DL(N);
19529   unsigned CombineOpcode = N.getOpcode();
19530
19531   // Walk up a single-use chain looking for a combinable shuffle.
19532   SDValue V = N.getOperand(0);
19533   for (; V.hasOneUse(); V = V.getOperand(0)) {
19534     switch (V.getOpcode()) {
19535     default:
19536       return false; // Nothing combined!
19537
19538     case ISD::BITCAST:
19539       // Skip bitcasts as we always know the type for the target specific
19540       // instructions.
19541       continue;
19542
19543     case X86ISD::PSHUFLW:
19544     case X86ISD::PSHUFHW:
19545       if (V.getOpcode() == CombineOpcode)
19546         break;
19547
19548       // Other-half shuffles are no-ops.
19549       continue;
19550     }
19551     // Break out of the loop if we break out of the switch.
19552     break;
19553   }
19554
19555   if (!V.hasOneUse())
19556     // We fell out of the loop without finding a viable combining instruction.
19557     return false;
19558
19559   // Combine away the bottom node as its shuffle will be accumulated into
19560   // a preceding shuffle.
19561   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19562
19563   // Record the old value.
19564   SDValue Old = V;
19565
19566   // Merge this node's mask and our incoming mask (adjusted to account for all
19567   // the pshufd instructions encountered).
19568   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19569   for (int &M : Mask)
19570     M = VMask[M];
19571   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19572                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19573
19574   // Check that the shuffles didn't cancel each other out. If not, we need to
19575   // combine to the new one.
19576   if (Old != V)
19577     // Replace the combinable shuffle with the combined one, updating all users
19578     // so that we re-evaluate the chain here.
19579     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19580
19581   return true;
19582 }
19583
19584 /// \brief Try to combine x86 target specific shuffles.
19585 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19586                                            TargetLowering::DAGCombinerInfo &DCI,
19587                                            const X86Subtarget *Subtarget) {
19588   SDLoc DL(N);
19589   MVT VT = N.getSimpleValueType();
19590   SmallVector<int, 4> Mask;
19591
19592   switch (N.getOpcode()) {
19593   case X86ISD::PSHUFD:
19594   case X86ISD::PSHUFLW:
19595   case X86ISD::PSHUFHW:
19596     Mask = getPSHUFShuffleMask(N);
19597     assert(Mask.size() == 4);
19598     break;
19599   default:
19600     return SDValue();
19601   }
19602
19603   // Nuke no-op shuffles that show up after combining.
19604   if (isNoopShuffleMask(Mask))
19605     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19606
19607   // Look for simplifications involving one or two shuffle instructions.
19608   SDValue V = N.getOperand(0);
19609   switch (N.getOpcode()) {
19610   default:
19611     break;
19612   case X86ISD::PSHUFLW:
19613   case X86ISD::PSHUFHW:
19614     assert(VT == MVT::v8i16);
19615     (void)VT;
19616
19617     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19618       return SDValue(); // We combined away this shuffle, so we're done.
19619
19620     // See if this reduces to a PSHUFD which is no more expensive and can
19621     // combine with more operations.
19622     if (canWidenShuffleElements(Mask)) {
19623       int DMask[] = {-1, -1, -1, -1};
19624       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19625       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19626       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19627       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19628       DCI.AddToWorklist(V.getNode());
19629       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19630                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19631       DCI.AddToWorklist(V.getNode());
19632       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19633     }
19634
19635     // Look for shuffle patterns which can be implemented as a single unpack.
19636     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19637     // only works when we have a PSHUFD followed by two half-shuffles.
19638     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19639         (V.getOpcode() == X86ISD::PSHUFLW ||
19640          V.getOpcode() == X86ISD::PSHUFHW) &&
19641         V.getOpcode() != N.getOpcode() &&
19642         V.hasOneUse()) {
19643       SDValue D = V.getOperand(0);
19644       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19645         D = D.getOperand(0);
19646       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19647         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19648         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19649         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19650         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19651         int WordMask[8];
19652         for (int i = 0; i < 4; ++i) {
19653           WordMask[i + NOffset] = Mask[i] + NOffset;
19654           WordMask[i + VOffset] = VMask[i] + VOffset;
19655         }
19656         // Map the word mask through the DWord mask.
19657         int MappedMask[8];
19658         for (int i = 0; i < 8; ++i)
19659           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19660         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19661         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19662         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19663                        std::begin(UnpackLoMask)) ||
19664             std::equal(std::begin(MappedMask), std::end(MappedMask),
19665                        std::begin(UnpackHiMask))) {
19666           // We can replace all three shuffles with an unpack.
19667           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19668           DCI.AddToWorklist(V.getNode());
19669           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19670                                                 : X86ISD::UNPCKH,
19671                              DL, MVT::v8i16, V, V);
19672         }
19673       }
19674     }
19675
19676     break;
19677
19678   case X86ISD::PSHUFD:
19679     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19680       return NewN;
19681
19682     break;
19683   }
19684
19685   return SDValue();
19686 }
19687
19688 /// PerformShuffleCombine - Performs several different shuffle combines.
19689 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19690                                      TargetLowering::DAGCombinerInfo &DCI,
19691                                      const X86Subtarget *Subtarget) {
19692   SDLoc dl(N);
19693   SDValue N0 = N->getOperand(0);
19694   SDValue N1 = N->getOperand(1);
19695   EVT VT = N->getValueType(0);
19696
19697   // Don't create instructions with illegal types after legalize types has run.
19698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19699   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19700     return SDValue();
19701
19702   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19703   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19704       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19705     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19706
19707   // During Type Legalization, when promoting illegal vector types,
19708   // the backend might introduce new shuffle dag nodes and bitcasts.
19709   //
19710   // This code performs the following transformation:
19711   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19712   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19713   //
19714   // We do this only if both the bitcast and the BINOP dag nodes have
19715   // one use. Also, perform this transformation only if the new binary
19716   // operation is legal. This is to avoid introducing dag nodes that
19717   // potentially need to be further expanded (or custom lowered) into a
19718   // less optimal sequence of dag nodes.
19719   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19720       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19721       N0.getOpcode() == ISD::BITCAST) {
19722     SDValue BC0 = N0.getOperand(0);
19723     EVT SVT = BC0.getValueType();
19724     unsigned Opcode = BC0.getOpcode();
19725     unsigned NumElts = VT.getVectorNumElements();
19726     
19727     if (BC0.hasOneUse() && SVT.isVector() &&
19728         SVT.getVectorNumElements() * 2 == NumElts &&
19729         TLI.isOperationLegal(Opcode, VT)) {
19730       bool CanFold = false;
19731       switch (Opcode) {
19732       default : break;
19733       case ISD::ADD :
19734       case ISD::FADD :
19735       case ISD::SUB :
19736       case ISD::FSUB :
19737       case ISD::MUL :
19738       case ISD::FMUL :
19739         CanFold = true;
19740       }
19741
19742       unsigned SVTNumElts = SVT.getVectorNumElements();
19743       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19744       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19745         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19746       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19747         CanFold = SVOp->getMaskElt(i) < 0;
19748
19749       if (CanFold) {
19750         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19751         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19752         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19753         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19754       }
19755     }
19756   }
19757
19758   // Only handle 128 wide vector from here on.
19759   if (!VT.is128BitVector())
19760     return SDValue();
19761
19762   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19763   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19764   // consecutive, non-overlapping, and in the right order.
19765   SmallVector<SDValue, 16> Elts;
19766   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19767     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19768
19769   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19770   if (LD.getNode())
19771     return LD;
19772
19773   if (isTargetShuffle(N->getOpcode())) {
19774     SDValue Shuffle =
19775         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19776     if (Shuffle.getNode())
19777       return Shuffle;
19778
19779     // Try recursively combining arbitrary sequences of x86 shuffle
19780     // instructions into higher-order shuffles. We do this after combining
19781     // specific PSHUF instruction sequences into their minimal form so that we
19782     // can evaluate how many specialized shuffle instructions are involved in
19783     // a particular chain.
19784     SmallVector<int, 1> NonceMask; // Just a placeholder.
19785     NonceMask.push_back(0);
19786     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19787                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19788                                       DCI, Subtarget))
19789       return SDValue(); // This routine will use CombineTo to replace N.
19790   }
19791
19792   return SDValue();
19793 }
19794
19795 /// PerformTruncateCombine - Converts truncate operation to
19796 /// a sequence of vector shuffle operations.
19797 /// It is possible when we truncate 256-bit vector to 128-bit vector
19798 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19799                                       TargetLowering::DAGCombinerInfo &DCI,
19800                                       const X86Subtarget *Subtarget)  {
19801   return SDValue();
19802 }
19803
19804 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19805 /// specific shuffle of a load can be folded into a single element load.
19806 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19807 /// shuffles have been customed lowered so we need to handle those here.
19808 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19809                                          TargetLowering::DAGCombinerInfo &DCI) {
19810   if (DCI.isBeforeLegalizeOps())
19811     return SDValue();
19812
19813   SDValue InVec = N->getOperand(0);
19814   SDValue EltNo = N->getOperand(1);
19815
19816   if (!isa<ConstantSDNode>(EltNo))
19817     return SDValue();
19818
19819   EVT VT = InVec.getValueType();
19820
19821   if (InVec.getOpcode() == ISD::BITCAST) {
19822     // Don't duplicate a load with other uses.
19823     if (!InVec.hasOneUse())
19824       return SDValue();
19825     EVT BCVT = InVec.getOperand(0).getValueType();
19826     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19827       return SDValue();
19828     InVec = InVec.getOperand(0);
19829   }
19830
19831   if (!isTargetShuffle(InVec.getOpcode()))
19832     return SDValue();
19833
19834   // Don't duplicate a load with other uses.
19835   if (!InVec.hasOneUse())
19836     return SDValue();
19837
19838   SmallVector<int, 16> ShuffleMask;
19839   bool UnaryShuffle;
19840   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19841                             UnaryShuffle))
19842     return SDValue();
19843
19844   // Select the input vector, guarding against out of range extract vector.
19845   unsigned NumElems = VT.getVectorNumElements();
19846   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19847   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19848   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19849                                          : InVec.getOperand(1);
19850
19851   // If inputs to shuffle are the same for both ops, then allow 2 uses
19852   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19853
19854   if (LdNode.getOpcode() == ISD::BITCAST) {
19855     // Don't duplicate a load with other uses.
19856     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19857       return SDValue();
19858
19859     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19860     LdNode = LdNode.getOperand(0);
19861   }
19862
19863   if (!ISD::isNormalLoad(LdNode.getNode()))
19864     return SDValue();
19865
19866   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19867
19868   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19869     return SDValue();
19870
19871   EVT EltVT = N->getValueType(0);
19872   // If there's a bitcast before the shuffle, check if the load type and
19873   // alignment is valid.
19874   unsigned Align = LN0->getAlignment();
19875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19876   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
19877       EltVT.getTypeForEVT(*DAG.getContext()));
19878
19879   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
19880     return SDValue();
19881
19882   // All checks match so transform back to vector_shuffle so that DAG combiner
19883   // can finish the job
19884   SDLoc dl(N);
19885
19886   // Create shuffle node taking into account the case that its a unary shuffle
19887   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19888   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19889                                  InVec.getOperand(0), Shuffle,
19890                                  &ShuffleMask[0]);
19891   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19892   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19893                      EltNo);
19894 }
19895
19896 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19897 /// generation and convert it from being a bunch of shuffles and extracts
19898 /// to a simple store and scalar loads to extract the elements.
19899 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19900                                          TargetLowering::DAGCombinerInfo &DCI) {
19901   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19902   if (NewOp.getNode())
19903     return NewOp;
19904
19905   SDValue InputVector = N->getOperand(0);
19906
19907   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19908   // from mmx to v2i32 has a single usage.
19909   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19910       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19911       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19912     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19913                        N->getValueType(0),
19914                        InputVector.getNode()->getOperand(0));
19915
19916   // Only operate on vectors of 4 elements, where the alternative shuffling
19917   // gets to be more expensive.
19918   if (InputVector.getValueType() != MVT::v4i32)
19919     return SDValue();
19920
19921   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19922   // single use which is a sign-extend or zero-extend, and all elements are
19923   // used.
19924   SmallVector<SDNode *, 4> Uses;
19925   unsigned ExtractedElements = 0;
19926   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19927        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19928     if (UI.getUse().getResNo() != InputVector.getResNo())
19929       return SDValue();
19930
19931     SDNode *Extract = *UI;
19932     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19933       return SDValue();
19934
19935     if (Extract->getValueType(0) != MVT::i32)
19936       return SDValue();
19937     if (!Extract->hasOneUse())
19938       return SDValue();
19939     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19940         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19941       return SDValue();
19942     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19943       return SDValue();
19944
19945     // Record which element was extracted.
19946     ExtractedElements |=
19947       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19948
19949     Uses.push_back(Extract);
19950   }
19951
19952   // If not all the elements were used, this may not be worthwhile.
19953   if (ExtractedElements != 15)
19954     return SDValue();
19955
19956   // Ok, we've now decided to do the transformation.
19957   SDLoc dl(InputVector);
19958
19959   // Store the value to a temporary stack slot.
19960   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19961   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19962                             MachinePointerInfo(), false, false, 0);
19963
19964   // Replace each use (extract) with a load of the appropriate element.
19965   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19966        UE = Uses.end(); UI != UE; ++UI) {
19967     SDNode *Extract = *UI;
19968
19969     // cOMpute the element's address.
19970     SDValue Idx = Extract->getOperand(1);
19971     unsigned EltSize =
19972         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19973     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19974     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19975     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19976
19977     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19978                                      StackPtr, OffsetVal);
19979
19980     // Load the scalar.
19981     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19982                                      ScalarAddr, MachinePointerInfo(),
19983                                      false, false, false, 0);
19984
19985     // Replace the exact with the load.
19986     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19987   }
19988
19989   // The replacement was made in place; don't return anything.
19990   return SDValue();
19991 }
19992
19993 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19994 static std::pair<unsigned, bool>
19995 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19996                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19997   if (!VT.isVector())
19998     return std::make_pair(0, false);
19999
20000   bool NeedSplit = false;
20001   switch (VT.getSimpleVT().SimpleTy) {
20002   default: return std::make_pair(0, false);
20003   case MVT::v32i8:
20004   case MVT::v16i16:
20005   case MVT::v8i32:
20006     if (!Subtarget->hasAVX2())
20007       NeedSplit = true;
20008     if (!Subtarget->hasAVX())
20009       return std::make_pair(0, false);
20010     break;
20011   case MVT::v16i8:
20012   case MVT::v8i16:
20013   case MVT::v4i32:
20014     if (!Subtarget->hasSSE2())
20015       return std::make_pair(0, false);
20016   }
20017
20018   // SSE2 has only a small subset of the operations.
20019   bool hasUnsigned = Subtarget->hasSSE41() ||
20020                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20021   bool hasSigned = Subtarget->hasSSE41() ||
20022                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20023
20024   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20025
20026   unsigned Opc = 0;
20027   // Check for x CC y ? x : y.
20028   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20029       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20030     switch (CC) {
20031     default: break;
20032     case ISD::SETULT:
20033     case ISD::SETULE:
20034       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20035     case ISD::SETUGT:
20036     case ISD::SETUGE:
20037       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20038     case ISD::SETLT:
20039     case ISD::SETLE:
20040       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20041     case ISD::SETGT:
20042     case ISD::SETGE:
20043       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20044     }
20045   // Check for x CC y ? y : x -- a min/max with reversed arms.
20046   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20047              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20048     switch (CC) {
20049     default: break;
20050     case ISD::SETULT:
20051     case ISD::SETULE:
20052       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20053     case ISD::SETUGT:
20054     case ISD::SETUGE:
20055       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20056     case ISD::SETLT:
20057     case ISD::SETLE:
20058       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20059     case ISD::SETGT:
20060     case ISD::SETGE:
20061       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20062     }
20063   }
20064
20065   return std::make_pair(Opc, NeedSplit);
20066 }
20067
20068 static SDValue
20069 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20070                                       const X86Subtarget *Subtarget) {
20071   SDLoc dl(N);
20072   SDValue Cond = N->getOperand(0);
20073   SDValue LHS = N->getOperand(1);
20074   SDValue RHS = N->getOperand(2);
20075
20076   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20077     SDValue CondSrc = Cond->getOperand(0);
20078     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20079       Cond = CondSrc->getOperand(0);
20080   }
20081
20082   MVT VT = N->getSimpleValueType(0);
20083   MVT EltVT = VT.getVectorElementType();
20084   unsigned NumElems = VT.getVectorNumElements();
20085   // There is no blend with immediate in AVX-512.
20086   if (VT.is512BitVector())
20087     return SDValue();
20088
20089   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20090     return SDValue();
20091   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20092     return SDValue();
20093
20094   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20095     return SDValue();
20096
20097   // A vselect where all conditions and data are constants can be optimized into
20098   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20099   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20100       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20101     return SDValue();
20102
20103   unsigned MaskValue = 0;
20104   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20105     return SDValue();
20106
20107   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20108   for (unsigned i = 0; i < NumElems; ++i) {
20109     // Be sure we emit undef where we can.
20110     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20111       ShuffleMask[i] = -1;
20112     else
20113       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20114   }
20115
20116   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20117 }
20118
20119 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20120 /// nodes.
20121 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20122                                     TargetLowering::DAGCombinerInfo &DCI,
20123                                     const X86Subtarget *Subtarget) {
20124   SDLoc DL(N);
20125   SDValue Cond = N->getOperand(0);
20126   // Get the LHS/RHS of the select.
20127   SDValue LHS = N->getOperand(1);
20128   SDValue RHS = N->getOperand(2);
20129   EVT VT = LHS.getValueType();
20130   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20131
20132   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20133   // instructions match the semantics of the common C idiom x<y?x:y but not
20134   // x<=y?x:y, because of how they handle negative zero (which can be
20135   // ignored in unsafe-math mode).
20136   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20137       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20138       (Subtarget->hasSSE2() ||
20139        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20140     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20141
20142     unsigned Opcode = 0;
20143     // Check for x CC y ? x : y.
20144     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20145         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20146       switch (CC) {
20147       default: break;
20148       case ISD::SETULT:
20149         // Converting this to a min would handle NaNs incorrectly, and swapping
20150         // the operands would cause it to handle comparisons between positive
20151         // and negative zero incorrectly.
20152         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20153           if (!DAG.getTarget().Options.UnsafeFPMath &&
20154               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20155             break;
20156           std::swap(LHS, RHS);
20157         }
20158         Opcode = X86ISD::FMIN;
20159         break;
20160       case ISD::SETOLE:
20161         // Converting this to a min would handle comparisons between positive
20162         // and negative zero incorrectly.
20163         if (!DAG.getTarget().Options.UnsafeFPMath &&
20164             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20165           break;
20166         Opcode = X86ISD::FMIN;
20167         break;
20168       case ISD::SETULE:
20169         // Converting this to a min would handle both negative zeros and NaNs
20170         // incorrectly, but we can swap the operands to fix both.
20171         std::swap(LHS, RHS);
20172       case ISD::SETOLT:
20173       case ISD::SETLT:
20174       case ISD::SETLE:
20175         Opcode = X86ISD::FMIN;
20176         break;
20177
20178       case ISD::SETOGE:
20179         // Converting this to a max would handle comparisons between positive
20180         // and negative zero incorrectly.
20181         if (!DAG.getTarget().Options.UnsafeFPMath &&
20182             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20183           break;
20184         Opcode = X86ISD::FMAX;
20185         break;
20186       case ISD::SETUGT:
20187         // Converting this to a max would handle NaNs incorrectly, and swapping
20188         // the operands would cause it to handle comparisons between positive
20189         // and negative zero incorrectly.
20190         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20191           if (!DAG.getTarget().Options.UnsafeFPMath &&
20192               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20193             break;
20194           std::swap(LHS, RHS);
20195         }
20196         Opcode = X86ISD::FMAX;
20197         break;
20198       case ISD::SETUGE:
20199         // Converting this to a max would handle both negative zeros and NaNs
20200         // incorrectly, but we can swap the operands to fix both.
20201         std::swap(LHS, RHS);
20202       case ISD::SETOGT:
20203       case ISD::SETGT:
20204       case ISD::SETGE:
20205         Opcode = X86ISD::FMAX;
20206         break;
20207       }
20208     // Check for x CC y ? y : x -- a min/max with reversed arms.
20209     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20210                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20211       switch (CC) {
20212       default: break;
20213       case ISD::SETOGE:
20214         // Converting this to a min would handle comparisons between positive
20215         // and negative zero incorrectly, and swapping the operands would
20216         // cause it to handle NaNs incorrectly.
20217         if (!DAG.getTarget().Options.UnsafeFPMath &&
20218             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20219           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20220             break;
20221           std::swap(LHS, RHS);
20222         }
20223         Opcode = X86ISD::FMIN;
20224         break;
20225       case ISD::SETUGT:
20226         // Converting this to a min would handle NaNs incorrectly.
20227         if (!DAG.getTarget().Options.UnsafeFPMath &&
20228             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20229           break;
20230         Opcode = X86ISD::FMIN;
20231         break;
20232       case ISD::SETUGE:
20233         // Converting this to a min 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::SETOGT:
20237       case ISD::SETGT:
20238       case ISD::SETGE:
20239         Opcode = X86ISD::FMIN;
20240         break;
20241
20242       case ISD::SETULT:
20243         // Converting this to a max would handle NaNs incorrectly.
20244         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20245           break;
20246         Opcode = X86ISD::FMAX;
20247         break;
20248       case ISD::SETOLE:
20249         // Converting this to a max would handle comparisons between positive
20250         // and negative zero incorrectly, and swapping the operands would
20251         // cause it to handle NaNs incorrectly.
20252         if (!DAG.getTarget().Options.UnsafeFPMath &&
20253             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20254           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20255             break;
20256           std::swap(LHS, RHS);
20257         }
20258         Opcode = X86ISD::FMAX;
20259         break;
20260       case ISD::SETULE:
20261         // Converting this to a max would handle both negative zeros and NaNs
20262         // incorrectly, but we can swap the operands to fix both.
20263         std::swap(LHS, RHS);
20264       case ISD::SETOLT:
20265       case ISD::SETLT:
20266       case ISD::SETLE:
20267         Opcode = X86ISD::FMAX;
20268         break;
20269       }
20270     }
20271
20272     if (Opcode)
20273       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20274   }
20275
20276   EVT CondVT = Cond.getValueType();
20277   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20278       CondVT.getVectorElementType() == MVT::i1) {
20279     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20280     // lowering on KNL. In this case we convert it to
20281     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20282     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20283     // Since SKX these selects have a proper lowering.
20284     EVT OpVT = LHS.getValueType();
20285     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20286         (OpVT.getVectorElementType() == MVT::i8 ||
20287          OpVT.getVectorElementType() == MVT::i16) &&
20288         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20289       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20290       DCI.AddToWorklist(Cond.getNode());
20291       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20292     }
20293   }
20294   // If this is a select between two integer constants, try to do some
20295   // optimizations.
20296   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20297     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20298       // Don't do this for crazy integer types.
20299       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20300         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20301         // so that TrueC (the true value) is larger than FalseC.
20302         bool NeedsCondInvert = false;
20303
20304         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20305             // Efficiently invertible.
20306             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20307              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20308               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20309           NeedsCondInvert = true;
20310           std::swap(TrueC, FalseC);
20311         }
20312
20313         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20314         if (FalseC->getAPIntValue() == 0 &&
20315             TrueC->getAPIntValue().isPowerOf2()) {
20316           if (NeedsCondInvert) // Invert the condition if needed.
20317             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20318                                DAG.getConstant(1, Cond.getValueType()));
20319
20320           // Zero extend the condition if needed.
20321           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20322
20323           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20324           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20325                              DAG.getConstant(ShAmt, MVT::i8));
20326         }
20327
20328         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20329         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20330           if (NeedsCondInvert) // Invert the condition if needed.
20331             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20332                                DAG.getConstant(1, Cond.getValueType()));
20333
20334           // Zero extend the condition if needed.
20335           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20336                              FalseC->getValueType(0), Cond);
20337           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20338                              SDValue(FalseC, 0));
20339         }
20340
20341         // Optimize cases that will turn into an LEA instruction.  This requires
20342         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20343         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20344           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20345           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20346
20347           bool isFastMultiplier = false;
20348           if (Diff < 10) {
20349             switch ((unsigned char)Diff) {
20350               default: break;
20351               case 1:  // result = add base, cond
20352               case 2:  // result = lea base(    , cond*2)
20353               case 3:  // result = lea base(cond, cond*2)
20354               case 4:  // result = lea base(    , cond*4)
20355               case 5:  // result = lea base(cond, cond*4)
20356               case 8:  // result = lea base(    , cond*8)
20357               case 9:  // result = lea base(cond, cond*8)
20358                 isFastMultiplier = true;
20359                 break;
20360             }
20361           }
20362
20363           if (isFastMultiplier) {
20364             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20365             if (NeedsCondInvert) // Invert the condition if needed.
20366               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20367                                  DAG.getConstant(1, Cond.getValueType()));
20368
20369             // Zero extend the condition if needed.
20370             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20371                                Cond);
20372             // Scale the condition by the difference.
20373             if (Diff != 1)
20374               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20375                                  DAG.getConstant(Diff, Cond.getValueType()));
20376
20377             // Add the base if non-zero.
20378             if (FalseC->getAPIntValue() != 0)
20379               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20380                                  SDValue(FalseC, 0));
20381             return Cond;
20382           }
20383         }
20384       }
20385   }
20386
20387   // Canonicalize max and min:
20388   // (x > y) ? x : y -> (x >= y) ? x : y
20389   // (x < y) ? x : y -> (x <= y) ? x : y
20390   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20391   // the need for an extra compare
20392   // against zero. e.g.
20393   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20394   // subl   %esi, %edi
20395   // testl  %edi, %edi
20396   // movl   $0, %eax
20397   // cmovgl %edi, %eax
20398   // =>
20399   // xorl   %eax, %eax
20400   // subl   %esi, $edi
20401   // cmovsl %eax, %edi
20402   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20403       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20404       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20405     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20406     switch (CC) {
20407     default: break;
20408     case ISD::SETLT:
20409     case ISD::SETGT: {
20410       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20411       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20412                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20413       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20414     }
20415     }
20416   }
20417
20418   // Early exit check
20419   if (!TLI.isTypeLegal(VT))
20420     return SDValue();
20421
20422   // Match VSELECTs into subs with unsigned saturation.
20423   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20424       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20425       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20426        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20427     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20428
20429     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20430     // left side invert the predicate to simplify logic below.
20431     SDValue Other;
20432     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20433       Other = RHS;
20434       CC = ISD::getSetCCInverse(CC, true);
20435     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20436       Other = LHS;
20437     }
20438
20439     if (Other.getNode() && Other->getNumOperands() == 2 &&
20440         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20441       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20442       SDValue CondRHS = Cond->getOperand(1);
20443
20444       // Look for a general sub with unsigned saturation first.
20445       // x >= y ? x-y : 0 --> subus x, y
20446       // x >  y ? x-y : 0 --> subus x, y
20447       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20448           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20449         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20450
20451       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20452         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20453           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20454             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20455               // If the RHS is a constant we have to reverse the const
20456               // canonicalization.
20457               // x > C-1 ? x+-C : 0 --> subus x, C
20458               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20459                   CondRHSConst->getAPIntValue() ==
20460                       (-OpRHSConst->getAPIntValue() - 1))
20461                 return DAG.getNode(
20462                     X86ISD::SUBUS, DL, VT, OpLHS,
20463                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20464
20465           // Another special case: If C was a sign bit, the sub has been
20466           // canonicalized into a xor.
20467           // FIXME: Would it be better to use computeKnownBits to determine
20468           //        whether it's safe to decanonicalize the xor?
20469           // x s< 0 ? x^C : 0 --> subus x, C
20470           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20471               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20472               OpRHSConst->getAPIntValue().isSignBit())
20473             // Note that we have to rebuild the RHS constant here to ensure we
20474             // don't rely on particular values of undef lanes.
20475             return DAG.getNode(
20476                 X86ISD::SUBUS, DL, VT, OpLHS,
20477                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20478         }
20479     }
20480   }
20481
20482   // Try to match a min/max vector operation.
20483   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20484     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20485     unsigned Opc = ret.first;
20486     bool NeedSplit = ret.second;
20487
20488     if (Opc && NeedSplit) {
20489       unsigned NumElems = VT.getVectorNumElements();
20490       // Extract the LHS vectors
20491       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20492       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20493
20494       // Extract the RHS vectors
20495       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20496       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20497
20498       // Create min/max for each subvector
20499       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20500       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20501
20502       // Merge the result
20503       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20504     } else if (Opc)
20505       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20506   }
20507
20508   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20509   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20510       // Check if SETCC has already been promoted
20511       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20512       // Check that condition value type matches vselect operand type
20513       CondVT == VT) { 
20514
20515     assert(Cond.getValueType().isVector() &&
20516            "vector select expects a vector selector!");
20517
20518     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20519     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20520
20521     if (!TValIsAllOnes && !FValIsAllZeros) {
20522       // Try invert the condition if true value is not all 1s and false value
20523       // is not all 0s.
20524       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20525       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20526
20527       if (TValIsAllZeros || FValIsAllOnes) {
20528         SDValue CC = Cond.getOperand(2);
20529         ISD::CondCode NewCC =
20530           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20531                                Cond.getOperand(0).getValueType().isInteger());
20532         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20533         std::swap(LHS, RHS);
20534         TValIsAllOnes = FValIsAllOnes;
20535         FValIsAllZeros = TValIsAllZeros;
20536       }
20537     }
20538
20539     if (TValIsAllOnes || FValIsAllZeros) {
20540       SDValue Ret;
20541
20542       if (TValIsAllOnes && FValIsAllZeros)
20543         Ret = Cond;
20544       else if (TValIsAllOnes)
20545         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20546                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20547       else if (FValIsAllZeros)
20548         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20549                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20550
20551       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20552     }
20553   }
20554
20555   // Try to fold this VSELECT into a MOVSS/MOVSD
20556   if (N->getOpcode() == ISD::VSELECT &&
20557       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20558     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20559         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20560       bool CanFold = false;
20561       unsigned NumElems = Cond.getNumOperands();
20562       SDValue A = LHS;
20563       SDValue B = RHS;
20564       
20565       if (isZero(Cond.getOperand(0))) {
20566         CanFold = true;
20567
20568         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20569         // fold (vselect <0,-1> -> (movsd A, B)
20570         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20571           CanFold = isAllOnes(Cond.getOperand(i));
20572       } else if (isAllOnes(Cond.getOperand(0))) {
20573         CanFold = true;
20574         std::swap(A, B);
20575
20576         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20577         // fold (vselect <-1,0> -> (movsd B, A)
20578         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20579           CanFold = isZero(Cond.getOperand(i));
20580       }
20581
20582       if (CanFold) {
20583         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20584           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20585         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20586       }
20587
20588       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20589         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20590         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20591         //                             (v2i64 (bitcast B)))))
20592         //
20593         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20594         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20595         //                             (v2f64 (bitcast B)))))
20596         //
20597         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20598         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20599         //                             (v2i64 (bitcast A)))))
20600         //
20601         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20602         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20603         //                             (v2f64 (bitcast A)))))
20604
20605         CanFold = (isZero(Cond.getOperand(0)) &&
20606                    isZero(Cond.getOperand(1)) &&
20607                    isAllOnes(Cond.getOperand(2)) &&
20608                    isAllOnes(Cond.getOperand(3)));
20609
20610         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20611             isAllOnes(Cond.getOperand(1)) &&
20612             isZero(Cond.getOperand(2)) &&
20613             isZero(Cond.getOperand(3))) {
20614           CanFold = true;
20615           std::swap(LHS, RHS);
20616         }
20617
20618         if (CanFold) {
20619           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20620           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20621           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20622           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20623                                                 NewB, DAG);
20624           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20625         }
20626       }
20627     }
20628   }
20629
20630   // If we know that this node is legal then we know that it is going to be
20631   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20632   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20633   // to simplify previous instructions.
20634   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20635       !DCI.isBeforeLegalize() &&
20636       // We explicitly check against v8i16 and v16i16 because, although
20637       // they're marked as Custom, they might only be legal when Cond is a
20638       // build_vector of constants. This will be taken care in a later
20639       // condition.
20640       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20641        VT != MVT::v8i16)) {
20642     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20643
20644     // Don't optimize vector selects that map to mask-registers.
20645     if (BitWidth == 1)
20646       return SDValue();
20647
20648     // Check all uses of that condition operand to check whether it will be
20649     // consumed by non-BLEND instructions, which may depend on all bits are set
20650     // properly.
20651     for (SDNode::use_iterator I = Cond->use_begin(),
20652                               E = Cond->use_end(); I != E; ++I)
20653       if (I->getOpcode() != ISD::VSELECT)
20654         // TODO: Add other opcodes eventually lowered into BLEND.
20655         return SDValue();
20656
20657     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20658     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20659
20660     APInt KnownZero, KnownOne;
20661     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20662                                           DCI.isBeforeLegalizeOps());
20663     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20664         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20665       DCI.CommitTargetLoweringOpt(TLO);
20666   }
20667
20668   // We should generate an X86ISD::BLENDI from a vselect if its argument
20669   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20670   // constants. This specific pattern gets generated when we split a
20671   // selector for a 512 bit vector in a machine without AVX512 (but with
20672   // 256-bit vectors), during legalization:
20673   //
20674   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20675   //
20676   // Iff we find this pattern and the build_vectors are built from
20677   // constants, we translate the vselect into a shuffle_vector that we
20678   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20679   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20680     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20681     if (Shuffle.getNode())
20682       return Shuffle;
20683   }
20684
20685   return SDValue();
20686 }
20687
20688 // Check whether a boolean test is testing a boolean value generated by
20689 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20690 // code.
20691 //
20692 // Simplify the following patterns:
20693 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20694 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20695 // to (Op EFLAGS Cond)
20696 //
20697 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20698 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20699 // to (Op EFLAGS !Cond)
20700 //
20701 // where Op could be BRCOND or CMOV.
20702 //
20703 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20704   // Quit if not CMP and SUB with its value result used.
20705   if (Cmp.getOpcode() != X86ISD::CMP &&
20706       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20707       return SDValue();
20708
20709   // Quit if not used as a boolean value.
20710   if (CC != X86::COND_E && CC != X86::COND_NE)
20711     return SDValue();
20712
20713   // Check CMP operands. One of them should be 0 or 1 and the other should be
20714   // an SetCC or extended from it.
20715   SDValue Op1 = Cmp.getOperand(0);
20716   SDValue Op2 = Cmp.getOperand(1);
20717
20718   SDValue SetCC;
20719   const ConstantSDNode* C = nullptr;
20720   bool needOppositeCond = (CC == X86::COND_E);
20721   bool checkAgainstTrue = false; // Is it a comparison against 1?
20722
20723   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20724     SetCC = Op2;
20725   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20726     SetCC = Op1;
20727   else // Quit if all operands are not constants.
20728     return SDValue();
20729
20730   if (C->getZExtValue() == 1) {
20731     needOppositeCond = !needOppositeCond;
20732     checkAgainstTrue = true;
20733   } else if (C->getZExtValue() != 0)
20734     // Quit if the constant is neither 0 or 1.
20735     return SDValue();
20736
20737   bool truncatedToBoolWithAnd = false;
20738   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20739   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20740          SetCC.getOpcode() == ISD::TRUNCATE ||
20741          SetCC.getOpcode() == ISD::AND) {
20742     if (SetCC.getOpcode() == ISD::AND) {
20743       int OpIdx = -1;
20744       ConstantSDNode *CS;
20745       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20746           CS->getZExtValue() == 1)
20747         OpIdx = 1;
20748       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20749           CS->getZExtValue() == 1)
20750         OpIdx = 0;
20751       if (OpIdx == -1)
20752         break;
20753       SetCC = SetCC.getOperand(OpIdx);
20754       truncatedToBoolWithAnd = true;
20755     } else
20756       SetCC = SetCC.getOperand(0);
20757   }
20758
20759   switch (SetCC.getOpcode()) {
20760   case X86ISD::SETCC_CARRY:
20761     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20762     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20763     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20764     // truncated to i1 using 'and'.
20765     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20766       break;
20767     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20768            "Invalid use of SETCC_CARRY!");
20769     // FALL THROUGH
20770   case X86ISD::SETCC:
20771     // Set the condition code or opposite one if necessary.
20772     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20773     if (needOppositeCond)
20774       CC = X86::GetOppositeBranchCondition(CC);
20775     return SetCC.getOperand(1);
20776   case X86ISD::CMOV: {
20777     // Check whether false/true value has canonical one, i.e. 0 or 1.
20778     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20779     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20780     // Quit if true value is not a constant.
20781     if (!TVal)
20782       return SDValue();
20783     // Quit if false value is not a constant.
20784     if (!FVal) {
20785       SDValue Op = SetCC.getOperand(0);
20786       // Skip 'zext' or 'trunc' node.
20787       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20788           Op.getOpcode() == ISD::TRUNCATE)
20789         Op = Op.getOperand(0);
20790       // A special case for rdrand/rdseed, where 0 is set if false cond is
20791       // found.
20792       if ((Op.getOpcode() != X86ISD::RDRAND &&
20793            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20794         return SDValue();
20795     }
20796     // Quit if false value is not the constant 0 or 1.
20797     bool FValIsFalse = true;
20798     if (FVal && FVal->getZExtValue() != 0) {
20799       if (FVal->getZExtValue() != 1)
20800         return SDValue();
20801       // If FVal is 1, opposite cond is needed.
20802       needOppositeCond = !needOppositeCond;
20803       FValIsFalse = false;
20804     }
20805     // Quit if TVal is not the constant opposite of FVal.
20806     if (FValIsFalse && TVal->getZExtValue() != 1)
20807       return SDValue();
20808     if (!FValIsFalse && TVal->getZExtValue() != 0)
20809       return SDValue();
20810     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20811     if (needOppositeCond)
20812       CC = X86::GetOppositeBranchCondition(CC);
20813     return SetCC.getOperand(3);
20814   }
20815   }
20816
20817   return SDValue();
20818 }
20819
20820 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20821 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20822                                   TargetLowering::DAGCombinerInfo &DCI,
20823                                   const X86Subtarget *Subtarget) {
20824   SDLoc DL(N);
20825
20826   // If the flag operand isn't dead, don't touch this CMOV.
20827   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20828     return SDValue();
20829
20830   SDValue FalseOp = N->getOperand(0);
20831   SDValue TrueOp = N->getOperand(1);
20832   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20833   SDValue Cond = N->getOperand(3);
20834
20835   if (CC == X86::COND_E || CC == X86::COND_NE) {
20836     switch (Cond.getOpcode()) {
20837     default: break;
20838     case X86ISD::BSR:
20839     case X86ISD::BSF:
20840       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20841       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20842         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20843     }
20844   }
20845
20846   SDValue Flags;
20847
20848   Flags = checkBoolTestSetCCCombine(Cond, CC);
20849   if (Flags.getNode() &&
20850       // Extra check as FCMOV only supports a subset of X86 cond.
20851       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20852     SDValue Ops[] = { FalseOp, TrueOp,
20853                       DAG.getConstant(CC, MVT::i8), Flags };
20854     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20855   }
20856
20857   // If this is a select between two integer constants, try to do some
20858   // optimizations.  Note that the operands are ordered the opposite of SELECT
20859   // operands.
20860   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20861     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20862       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20863       // larger than FalseC (the false value).
20864       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20865         CC = X86::GetOppositeBranchCondition(CC);
20866         std::swap(TrueC, FalseC);
20867         std::swap(TrueOp, FalseOp);
20868       }
20869
20870       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20871       // This is efficient for any integer data type (including i8/i16) and
20872       // shift amount.
20873       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20874         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20875                            DAG.getConstant(CC, MVT::i8), Cond);
20876
20877         // Zero extend the condition if needed.
20878         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20879
20880         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20881         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20882                            DAG.getConstant(ShAmt, MVT::i8));
20883         if (N->getNumValues() == 2)  // Dead flag value?
20884           return DCI.CombineTo(N, Cond, SDValue());
20885         return Cond;
20886       }
20887
20888       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20889       // for any integer data type, including i8/i16.
20890       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20891         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20892                            DAG.getConstant(CC, MVT::i8), Cond);
20893
20894         // Zero extend the condition if needed.
20895         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20896                            FalseC->getValueType(0), Cond);
20897         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20898                            SDValue(FalseC, 0));
20899
20900         if (N->getNumValues() == 2)  // Dead flag value?
20901           return DCI.CombineTo(N, Cond, SDValue());
20902         return Cond;
20903       }
20904
20905       // Optimize cases that will turn into an LEA instruction.  This requires
20906       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20907       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20908         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20909         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20910
20911         bool isFastMultiplier = false;
20912         if (Diff < 10) {
20913           switch ((unsigned char)Diff) {
20914           default: break;
20915           case 1:  // result = add base, cond
20916           case 2:  // result = lea base(    , cond*2)
20917           case 3:  // result = lea base(cond, cond*2)
20918           case 4:  // result = lea base(    , cond*4)
20919           case 5:  // result = lea base(cond, cond*4)
20920           case 8:  // result = lea base(    , cond*8)
20921           case 9:  // result = lea base(cond, cond*8)
20922             isFastMultiplier = true;
20923             break;
20924           }
20925         }
20926
20927         if (isFastMultiplier) {
20928           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20929           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20930                              DAG.getConstant(CC, MVT::i8), Cond);
20931           // Zero extend the condition if needed.
20932           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20933                              Cond);
20934           // Scale the condition by the difference.
20935           if (Diff != 1)
20936             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20937                                DAG.getConstant(Diff, Cond.getValueType()));
20938
20939           // Add the base if non-zero.
20940           if (FalseC->getAPIntValue() != 0)
20941             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20942                                SDValue(FalseC, 0));
20943           if (N->getNumValues() == 2)  // Dead flag value?
20944             return DCI.CombineTo(N, Cond, SDValue());
20945           return Cond;
20946         }
20947       }
20948     }
20949   }
20950
20951   // Handle these cases:
20952   //   (select (x != c), e, c) -> select (x != c), e, x),
20953   //   (select (x == c), c, e) -> select (x == c), x, e)
20954   // where the c is an integer constant, and the "select" is the combination
20955   // of CMOV and CMP.
20956   //
20957   // The rationale for this change is that the conditional-move from a constant
20958   // needs two instructions, however, conditional-move from a register needs
20959   // only one instruction.
20960   //
20961   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20962   //  some instruction-combining opportunities. This opt needs to be
20963   //  postponed as late as possible.
20964   //
20965   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20966     // the DCI.xxxx conditions are provided to postpone the optimization as
20967     // late as possible.
20968
20969     ConstantSDNode *CmpAgainst = nullptr;
20970     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20971         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20972         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20973
20974       if (CC == X86::COND_NE &&
20975           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20976         CC = X86::GetOppositeBranchCondition(CC);
20977         std::swap(TrueOp, FalseOp);
20978       }
20979
20980       if (CC == X86::COND_E &&
20981           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20982         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20983                           DAG.getConstant(CC, MVT::i8), Cond };
20984         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20985       }
20986     }
20987   }
20988
20989   return SDValue();
20990 }
20991
20992 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20993                                                 const X86Subtarget *Subtarget) {
20994   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20995   switch (IntNo) {
20996   default: return SDValue();
20997   // SSE/AVX/AVX2 blend intrinsics.
20998   case Intrinsic::x86_avx2_pblendvb:
20999   case Intrinsic::x86_avx2_pblendw:
21000   case Intrinsic::x86_avx2_pblendd_128:
21001   case Intrinsic::x86_avx2_pblendd_256:
21002     // Don't try to simplify this intrinsic if we don't have AVX2.
21003     if (!Subtarget->hasAVX2())
21004       return SDValue();
21005     // FALL-THROUGH
21006   case Intrinsic::x86_avx_blend_pd_256:
21007   case Intrinsic::x86_avx_blend_ps_256:
21008   case Intrinsic::x86_avx_blendv_pd_256:
21009   case Intrinsic::x86_avx_blendv_ps_256:
21010     // Don't try to simplify this intrinsic if we don't have AVX.
21011     if (!Subtarget->hasAVX())
21012       return SDValue();
21013     // FALL-THROUGH
21014   case Intrinsic::x86_sse41_pblendw:
21015   case Intrinsic::x86_sse41_blendpd:
21016   case Intrinsic::x86_sse41_blendps:
21017   case Intrinsic::x86_sse41_blendvps:
21018   case Intrinsic::x86_sse41_blendvpd:
21019   case Intrinsic::x86_sse41_pblendvb: {
21020     SDValue Op0 = N->getOperand(1);
21021     SDValue Op1 = N->getOperand(2);
21022     SDValue Mask = N->getOperand(3);
21023
21024     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21025     if (!Subtarget->hasSSE41())
21026       return SDValue();
21027
21028     // fold (blend A, A, Mask) -> A
21029     if (Op0 == Op1)
21030       return Op0;
21031     // fold (blend A, B, allZeros) -> A
21032     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21033       return Op0;
21034     // fold (blend A, B, allOnes) -> B
21035     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21036       return Op1;
21037     
21038     // Simplify the case where the mask is a constant i32 value.
21039     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21040       if (C->isNullValue())
21041         return Op0;
21042       if (C->isAllOnesValue())
21043         return Op1;
21044     }
21045
21046     return SDValue();
21047   }
21048
21049   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21050   case Intrinsic::x86_sse2_psrai_w:
21051   case Intrinsic::x86_sse2_psrai_d:
21052   case Intrinsic::x86_avx2_psrai_w:
21053   case Intrinsic::x86_avx2_psrai_d:
21054   case Intrinsic::x86_sse2_psra_w:
21055   case Intrinsic::x86_sse2_psra_d:
21056   case Intrinsic::x86_avx2_psra_w:
21057   case Intrinsic::x86_avx2_psra_d: {
21058     SDValue Op0 = N->getOperand(1);
21059     SDValue Op1 = N->getOperand(2);
21060     EVT VT = Op0.getValueType();
21061     assert(VT.isVector() && "Expected a vector type!");
21062
21063     if (isa<BuildVectorSDNode>(Op1))
21064       Op1 = Op1.getOperand(0);
21065
21066     if (!isa<ConstantSDNode>(Op1))
21067       return SDValue();
21068
21069     EVT SVT = VT.getVectorElementType();
21070     unsigned SVTBits = SVT.getSizeInBits();
21071
21072     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21073     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21074     uint64_t ShAmt = C.getZExtValue();
21075
21076     // Don't try to convert this shift into a ISD::SRA if the shift
21077     // count is bigger than or equal to the element size.
21078     if (ShAmt >= SVTBits)
21079       return SDValue();
21080
21081     // Trivial case: if the shift count is zero, then fold this
21082     // into the first operand.
21083     if (ShAmt == 0)
21084       return Op0;
21085
21086     // Replace this packed shift intrinsic with a target independent
21087     // shift dag node.
21088     SDValue Splat = DAG.getConstant(C, VT);
21089     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21090   }
21091   }
21092 }
21093
21094 /// PerformMulCombine - Optimize a single multiply with constant into two
21095 /// in order to implement it with two cheaper instructions, e.g.
21096 /// LEA + SHL, LEA + LEA.
21097 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21098                                  TargetLowering::DAGCombinerInfo &DCI) {
21099   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21100     return SDValue();
21101
21102   EVT VT = N->getValueType(0);
21103   if (VT != MVT::i64)
21104     return SDValue();
21105
21106   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21107   if (!C)
21108     return SDValue();
21109   uint64_t MulAmt = C->getZExtValue();
21110   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21111     return SDValue();
21112
21113   uint64_t MulAmt1 = 0;
21114   uint64_t MulAmt2 = 0;
21115   if ((MulAmt % 9) == 0) {
21116     MulAmt1 = 9;
21117     MulAmt2 = MulAmt / 9;
21118   } else if ((MulAmt % 5) == 0) {
21119     MulAmt1 = 5;
21120     MulAmt2 = MulAmt / 5;
21121   } else if ((MulAmt % 3) == 0) {
21122     MulAmt1 = 3;
21123     MulAmt2 = MulAmt / 3;
21124   }
21125   if (MulAmt2 &&
21126       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21127     SDLoc DL(N);
21128
21129     if (isPowerOf2_64(MulAmt2) &&
21130         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21131       // If second multiplifer is pow2, issue it first. We want the multiply by
21132       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21133       // is an add.
21134       std::swap(MulAmt1, MulAmt2);
21135
21136     SDValue NewMul;
21137     if (isPowerOf2_64(MulAmt1))
21138       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21139                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21140     else
21141       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21142                            DAG.getConstant(MulAmt1, VT));
21143
21144     if (isPowerOf2_64(MulAmt2))
21145       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21146                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21147     else
21148       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21149                            DAG.getConstant(MulAmt2, VT));
21150
21151     // Do not add new nodes to DAG combiner worklist.
21152     DCI.CombineTo(N, NewMul, false);
21153   }
21154   return SDValue();
21155 }
21156
21157 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21158   SDValue N0 = N->getOperand(0);
21159   SDValue N1 = N->getOperand(1);
21160   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21161   EVT VT = N0.getValueType();
21162
21163   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21164   // since the result of setcc_c is all zero's or all ones.
21165   if (VT.isInteger() && !VT.isVector() &&
21166       N1C && N0.getOpcode() == ISD::AND &&
21167       N0.getOperand(1).getOpcode() == ISD::Constant) {
21168     SDValue N00 = N0.getOperand(0);
21169     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21170         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21171           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21172          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21173       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21174       APInt ShAmt = N1C->getAPIntValue();
21175       Mask = Mask.shl(ShAmt);
21176       if (Mask != 0)
21177         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21178                            N00, DAG.getConstant(Mask, VT));
21179     }
21180   }
21181
21182   // Hardware support for vector shifts is sparse which makes us scalarize the
21183   // vector operations in many cases. Also, on sandybridge ADD is faster than
21184   // shl.
21185   // (shl V, 1) -> add V,V
21186   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21187     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21188       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21189       // We shift all of the values by one. In many cases we do not have
21190       // hardware support for this operation. This is better expressed as an ADD
21191       // of two values.
21192       if (N1SplatC->getZExtValue() == 1)
21193         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21194     }
21195
21196   return SDValue();
21197 }
21198
21199 /// \brief Returns a vector of 0s if the node in input is a vector logical
21200 /// shift by a constant amount which is known to be bigger than or equal
21201 /// to the vector element size in bits.
21202 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21203                                       const X86Subtarget *Subtarget) {
21204   EVT VT = N->getValueType(0);
21205
21206   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21207       (!Subtarget->hasInt256() ||
21208        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21209     return SDValue();
21210
21211   SDValue Amt = N->getOperand(1);
21212   SDLoc DL(N);
21213   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21214     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21215       APInt ShiftAmt = AmtSplat->getAPIntValue();
21216       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21217
21218       // SSE2/AVX2 logical shifts always return a vector of 0s
21219       // if the shift amount is bigger than or equal to
21220       // the element size. The constant shift amount will be
21221       // encoded as a 8-bit immediate.
21222       if (ShiftAmt.trunc(8).uge(MaxAmount))
21223         return getZeroVector(VT, Subtarget, DAG, DL);
21224     }
21225
21226   return SDValue();
21227 }
21228
21229 /// PerformShiftCombine - Combine shifts.
21230 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21231                                    TargetLowering::DAGCombinerInfo &DCI,
21232                                    const X86Subtarget *Subtarget) {
21233   if (N->getOpcode() == ISD::SHL) {
21234     SDValue V = PerformSHLCombine(N, DAG);
21235     if (V.getNode()) return V;
21236   }
21237
21238   if (N->getOpcode() != ISD::SRA) {
21239     // Try to fold this logical shift into a zero vector.
21240     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21241     if (V.getNode()) return V;
21242   }
21243
21244   return SDValue();
21245 }
21246
21247 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21248 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21249 // and friends.  Likewise for OR -> CMPNEQSS.
21250 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21251                             TargetLowering::DAGCombinerInfo &DCI,
21252                             const X86Subtarget *Subtarget) {
21253   unsigned opcode;
21254
21255   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21256   // we're requiring SSE2 for both.
21257   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21258     SDValue N0 = N->getOperand(0);
21259     SDValue N1 = N->getOperand(1);
21260     SDValue CMP0 = N0->getOperand(1);
21261     SDValue CMP1 = N1->getOperand(1);
21262     SDLoc DL(N);
21263
21264     // The SETCCs should both refer to the same CMP.
21265     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21266       return SDValue();
21267
21268     SDValue CMP00 = CMP0->getOperand(0);
21269     SDValue CMP01 = CMP0->getOperand(1);
21270     EVT     VT    = CMP00.getValueType();
21271
21272     if (VT == MVT::f32 || VT == MVT::f64) {
21273       bool ExpectingFlags = false;
21274       // Check for any users that want flags:
21275       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21276            !ExpectingFlags && UI != UE; ++UI)
21277         switch (UI->getOpcode()) {
21278         default:
21279         case ISD::BR_CC:
21280         case ISD::BRCOND:
21281         case ISD::SELECT:
21282           ExpectingFlags = true;
21283           break;
21284         case ISD::CopyToReg:
21285         case ISD::SIGN_EXTEND:
21286         case ISD::ZERO_EXTEND:
21287         case ISD::ANY_EXTEND:
21288           break;
21289         }
21290
21291       if (!ExpectingFlags) {
21292         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21293         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21294
21295         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21296           X86::CondCode tmp = cc0;
21297           cc0 = cc1;
21298           cc1 = tmp;
21299         }
21300
21301         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21302             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21303           // FIXME: need symbolic constants for these magic numbers.
21304           // See X86ATTInstPrinter.cpp:printSSECC().
21305           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21306           if (Subtarget->hasAVX512()) {
21307             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21308                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21309             if (N->getValueType(0) != MVT::i1)
21310               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21311                                  FSetCC);
21312             return FSetCC;
21313           }
21314           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21315                                               CMP00.getValueType(), CMP00, CMP01,
21316                                               DAG.getConstant(x86cc, MVT::i8));
21317
21318           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21319           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21320
21321           if (is64BitFP && !Subtarget->is64Bit()) {
21322             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21323             // 64-bit integer, since that's not a legal type. Since
21324             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21325             // bits, but can do this little dance to extract the lowest 32 bits
21326             // and work with those going forward.
21327             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21328                                            OnesOrZeroesF);
21329             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21330                                            Vector64);
21331             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21332                                         Vector32, DAG.getIntPtrConstant(0));
21333             IntVT = MVT::i32;
21334           }
21335
21336           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21337           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21338                                       DAG.getConstant(1, IntVT));
21339           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21340           return OneBitOfTruth;
21341         }
21342       }
21343     }
21344   }
21345   return SDValue();
21346 }
21347
21348 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21349 /// so it can be folded inside ANDNP.
21350 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21351   EVT VT = N->getValueType(0);
21352
21353   // Match direct AllOnes for 128 and 256-bit vectors
21354   if (ISD::isBuildVectorAllOnes(N))
21355     return true;
21356
21357   // Look through a bit convert.
21358   if (N->getOpcode() == ISD::BITCAST)
21359     N = N->getOperand(0).getNode();
21360
21361   // Sometimes the operand may come from a insert_subvector building a 256-bit
21362   // allones vector
21363   if (VT.is256BitVector() &&
21364       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21365     SDValue V1 = N->getOperand(0);
21366     SDValue V2 = N->getOperand(1);
21367
21368     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21369         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21370         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21371         ISD::isBuildVectorAllOnes(V2.getNode()))
21372       return true;
21373   }
21374
21375   return false;
21376 }
21377
21378 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21379 // register. In most cases we actually compare or select YMM-sized registers
21380 // and mixing the two types creates horrible code. This method optimizes
21381 // some of the transition sequences.
21382 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21383                                  TargetLowering::DAGCombinerInfo &DCI,
21384                                  const X86Subtarget *Subtarget) {
21385   EVT VT = N->getValueType(0);
21386   if (!VT.is256BitVector())
21387     return SDValue();
21388
21389   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21390           N->getOpcode() == ISD::ZERO_EXTEND ||
21391           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21392
21393   SDValue Narrow = N->getOperand(0);
21394   EVT NarrowVT = Narrow->getValueType(0);
21395   if (!NarrowVT.is128BitVector())
21396     return SDValue();
21397
21398   if (Narrow->getOpcode() != ISD::XOR &&
21399       Narrow->getOpcode() != ISD::AND &&
21400       Narrow->getOpcode() != ISD::OR)
21401     return SDValue();
21402
21403   SDValue N0  = Narrow->getOperand(0);
21404   SDValue N1  = Narrow->getOperand(1);
21405   SDLoc DL(Narrow);
21406
21407   // The Left side has to be a trunc.
21408   if (N0.getOpcode() != ISD::TRUNCATE)
21409     return SDValue();
21410
21411   // The type of the truncated inputs.
21412   EVT WideVT = N0->getOperand(0)->getValueType(0);
21413   if (WideVT != VT)
21414     return SDValue();
21415
21416   // The right side has to be a 'trunc' or a constant vector.
21417   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21418   ConstantSDNode *RHSConstSplat = nullptr;
21419   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21420     RHSConstSplat = RHSBV->getConstantSplatNode();
21421   if (!RHSTrunc && !RHSConstSplat)
21422     return SDValue();
21423
21424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21425
21426   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21427     return SDValue();
21428
21429   // Set N0 and N1 to hold the inputs to the new wide operation.
21430   N0 = N0->getOperand(0);
21431   if (RHSConstSplat) {
21432     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21433                      SDValue(RHSConstSplat, 0));
21434     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21435     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21436   } else if (RHSTrunc) {
21437     N1 = N1->getOperand(0);
21438   }
21439
21440   // Generate the wide operation.
21441   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21442   unsigned Opcode = N->getOpcode();
21443   switch (Opcode) {
21444   case ISD::ANY_EXTEND:
21445     return Op;
21446   case ISD::ZERO_EXTEND: {
21447     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21448     APInt Mask = APInt::getAllOnesValue(InBits);
21449     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21450     return DAG.getNode(ISD::AND, DL, VT,
21451                        Op, DAG.getConstant(Mask, VT));
21452   }
21453   case ISD::SIGN_EXTEND:
21454     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21455                        Op, DAG.getValueType(NarrowVT));
21456   default:
21457     llvm_unreachable("Unexpected opcode");
21458   }
21459 }
21460
21461 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21462                                  TargetLowering::DAGCombinerInfo &DCI,
21463                                  const X86Subtarget *Subtarget) {
21464   EVT VT = N->getValueType(0);
21465   if (DCI.isBeforeLegalizeOps())
21466     return SDValue();
21467
21468   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21469   if (R.getNode())
21470     return R;
21471
21472   // Create BEXTR instructions
21473   // BEXTR is ((X >> imm) & (2**size-1))
21474   if (VT == MVT::i32 || VT == MVT::i64) {
21475     SDValue N0 = N->getOperand(0);
21476     SDValue N1 = N->getOperand(1);
21477     SDLoc DL(N);
21478
21479     // Check for BEXTR.
21480     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21481         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21482       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21483       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21484       if (MaskNode && ShiftNode) {
21485         uint64_t Mask = MaskNode->getZExtValue();
21486         uint64_t Shift = ShiftNode->getZExtValue();
21487         if (isMask_64(Mask)) {
21488           uint64_t MaskSize = CountPopulation_64(Mask);
21489           if (Shift + MaskSize <= VT.getSizeInBits())
21490             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21491                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21492         }
21493       }
21494     } // BEXTR
21495
21496     return SDValue();
21497   }
21498
21499   // Want to form ANDNP nodes:
21500   // 1) In the hopes of then easily combining them with OR and AND nodes
21501   //    to form PBLEND/PSIGN.
21502   // 2) To match ANDN packed intrinsics
21503   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21504     return SDValue();
21505
21506   SDValue N0 = N->getOperand(0);
21507   SDValue N1 = N->getOperand(1);
21508   SDLoc DL(N);
21509
21510   // Check LHS for vnot
21511   if (N0.getOpcode() == ISD::XOR &&
21512       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21513       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21514     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21515
21516   // Check RHS for vnot
21517   if (N1.getOpcode() == ISD::XOR &&
21518       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21519       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21520     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21521
21522   return SDValue();
21523 }
21524
21525 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21526                                 TargetLowering::DAGCombinerInfo &DCI,
21527                                 const X86Subtarget *Subtarget) {
21528   if (DCI.isBeforeLegalizeOps())
21529     return SDValue();
21530
21531   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21532   if (R.getNode())
21533     return R;
21534
21535   SDValue N0 = N->getOperand(0);
21536   SDValue N1 = N->getOperand(1);
21537   EVT VT = N->getValueType(0);
21538
21539   // look for psign/blend
21540   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21541     if (!Subtarget->hasSSSE3() ||
21542         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21543       return SDValue();
21544
21545     // Canonicalize pandn to RHS
21546     if (N0.getOpcode() == X86ISD::ANDNP)
21547       std::swap(N0, N1);
21548     // or (and (m, y), (pandn m, x))
21549     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21550       SDValue Mask = N1.getOperand(0);
21551       SDValue X    = N1.getOperand(1);
21552       SDValue Y;
21553       if (N0.getOperand(0) == Mask)
21554         Y = N0.getOperand(1);
21555       if (N0.getOperand(1) == Mask)
21556         Y = N0.getOperand(0);
21557
21558       // Check to see if the mask appeared in both the AND and ANDNP and
21559       if (!Y.getNode())
21560         return SDValue();
21561
21562       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21563       // Look through mask bitcast.
21564       if (Mask.getOpcode() == ISD::BITCAST)
21565         Mask = Mask.getOperand(0);
21566       if (X.getOpcode() == ISD::BITCAST)
21567         X = X.getOperand(0);
21568       if (Y.getOpcode() == ISD::BITCAST)
21569         Y = Y.getOperand(0);
21570
21571       EVT MaskVT = Mask.getValueType();
21572
21573       // Validate that the Mask operand is a vector sra node.
21574       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21575       // there is no psrai.b
21576       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21577       unsigned SraAmt = ~0;
21578       if (Mask.getOpcode() == ISD::SRA) {
21579         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21580           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21581             SraAmt = AmtConst->getZExtValue();
21582       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21583         SDValue SraC = Mask.getOperand(1);
21584         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21585       }
21586       if ((SraAmt + 1) != EltBits)
21587         return SDValue();
21588
21589       SDLoc DL(N);
21590
21591       // Now we know we at least have a plendvb with the mask val.  See if
21592       // we can form a psignb/w/d.
21593       // psign = x.type == y.type == mask.type && y = sub(0, x);
21594       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21595           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21596           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21597         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21598                "Unsupported VT for PSIGN");
21599         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21600         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21601       }
21602       // PBLENDVB only available on SSE 4.1
21603       if (!Subtarget->hasSSE41())
21604         return SDValue();
21605
21606       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21607
21608       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21609       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21610       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21611       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21612       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21613     }
21614   }
21615
21616   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21617     return SDValue();
21618
21619   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21620   MachineFunction &MF = DAG.getMachineFunction();
21621   bool OptForSize = MF.getFunction()->getAttributes().
21622     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21623
21624   // SHLD/SHRD instructions have lower register pressure, but on some
21625   // platforms they have higher latency than the equivalent
21626   // series of shifts/or that would otherwise be generated.
21627   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21628   // have higher latencies and we are not optimizing for size.
21629   if (!OptForSize && Subtarget->isSHLDSlow())
21630     return SDValue();
21631
21632   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21633     std::swap(N0, N1);
21634   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21635     return SDValue();
21636   if (!N0.hasOneUse() || !N1.hasOneUse())
21637     return SDValue();
21638
21639   SDValue ShAmt0 = N0.getOperand(1);
21640   if (ShAmt0.getValueType() != MVT::i8)
21641     return SDValue();
21642   SDValue ShAmt1 = N1.getOperand(1);
21643   if (ShAmt1.getValueType() != MVT::i8)
21644     return SDValue();
21645   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21646     ShAmt0 = ShAmt0.getOperand(0);
21647   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21648     ShAmt1 = ShAmt1.getOperand(0);
21649
21650   SDLoc DL(N);
21651   unsigned Opc = X86ISD::SHLD;
21652   SDValue Op0 = N0.getOperand(0);
21653   SDValue Op1 = N1.getOperand(0);
21654   if (ShAmt0.getOpcode() == ISD::SUB) {
21655     Opc = X86ISD::SHRD;
21656     std::swap(Op0, Op1);
21657     std::swap(ShAmt0, ShAmt1);
21658   }
21659
21660   unsigned Bits = VT.getSizeInBits();
21661   if (ShAmt1.getOpcode() == ISD::SUB) {
21662     SDValue Sum = ShAmt1.getOperand(0);
21663     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21664       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21665       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21666         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21667       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21668         return DAG.getNode(Opc, DL, VT,
21669                            Op0, Op1,
21670                            DAG.getNode(ISD::TRUNCATE, DL,
21671                                        MVT::i8, ShAmt0));
21672     }
21673   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21674     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21675     if (ShAmt0C &&
21676         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21677       return DAG.getNode(Opc, DL, VT,
21678                          N0.getOperand(0), N1.getOperand(0),
21679                          DAG.getNode(ISD::TRUNCATE, DL,
21680                                        MVT::i8, ShAmt0));
21681   }
21682
21683   return SDValue();
21684 }
21685
21686 // Generate NEG and CMOV for integer abs.
21687 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21688   EVT VT = N->getValueType(0);
21689
21690   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21691   // 8-bit integer abs to NEG and CMOV.
21692   if (VT.isInteger() && VT.getSizeInBits() == 8)
21693     return SDValue();
21694
21695   SDValue N0 = N->getOperand(0);
21696   SDValue N1 = N->getOperand(1);
21697   SDLoc DL(N);
21698
21699   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21700   // and change it to SUB and CMOV.
21701   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21702       N0.getOpcode() == ISD::ADD &&
21703       N0.getOperand(1) == N1 &&
21704       N1.getOpcode() == ISD::SRA &&
21705       N1.getOperand(0) == N0.getOperand(0))
21706     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21707       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21708         // Generate SUB & CMOV.
21709         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21710                                   DAG.getConstant(0, VT), N0.getOperand(0));
21711
21712         SDValue Ops[] = { N0.getOperand(0), Neg,
21713                           DAG.getConstant(X86::COND_GE, MVT::i8),
21714                           SDValue(Neg.getNode(), 1) };
21715         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21716       }
21717   return SDValue();
21718 }
21719
21720 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21721 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21722                                  TargetLowering::DAGCombinerInfo &DCI,
21723                                  const X86Subtarget *Subtarget) {
21724   if (DCI.isBeforeLegalizeOps())
21725     return SDValue();
21726
21727   if (Subtarget->hasCMov()) {
21728     SDValue RV = performIntegerAbsCombine(N, DAG);
21729     if (RV.getNode())
21730       return RV;
21731   }
21732
21733   return SDValue();
21734 }
21735
21736 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21737 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21738                                   TargetLowering::DAGCombinerInfo &DCI,
21739                                   const X86Subtarget *Subtarget) {
21740   LoadSDNode *Ld = cast<LoadSDNode>(N);
21741   EVT RegVT = Ld->getValueType(0);
21742   EVT MemVT = Ld->getMemoryVT();
21743   SDLoc dl(Ld);
21744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21745
21746   // On Sandybridge unaligned 256bit loads are inefficient.
21747   ISD::LoadExtType Ext = Ld->getExtensionType();
21748   unsigned Alignment = Ld->getAlignment();
21749   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21750   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21751       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21752     unsigned NumElems = RegVT.getVectorNumElements();
21753     if (NumElems < 2)
21754       return SDValue();
21755
21756     SDValue Ptr = Ld->getBasePtr();
21757     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21758
21759     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21760                                   NumElems/2);
21761     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21762                                 Ld->getPointerInfo(), Ld->isVolatile(),
21763                                 Ld->isNonTemporal(), Ld->isInvariant(),
21764                                 Alignment);
21765     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21766     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21767                                 Ld->getPointerInfo(), Ld->isVolatile(),
21768                                 Ld->isNonTemporal(), Ld->isInvariant(),
21769                                 std::min(16U, Alignment));
21770     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21771                              Load1.getValue(1),
21772                              Load2.getValue(1));
21773
21774     SDValue NewVec = DAG.getUNDEF(RegVT);
21775     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21776     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21777     return DCI.CombineTo(N, NewVec, TF, true);
21778   }
21779
21780   return SDValue();
21781 }
21782
21783 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21784 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21785                                    const X86Subtarget *Subtarget) {
21786   StoreSDNode *St = cast<StoreSDNode>(N);
21787   EVT VT = St->getValue().getValueType();
21788   EVT StVT = St->getMemoryVT();
21789   SDLoc dl(St);
21790   SDValue StoredVal = St->getOperand(1);
21791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21792
21793   // If we are saving a concatenation of two XMM registers, perform two stores.
21794   // On Sandy Bridge, 256-bit memory operations are executed by two
21795   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21796   // memory  operation.
21797   unsigned Alignment = St->getAlignment();
21798   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21799   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21800       StVT == VT && !IsAligned) {
21801     unsigned NumElems = VT.getVectorNumElements();
21802     if (NumElems < 2)
21803       return SDValue();
21804
21805     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21806     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21807
21808     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21809     SDValue Ptr0 = St->getBasePtr();
21810     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21811
21812     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21813                                 St->getPointerInfo(), St->isVolatile(),
21814                                 St->isNonTemporal(), Alignment);
21815     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21816                                 St->getPointerInfo(), St->isVolatile(),
21817                                 St->isNonTemporal(),
21818                                 std::min(16U, Alignment));
21819     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21820   }
21821
21822   // Optimize trunc store (of multiple scalars) to shuffle and store.
21823   // First, pack all of the elements in one place. Next, store to memory
21824   // in fewer chunks.
21825   if (St->isTruncatingStore() && VT.isVector()) {
21826     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21827     unsigned NumElems = VT.getVectorNumElements();
21828     assert(StVT != VT && "Cannot truncate to the same type");
21829     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21830     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21831
21832     // From, To sizes and ElemCount must be pow of two
21833     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21834     // We are going to use the original vector elt for storing.
21835     // Accumulated smaller vector elements must be a multiple of the store size.
21836     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21837
21838     unsigned SizeRatio  = FromSz / ToSz;
21839
21840     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21841
21842     // Create a type on which we perform the shuffle
21843     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21844             StVT.getScalarType(), NumElems*SizeRatio);
21845
21846     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21847
21848     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21849     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21850     for (unsigned i = 0; i != NumElems; ++i)
21851       ShuffleVec[i] = i * SizeRatio;
21852
21853     // Can't shuffle using an illegal type.
21854     if (!TLI.isTypeLegal(WideVecVT))
21855       return SDValue();
21856
21857     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21858                                          DAG.getUNDEF(WideVecVT),
21859                                          &ShuffleVec[0]);
21860     // At this point all of the data is stored at the bottom of the
21861     // register. We now need to save it to mem.
21862
21863     // Find the largest store unit
21864     MVT StoreType = MVT::i8;
21865     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21866          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21867       MVT Tp = (MVT::SimpleValueType)tp;
21868       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21869         StoreType = Tp;
21870     }
21871
21872     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21873     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21874         (64 <= NumElems * ToSz))
21875       StoreType = MVT::f64;
21876
21877     // Bitcast the original vector into a vector of store-size units
21878     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21879             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21880     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21881     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21882     SmallVector<SDValue, 8> Chains;
21883     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21884                                         TLI.getPointerTy());
21885     SDValue Ptr = St->getBasePtr();
21886
21887     // Perform one or more big stores into memory.
21888     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21889       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21890                                    StoreType, ShuffWide,
21891                                    DAG.getIntPtrConstant(i));
21892       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21893                                 St->getPointerInfo(), St->isVolatile(),
21894                                 St->isNonTemporal(), St->getAlignment());
21895       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21896       Chains.push_back(Ch);
21897     }
21898
21899     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21900   }
21901
21902   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21903   // the FP state in cases where an emms may be missing.
21904   // A preferable solution to the general problem is to figure out the right
21905   // places to insert EMMS.  This qualifies as a quick hack.
21906
21907   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21908   if (VT.getSizeInBits() != 64)
21909     return SDValue();
21910
21911   const Function *F = DAG.getMachineFunction().getFunction();
21912   bool NoImplicitFloatOps = F->getAttributes().
21913     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21914   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21915                      && Subtarget->hasSSE2();
21916   if ((VT.isVector() ||
21917        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21918       isa<LoadSDNode>(St->getValue()) &&
21919       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21920       St->getChain().hasOneUse() && !St->isVolatile()) {
21921     SDNode* LdVal = St->getValue().getNode();
21922     LoadSDNode *Ld = nullptr;
21923     int TokenFactorIndex = -1;
21924     SmallVector<SDValue, 8> Ops;
21925     SDNode* ChainVal = St->getChain().getNode();
21926     // Must be a store of a load.  We currently handle two cases:  the load
21927     // is a direct child, and it's under an intervening TokenFactor.  It is
21928     // possible to dig deeper under nested TokenFactors.
21929     if (ChainVal == LdVal)
21930       Ld = cast<LoadSDNode>(St->getChain());
21931     else if (St->getValue().hasOneUse() &&
21932              ChainVal->getOpcode() == ISD::TokenFactor) {
21933       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21934         if (ChainVal->getOperand(i).getNode() == LdVal) {
21935           TokenFactorIndex = i;
21936           Ld = cast<LoadSDNode>(St->getValue());
21937         } else
21938           Ops.push_back(ChainVal->getOperand(i));
21939       }
21940     }
21941
21942     if (!Ld || !ISD::isNormalLoad(Ld))
21943       return SDValue();
21944
21945     // If this is not the MMX case, i.e. we are just turning i64 load/store
21946     // into f64 load/store, avoid the transformation if there are multiple
21947     // uses of the loaded value.
21948     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21949       return SDValue();
21950
21951     SDLoc LdDL(Ld);
21952     SDLoc StDL(N);
21953     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21954     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21955     // pair instead.
21956     if (Subtarget->is64Bit() || F64IsLegal) {
21957       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21958       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21959                                   Ld->getPointerInfo(), Ld->isVolatile(),
21960                                   Ld->isNonTemporal(), Ld->isInvariant(),
21961                                   Ld->getAlignment());
21962       SDValue NewChain = NewLd.getValue(1);
21963       if (TokenFactorIndex != -1) {
21964         Ops.push_back(NewChain);
21965         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21966       }
21967       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21968                           St->getPointerInfo(),
21969                           St->isVolatile(), St->isNonTemporal(),
21970                           St->getAlignment());
21971     }
21972
21973     // Otherwise, lower to two pairs of 32-bit loads / stores.
21974     SDValue LoAddr = Ld->getBasePtr();
21975     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21976                                  DAG.getConstant(4, MVT::i32));
21977
21978     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21979                                Ld->getPointerInfo(),
21980                                Ld->isVolatile(), Ld->isNonTemporal(),
21981                                Ld->isInvariant(), Ld->getAlignment());
21982     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21983                                Ld->getPointerInfo().getWithOffset(4),
21984                                Ld->isVolatile(), Ld->isNonTemporal(),
21985                                Ld->isInvariant(),
21986                                MinAlign(Ld->getAlignment(), 4));
21987
21988     SDValue NewChain = LoLd.getValue(1);
21989     if (TokenFactorIndex != -1) {
21990       Ops.push_back(LoLd);
21991       Ops.push_back(HiLd);
21992       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21993     }
21994
21995     LoAddr = St->getBasePtr();
21996     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21997                          DAG.getConstant(4, MVT::i32));
21998
21999     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22000                                 St->getPointerInfo(),
22001                                 St->isVolatile(), St->isNonTemporal(),
22002                                 St->getAlignment());
22003     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22004                                 St->getPointerInfo().getWithOffset(4),
22005                                 St->isVolatile(),
22006                                 St->isNonTemporal(),
22007                                 MinAlign(St->getAlignment(), 4));
22008     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22009   }
22010   return SDValue();
22011 }
22012
22013 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22014 /// and return the operands for the horizontal operation in LHS and RHS.  A
22015 /// horizontal operation performs the binary operation on successive elements
22016 /// of its first operand, then on successive elements of its second operand,
22017 /// returning the resulting values in a vector.  For example, if
22018 ///   A = < float a0, float a1, float a2, float a3 >
22019 /// and
22020 ///   B = < float b0, float b1, float b2, float b3 >
22021 /// then the result of doing a horizontal operation on A and B is
22022 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22023 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22024 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22025 /// set to A, RHS to B, and the routine returns 'true'.
22026 /// Note that the binary operation should have the property that if one of the
22027 /// operands is UNDEF then the result is UNDEF.
22028 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22029   // Look for the following pattern: if
22030   //   A = < float a0, float a1, float a2, float a3 >
22031   //   B = < float b0, float b1, float b2, float b3 >
22032   // and
22033   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22034   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22035   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22036   // which is A horizontal-op B.
22037
22038   // At least one of the operands should be a vector shuffle.
22039   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22040       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22041     return false;
22042
22043   MVT VT = LHS.getSimpleValueType();
22044
22045   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22046          "Unsupported vector type for horizontal add/sub");
22047
22048   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22049   // operate independently on 128-bit lanes.
22050   unsigned NumElts = VT.getVectorNumElements();
22051   unsigned NumLanes = VT.getSizeInBits()/128;
22052   unsigned NumLaneElts = NumElts / NumLanes;
22053   assert((NumLaneElts % 2 == 0) &&
22054          "Vector type should have an even number of elements in each lane");
22055   unsigned HalfLaneElts = NumLaneElts/2;
22056
22057   // View LHS in the form
22058   //   LHS = VECTOR_SHUFFLE A, B, LMask
22059   // If LHS is not a shuffle then pretend it is the shuffle
22060   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22061   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22062   // type VT.
22063   SDValue A, B;
22064   SmallVector<int, 16> LMask(NumElts);
22065   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22066     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22067       A = LHS.getOperand(0);
22068     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22069       B = LHS.getOperand(1);
22070     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22071     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22072   } else {
22073     if (LHS.getOpcode() != ISD::UNDEF)
22074       A = LHS;
22075     for (unsigned i = 0; i != NumElts; ++i)
22076       LMask[i] = i;
22077   }
22078
22079   // Likewise, view RHS in the form
22080   //   RHS = VECTOR_SHUFFLE C, D, RMask
22081   SDValue C, D;
22082   SmallVector<int, 16> RMask(NumElts);
22083   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22084     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22085       C = RHS.getOperand(0);
22086     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22087       D = RHS.getOperand(1);
22088     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22089     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22090   } else {
22091     if (RHS.getOpcode() != ISD::UNDEF)
22092       C = RHS;
22093     for (unsigned i = 0; i != NumElts; ++i)
22094       RMask[i] = i;
22095   }
22096
22097   // Check that the shuffles are both shuffling the same vectors.
22098   if (!(A == C && B == D) && !(A == D && B == C))
22099     return false;
22100
22101   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22102   if (!A.getNode() && !B.getNode())
22103     return false;
22104
22105   // If A and B occur in reverse order in RHS, then "swap" them (which means
22106   // rewriting the mask).
22107   if (A != C)
22108     CommuteVectorShuffleMask(RMask, NumElts);
22109
22110   // At this point LHS and RHS are equivalent to
22111   //   LHS = VECTOR_SHUFFLE A, B, LMask
22112   //   RHS = VECTOR_SHUFFLE A, B, RMask
22113   // Check that the masks correspond to performing a horizontal operation.
22114   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22115     for (unsigned i = 0; i != NumLaneElts; ++i) {
22116       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22117
22118       // Ignore any UNDEF components.
22119       if (LIdx < 0 || RIdx < 0 ||
22120           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22121           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22122         continue;
22123
22124       // Check that successive elements are being operated on.  If not, this is
22125       // not a horizontal operation.
22126       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22127       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22128       if (!(LIdx == Index && RIdx == Index + 1) &&
22129           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22130         return false;
22131     }
22132   }
22133
22134   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22135   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22136   return true;
22137 }
22138
22139 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22140 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22141                                   const X86Subtarget *Subtarget) {
22142   EVT VT = N->getValueType(0);
22143   SDValue LHS = N->getOperand(0);
22144   SDValue RHS = N->getOperand(1);
22145
22146   // Try to synthesize horizontal adds from adds of shuffles.
22147   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22148        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22149       isHorizontalBinOp(LHS, RHS, true))
22150     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22151   return SDValue();
22152 }
22153
22154 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22155 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22156                                   const X86Subtarget *Subtarget) {
22157   EVT VT = N->getValueType(0);
22158   SDValue LHS = N->getOperand(0);
22159   SDValue RHS = N->getOperand(1);
22160
22161   // Try to synthesize horizontal subs from subs of shuffles.
22162   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22163        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22164       isHorizontalBinOp(LHS, RHS, false))
22165     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22166   return SDValue();
22167 }
22168
22169 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22170 /// X86ISD::FXOR nodes.
22171 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22172   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22173   // F[X]OR(0.0, x) -> x
22174   // F[X]OR(x, 0.0) -> x
22175   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22176     if (C->getValueAPF().isPosZero())
22177       return N->getOperand(1);
22178   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22179     if (C->getValueAPF().isPosZero())
22180       return N->getOperand(0);
22181   return SDValue();
22182 }
22183
22184 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22185 /// X86ISD::FMAX nodes.
22186 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22187   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22188
22189   // Only perform optimizations if UnsafeMath is used.
22190   if (!DAG.getTarget().Options.UnsafeFPMath)
22191     return SDValue();
22192
22193   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22194   // into FMINC and FMAXC, which are Commutative operations.
22195   unsigned NewOp = 0;
22196   switch (N->getOpcode()) {
22197     default: llvm_unreachable("unknown opcode");
22198     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22199     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22200   }
22201
22202   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22203                      N->getOperand(0), N->getOperand(1));
22204 }
22205
22206 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22207 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22208   // FAND(0.0, x) -> 0.0
22209   // FAND(x, 0.0) -> 0.0
22210   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22211     if (C->getValueAPF().isPosZero())
22212       return N->getOperand(0);
22213   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22214     if (C->getValueAPF().isPosZero())
22215       return N->getOperand(1);
22216   return SDValue();
22217 }
22218
22219 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22220 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22221   // FANDN(x, 0.0) -> 0.0
22222   // FANDN(0.0, x) -> x
22223   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22224     if (C->getValueAPF().isPosZero())
22225       return N->getOperand(1);
22226   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22227     if (C->getValueAPF().isPosZero())
22228       return N->getOperand(1);
22229   return SDValue();
22230 }
22231
22232 static SDValue PerformBTCombine(SDNode *N,
22233                                 SelectionDAG &DAG,
22234                                 TargetLowering::DAGCombinerInfo &DCI) {
22235   // BT ignores high bits in the bit index operand.
22236   SDValue Op1 = N->getOperand(1);
22237   if (Op1.hasOneUse()) {
22238     unsigned BitWidth = Op1.getValueSizeInBits();
22239     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22240     APInt KnownZero, KnownOne;
22241     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22242                                           !DCI.isBeforeLegalizeOps());
22243     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22244     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22245         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22246       DCI.CommitTargetLoweringOpt(TLO);
22247   }
22248   return SDValue();
22249 }
22250
22251 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22252   SDValue Op = N->getOperand(0);
22253   if (Op.getOpcode() == ISD::BITCAST)
22254     Op = Op.getOperand(0);
22255   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22256   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22257       VT.getVectorElementType().getSizeInBits() ==
22258       OpVT.getVectorElementType().getSizeInBits()) {
22259     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22260   }
22261   return SDValue();
22262 }
22263
22264 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22265                                                const X86Subtarget *Subtarget) {
22266   EVT VT = N->getValueType(0);
22267   if (!VT.isVector())
22268     return SDValue();
22269
22270   SDValue N0 = N->getOperand(0);
22271   SDValue N1 = N->getOperand(1);
22272   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22273   SDLoc dl(N);
22274
22275   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22276   // both SSE and AVX2 since there is no sign-extended shift right
22277   // operation on a vector with 64-bit elements.
22278   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22279   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22280   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22281       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22282     SDValue N00 = N0.getOperand(0);
22283
22284     // EXTLOAD has a better solution on AVX2,
22285     // it may be replaced with X86ISD::VSEXT node.
22286     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22287       if (!ISD::isNormalLoad(N00.getNode()))
22288         return SDValue();
22289
22290     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22291         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22292                                   N00, N1);
22293       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22294     }
22295   }
22296   return SDValue();
22297 }
22298
22299 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22300                                   TargetLowering::DAGCombinerInfo &DCI,
22301                                   const X86Subtarget *Subtarget) {
22302   if (!DCI.isBeforeLegalizeOps())
22303     return SDValue();
22304
22305   if (!Subtarget->hasFp256())
22306     return SDValue();
22307
22308   EVT VT = N->getValueType(0);
22309   if (VT.isVector() && VT.getSizeInBits() == 256) {
22310     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22311     if (R.getNode())
22312       return R;
22313   }
22314
22315   return SDValue();
22316 }
22317
22318 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22319                                  const X86Subtarget* Subtarget) {
22320   SDLoc dl(N);
22321   EVT VT = N->getValueType(0);
22322
22323   // Let legalize expand this if it isn't a legal type yet.
22324   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22325     return SDValue();
22326
22327   EVT ScalarVT = VT.getScalarType();
22328   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22329       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22330     return SDValue();
22331
22332   SDValue A = N->getOperand(0);
22333   SDValue B = N->getOperand(1);
22334   SDValue C = N->getOperand(2);
22335
22336   bool NegA = (A.getOpcode() == ISD::FNEG);
22337   bool NegB = (B.getOpcode() == ISD::FNEG);
22338   bool NegC = (C.getOpcode() == ISD::FNEG);
22339
22340   // Negative multiplication when NegA xor NegB
22341   bool NegMul = (NegA != NegB);
22342   if (NegA)
22343     A = A.getOperand(0);
22344   if (NegB)
22345     B = B.getOperand(0);
22346   if (NegC)
22347     C = C.getOperand(0);
22348
22349   unsigned Opcode;
22350   if (!NegMul)
22351     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22352   else
22353     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22354
22355   return DAG.getNode(Opcode, dl, VT, A, B, C);
22356 }
22357
22358 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22359                                   TargetLowering::DAGCombinerInfo &DCI,
22360                                   const X86Subtarget *Subtarget) {
22361   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22362   //           (and (i32 x86isd::setcc_carry), 1)
22363   // This eliminates the zext. This transformation is necessary because
22364   // ISD::SETCC is always legalized to i8.
22365   SDLoc dl(N);
22366   SDValue N0 = N->getOperand(0);
22367   EVT VT = N->getValueType(0);
22368
22369   if (N0.getOpcode() == ISD::AND &&
22370       N0.hasOneUse() &&
22371       N0.getOperand(0).hasOneUse()) {
22372     SDValue N00 = N0.getOperand(0);
22373     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22374       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22375       if (!C || C->getZExtValue() != 1)
22376         return SDValue();
22377       return DAG.getNode(ISD::AND, dl, VT,
22378                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22379                                      N00.getOperand(0), N00.getOperand(1)),
22380                          DAG.getConstant(1, VT));
22381     }
22382   }
22383
22384   if (N0.getOpcode() == ISD::TRUNCATE &&
22385       N0.hasOneUse() &&
22386       N0.getOperand(0).hasOneUse()) {
22387     SDValue N00 = N0.getOperand(0);
22388     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22389       return DAG.getNode(ISD::AND, dl, VT,
22390                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22391                                      N00.getOperand(0), N00.getOperand(1)),
22392                          DAG.getConstant(1, VT));
22393     }
22394   }
22395   if (VT.is256BitVector()) {
22396     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22397     if (R.getNode())
22398       return R;
22399   }
22400
22401   return SDValue();
22402 }
22403
22404 // Optimize x == -y --> x+y == 0
22405 //          x != -y --> x+y != 0
22406 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22407                                       const X86Subtarget* Subtarget) {
22408   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22409   SDValue LHS = N->getOperand(0);
22410   SDValue RHS = N->getOperand(1);
22411   EVT VT = N->getValueType(0);
22412   SDLoc DL(N);
22413
22414   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22415     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22416       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22417         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22418                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22419         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22420                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22421       }
22422   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22423     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22424       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22425         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22426                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22427         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22428                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22429       }
22430
22431   if (VT.getScalarType() == MVT::i1) {
22432     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22433       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22434     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22435     if (!IsSEXT0 && !IsVZero0)
22436       return SDValue();
22437     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22438       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22439     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22440
22441     if (!IsSEXT1 && !IsVZero1)
22442       return SDValue();
22443
22444     if (IsSEXT0 && IsVZero1) {
22445       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22446       if (CC == ISD::SETEQ)
22447         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22448       return LHS.getOperand(0);
22449     }
22450     if (IsSEXT1 && IsVZero0) {
22451       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22452       if (CC == ISD::SETEQ)
22453         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22454       return RHS.getOperand(0);
22455     }
22456   }
22457
22458   return SDValue();
22459 }
22460
22461 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22462                                       const X86Subtarget *Subtarget) {
22463   SDLoc dl(N);
22464   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22465   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22466          "X86insertps is only defined for v4x32");
22467
22468   SDValue Ld = N->getOperand(1);
22469   if (MayFoldLoad(Ld)) {
22470     // Extract the countS bits from the immediate so we can get the proper
22471     // address when narrowing the vector load to a specific element.
22472     // When the second source op is a memory address, interps doesn't use
22473     // countS and just gets an f32 from that address.
22474     unsigned DestIndex =
22475         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22476     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22477   } else
22478     return SDValue();
22479
22480   // Create this as a scalar to vector to match the instruction pattern.
22481   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22482   // countS bits are ignored when loading from memory on insertps, which
22483   // means we don't need to explicitly set them to 0.
22484   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22485                      LoadScalarToVector, N->getOperand(2));
22486 }
22487
22488 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22489 // as "sbb reg,reg", since it can be extended without zext and produces
22490 // an all-ones bit which is more useful than 0/1 in some cases.
22491 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22492                                MVT VT) {
22493   if (VT == MVT::i8)
22494     return DAG.getNode(ISD::AND, DL, VT,
22495                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22496                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22497                        DAG.getConstant(1, VT));
22498   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22499   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22500                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22501                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22502 }
22503
22504 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22505 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22506                                    TargetLowering::DAGCombinerInfo &DCI,
22507                                    const X86Subtarget *Subtarget) {
22508   SDLoc DL(N);
22509   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22510   SDValue EFLAGS = N->getOperand(1);
22511
22512   if (CC == X86::COND_A) {
22513     // Try to convert COND_A into COND_B in an attempt to facilitate
22514     // materializing "setb reg".
22515     //
22516     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22517     // cannot take an immediate as its first operand.
22518     //
22519     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22520         EFLAGS.getValueType().isInteger() &&
22521         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22522       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22523                                    EFLAGS.getNode()->getVTList(),
22524                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22525       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22526       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22527     }
22528   }
22529
22530   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22531   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22532   // cases.
22533   if (CC == X86::COND_B)
22534     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22535
22536   SDValue Flags;
22537
22538   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22539   if (Flags.getNode()) {
22540     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22541     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22542   }
22543
22544   return SDValue();
22545 }
22546
22547 // Optimize branch condition evaluation.
22548 //
22549 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22550                                     TargetLowering::DAGCombinerInfo &DCI,
22551                                     const X86Subtarget *Subtarget) {
22552   SDLoc DL(N);
22553   SDValue Chain = N->getOperand(0);
22554   SDValue Dest = N->getOperand(1);
22555   SDValue EFLAGS = N->getOperand(3);
22556   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22557
22558   SDValue Flags;
22559
22560   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22561   if (Flags.getNode()) {
22562     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22563     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22564                        Flags);
22565   }
22566
22567   return SDValue();
22568 }
22569
22570 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22571                                                          SelectionDAG &DAG) {
22572   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22573   // optimize away operation when it's from a constant.
22574   //
22575   // The general transformation is:
22576   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22577   //       AND(VECTOR_CMP(x,y), constant2)
22578   //    constant2 = UNARYOP(constant)
22579
22580   // Early exit if this isn't a vector operation, the operand of the
22581   // unary operation isn't a bitwise AND, or if the sizes of the operations
22582   // aren't the same.
22583   EVT VT = N->getValueType(0);
22584   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22585       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22586       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22587     return SDValue();
22588
22589   // Now check that the other operand of the AND is a constant. We could
22590   // make the transformation for non-constant splats as well, but it's unclear
22591   // that would be a benefit as it would not eliminate any operations, just
22592   // perform one more step in scalar code before moving to the vector unit.
22593   if (BuildVectorSDNode *BV =
22594           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22595     // Bail out if the vector isn't a constant.
22596     if (!BV->isConstant())
22597       return SDValue();
22598
22599     // Everything checks out. Build up the new and improved node.
22600     SDLoc DL(N);
22601     EVT IntVT = BV->getValueType(0);
22602     // Create a new constant of the appropriate type for the transformed
22603     // DAG.
22604     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22605     // The AND node needs bitcasts to/from an integer vector type around it.
22606     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22607     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22608                                  N->getOperand(0)->getOperand(0), MaskConst);
22609     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22610     return Res;
22611   }
22612
22613   return SDValue();
22614 }
22615
22616 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22617                                         const X86TargetLowering *XTLI) {
22618   // First try to optimize away the conversion entirely when it's
22619   // conditionally from a constant. Vectors only.
22620   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22621   if (Res != SDValue())
22622     return Res;
22623
22624   // Now move on to more general possibilities.
22625   SDValue Op0 = N->getOperand(0);
22626   EVT InVT = Op0->getValueType(0);
22627
22628   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22629   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22630     SDLoc dl(N);
22631     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22632     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22633     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22634   }
22635
22636   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22637   // a 32-bit target where SSE doesn't support i64->FP operations.
22638   if (Op0.getOpcode() == ISD::LOAD) {
22639     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22640     EVT VT = Ld->getValueType(0);
22641     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22642         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22643         !XTLI->getSubtarget()->is64Bit() &&
22644         VT == MVT::i64) {
22645       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22646                                           Ld->getChain(), Op0, DAG);
22647       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22648       return FILDChain;
22649     }
22650   }
22651   return SDValue();
22652 }
22653
22654 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22655 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22656                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22657   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22658   // the result is either zero or one (depending on the input carry bit).
22659   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22660   if (X86::isZeroNode(N->getOperand(0)) &&
22661       X86::isZeroNode(N->getOperand(1)) &&
22662       // We don't have a good way to replace an EFLAGS use, so only do this when
22663       // dead right now.
22664       SDValue(N, 1).use_empty()) {
22665     SDLoc DL(N);
22666     EVT VT = N->getValueType(0);
22667     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22668     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22669                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22670                                            DAG.getConstant(X86::COND_B,MVT::i8),
22671                                            N->getOperand(2)),
22672                                DAG.getConstant(1, VT));
22673     return DCI.CombineTo(N, Res1, CarryOut);
22674   }
22675
22676   return SDValue();
22677 }
22678
22679 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22680 //      (add Y, (setne X, 0)) -> sbb -1, Y
22681 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22682 //      (sub (setne X, 0), Y) -> adc -1, Y
22683 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22684   SDLoc DL(N);
22685
22686   // Look through ZExts.
22687   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22688   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22689     return SDValue();
22690
22691   SDValue SetCC = Ext.getOperand(0);
22692   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22693     return SDValue();
22694
22695   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22696   if (CC != X86::COND_E && CC != X86::COND_NE)
22697     return SDValue();
22698
22699   SDValue Cmp = SetCC.getOperand(1);
22700   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22701       !X86::isZeroNode(Cmp.getOperand(1)) ||
22702       !Cmp.getOperand(0).getValueType().isInteger())
22703     return SDValue();
22704
22705   SDValue CmpOp0 = Cmp.getOperand(0);
22706   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22707                                DAG.getConstant(1, CmpOp0.getValueType()));
22708
22709   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22710   if (CC == X86::COND_NE)
22711     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22712                        DL, OtherVal.getValueType(), OtherVal,
22713                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22714   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22715                      DL, OtherVal.getValueType(), OtherVal,
22716                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22717 }
22718
22719 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22720 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22721                                  const X86Subtarget *Subtarget) {
22722   EVT VT = N->getValueType(0);
22723   SDValue Op0 = N->getOperand(0);
22724   SDValue Op1 = N->getOperand(1);
22725
22726   // Try to synthesize horizontal adds from adds of shuffles.
22727   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22728        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22729       isHorizontalBinOp(Op0, Op1, true))
22730     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22731
22732   return OptimizeConditionalInDecrement(N, DAG);
22733 }
22734
22735 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22736                                  const X86Subtarget *Subtarget) {
22737   SDValue Op0 = N->getOperand(0);
22738   SDValue Op1 = N->getOperand(1);
22739
22740   // X86 can't encode an immediate LHS of a sub. See if we can push the
22741   // negation into a preceding instruction.
22742   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22743     // If the RHS of the sub is a XOR with one use and a constant, invert the
22744     // immediate. Then add one to the LHS of the sub so we can turn
22745     // X-Y -> X+~Y+1, saving one register.
22746     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22747         isa<ConstantSDNode>(Op1.getOperand(1))) {
22748       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22749       EVT VT = Op0.getValueType();
22750       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22751                                    Op1.getOperand(0),
22752                                    DAG.getConstant(~XorC, VT));
22753       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22754                          DAG.getConstant(C->getAPIntValue()+1, VT));
22755     }
22756   }
22757
22758   // Try to synthesize horizontal adds from adds of shuffles.
22759   EVT VT = N->getValueType(0);
22760   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22761        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22762       isHorizontalBinOp(Op0, Op1, true))
22763     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22764
22765   return OptimizeConditionalInDecrement(N, DAG);
22766 }
22767
22768 /// performVZEXTCombine - Performs build vector combines
22769 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22770                                         TargetLowering::DAGCombinerInfo &DCI,
22771                                         const X86Subtarget *Subtarget) {
22772   // (vzext (bitcast (vzext (x)) -> (vzext x)
22773   SDValue In = N->getOperand(0);
22774   while (In.getOpcode() == ISD::BITCAST)
22775     In = In.getOperand(0);
22776
22777   if (In.getOpcode() != X86ISD::VZEXT)
22778     return SDValue();
22779
22780   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22781                      In.getOperand(0));
22782 }
22783
22784 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22785                                              DAGCombinerInfo &DCI) const {
22786   SelectionDAG &DAG = DCI.DAG;
22787   switch (N->getOpcode()) {
22788   default: break;
22789   case ISD::EXTRACT_VECTOR_ELT:
22790     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22791   case ISD::VSELECT:
22792   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22793   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22794   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22795   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22796   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22797   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22798   case ISD::SHL:
22799   case ISD::SRA:
22800   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22801   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22802   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22803   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22804   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22805   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22806   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22807   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22808   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22809   case X86ISD::FXOR:
22810   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22811   case X86ISD::FMIN:
22812   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22813   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22814   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22815   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22816   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22817   case ISD::ANY_EXTEND:
22818   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22819   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22820   case ISD::SIGN_EXTEND_INREG:
22821     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22822   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22823   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22824   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22825   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22826   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22827   case X86ISD::SHUFP:       // Handle all target specific shuffles
22828   case X86ISD::PALIGNR:
22829   case X86ISD::UNPCKH:
22830   case X86ISD::UNPCKL:
22831   case X86ISD::MOVHLPS:
22832   case X86ISD::MOVLHPS:
22833   case X86ISD::PSHUFB:
22834   case X86ISD::PSHUFD:
22835   case X86ISD::PSHUFHW:
22836   case X86ISD::PSHUFLW:
22837   case X86ISD::MOVSS:
22838   case X86ISD::MOVSD:
22839   case X86ISD::VPERMILP:
22840   case X86ISD::VPERM2X128:
22841   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22842   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22843   case ISD::INTRINSIC_WO_CHAIN:
22844     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22845   case X86ISD::INSERTPS:
22846     return PerformINSERTPSCombine(N, DAG, Subtarget);
22847   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22848   }
22849
22850   return SDValue();
22851 }
22852
22853 /// isTypeDesirableForOp - Return true if the target has native support for
22854 /// the specified value type and it is 'desirable' to use the type for the
22855 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22856 /// instruction encodings are longer and some i16 instructions are slow.
22857 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22858   if (!isTypeLegal(VT))
22859     return false;
22860   if (VT != MVT::i16)
22861     return true;
22862
22863   switch (Opc) {
22864   default:
22865     return true;
22866   case ISD::LOAD:
22867   case ISD::SIGN_EXTEND:
22868   case ISD::ZERO_EXTEND:
22869   case ISD::ANY_EXTEND:
22870   case ISD::SHL:
22871   case ISD::SRL:
22872   case ISD::SUB:
22873   case ISD::ADD:
22874   case ISD::MUL:
22875   case ISD::AND:
22876   case ISD::OR:
22877   case ISD::XOR:
22878     return false;
22879   }
22880 }
22881
22882 /// IsDesirableToPromoteOp - This method query the target whether it is
22883 /// beneficial for dag combiner to promote the specified node. If true, it
22884 /// should return the desired promotion type by reference.
22885 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22886   EVT VT = Op.getValueType();
22887   if (VT != MVT::i16)
22888     return false;
22889
22890   bool Promote = false;
22891   bool Commute = false;
22892   switch (Op.getOpcode()) {
22893   default: break;
22894   case ISD::LOAD: {
22895     LoadSDNode *LD = cast<LoadSDNode>(Op);
22896     // If the non-extending load has a single use and it's not live out, then it
22897     // might be folded.
22898     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22899                                                      Op.hasOneUse()*/) {
22900       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22901              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22902         // The only case where we'd want to promote LOAD (rather then it being
22903         // promoted as an operand is when it's only use is liveout.
22904         if (UI->getOpcode() != ISD::CopyToReg)
22905           return false;
22906       }
22907     }
22908     Promote = true;
22909     break;
22910   }
22911   case ISD::SIGN_EXTEND:
22912   case ISD::ZERO_EXTEND:
22913   case ISD::ANY_EXTEND:
22914     Promote = true;
22915     break;
22916   case ISD::SHL:
22917   case ISD::SRL: {
22918     SDValue N0 = Op.getOperand(0);
22919     // Look out for (store (shl (load), x)).
22920     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22921       return false;
22922     Promote = true;
22923     break;
22924   }
22925   case ISD::ADD:
22926   case ISD::MUL:
22927   case ISD::AND:
22928   case ISD::OR:
22929   case ISD::XOR:
22930     Commute = true;
22931     // fallthrough
22932   case ISD::SUB: {
22933     SDValue N0 = Op.getOperand(0);
22934     SDValue N1 = Op.getOperand(1);
22935     if (!Commute && MayFoldLoad(N1))
22936       return false;
22937     // Avoid disabling potential load folding opportunities.
22938     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22939       return false;
22940     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22941       return false;
22942     Promote = true;
22943   }
22944   }
22945
22946   PVT = MVT::i32;
22947   return Promote;
22948 }
22949
22950 //===----------------------------------------------------------------------===//
22951 //                           X86 Inline Assembly Support
22952 //===----------------------------------------------------------------------===//
22953
22954 namespace {
22955   // Helper to match a string separated by whitespace.
22956   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22957     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22958
22959     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22960       StringRef piece(*args[i]);
22961       if (!s.startswith(piece)) // Check if the piece matches.
22962         return false;
22963
22964       s = s.substr(piece.size());
22965       StringRef::size_type pos = s.find_first_not_of(" \t");
22966       if (pos == 0) // We matched a prefix.
22967         return false;
22968
22969       s = s.substr(pos);
22970     }
22971
22972     return s.empty();
22973   }
22974   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22975 }
22976
22977 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22978
22979   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22980     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22981         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22982         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22983
22984       if (AsmPieces.size() == 3)
22985         return true;
22986       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22987         return true;
22988     }
22989   }
22990   return false;
22991 }
22992
22993 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22994   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22995
22996   std::string AsmStr = IA->getAsmString();
22997
22998   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22999   if (!Ty || Ty->getBitWidth() % 16 != 0)
23000     return false;
23001
23002   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23003   SmallVector<StringRef, 4> AsmPieces;
23004   SplitString(AsmStr, AsmPieces, ";\n");
23005
23006   switch (AsmPieces.size()) {
23007   default: return false;
23008   case 1:
23009     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23010     // we will turn this bswap into something that will be lowered to logical
23011     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23012     // lower so don't worry about this.
23013     // bswap $0
23014     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23015         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23016         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23017         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23018         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23019         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23020       // No need to check constraints, nothing other than the equivalent of
23021       // "=r,0" would be valid here.
23022       return IntrinsicLowering::LowerToByteSwap(CI);
23023     }
23024
23025     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23026     if (CI->getType()->isIntegerTy(16) &&
23027         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23028         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23029          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23030       AsmPieces.clear();
23031       const std::string &ConstraintsStr = IA->getConstraintString();
23032       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23033       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23034       if (clobbersFlagRegisters(AsmPieces))
23035         return IntrinsicLowering::LowerToByteSwap(CI);
23036     }
23037     break;
23038   case 3:
23039     if (CI->getType()->isIntegerTy(32) &&
23040         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23041         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23042         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23043         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23044       AsmPieces.clear();
23045       const std::string &ConstraintsStr = IA->getConstraintString();
23046       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23047       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23048       if (clobbersFlagRegisters(AsmPieces))
23049         return IntrinsicLowering::LowerToByteSwap(CI);
23050     }
23051
23052     if (CI->getType()->isIntegerTy(64)) {
23053       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23054       if (Constraints.size() >= 2 &&
23055           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23056           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23057         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23058         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23059             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23060             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23061           return IntrinsicLowering::LowerToByteSwap(CI);
23062       }
23063     }
23064     break;
23065   }
23066   return false;
23067 }
23068
23069 /// getConstraintType - Given a constraint letter, return the type of
23070 /// constraint it is for this target.
23071 X86TargetLowering::ConstraintType
23072 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23073   if (Constraint.size() == 1) {
23074     switch (Constraint[0]) {
23075     case 'R':
23076     case 'q':
23077     case 'Q':
23078     case 'f':
23079     case 't':
23080     case 'u':
23081     case 'y':
23082     case 'x':
23083     case 'Y':
23084     case 'l':
23085       return C_RegisterClass;
23086     case 'a':
23087     case 'b':
23088     case 'c':
23089     case 'd':
23090     case 'S':
23091     case 'D':
23092     case 'A':
23093       return C_Register;
23094     case 'I':
23095     case 'J':
23096     case 'K':
23097     case 'L':
23098     case 'M':
23099     case 'N':
23100     case 'G':
23101     case 'C':
23102     case 'e':
23103     case 'Z':
23104       return C_Other;
23105     default:
23106       break;
23107     }
23108   }
23109   return TargetLowering::getConstraintType(Constraint);
23110 }
23111
23112 /// Examine constraint type and operand type and determine a weight value.
23113 /// This object must already have been set up with the operand type
23114 /// and the current alternative constraint selected.
23115 TargetLowering::ConstraintWeight
23116   X86TargetLowering::getSingleConstraintMatchWeight(
23117     AsmOperandInfo &info, const char *constraint) const {
23118   ConstraintWeight weight = CW_Invalid;
23119   Value *CallOperandVal = info.CallOperandVal;
23120     // If we don't have a value, we can't do a match,
23121     // but allow it at the lowest weight.
23122   if (!CallOperandVal)
23123     return CW_Default;
23124   Type *type = CallOperandVal->getType();
23125   // Look at the constraint type.
23126   switch (*constraint) {
23127   default:
23128     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23129   case 'R':
23130   case 'q':
23131   case 'Q':
23132   case 'a':
23133   case 'b':
23134   case 'c':
23135   case 'd':
23136   case 'S':
23137   case 'D':
23138   case 'A':
23139     if (CallOperandVal->getType()->isIntegerTy())
23140       weight = CW_SpecificReg;
23141     break;
23142   case 'f':
23143   case 't':
23144   case 'u':
23145     if (type->isFloatingPointTy())
23146       weight = CW_SpecificReg;
23147     break;
23148   case 'y':
23149     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23150       weight = CW_SpecificReg;
23151     break;
23152   case 'x':
23153   case 'Y':
23154     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23155         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23156       weight = CW_Register;
23157     break;
23158   case 'I':
23159     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23160       if (C->getZExtValue() <= 31)
23161         weight = CW_Constant;
23162     }
23163     break;
23164   case 'J':
23165     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23166       if (C->getZExtValue() <= 63)
23167         weight = CW_Constant;
23168     }
23169     break;
23170   case 'K':
23171     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23172       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23173         weight = CW_Constant;
23174     }
23175     break;
23176   case 'L':
23177     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23178       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23179         weight = CW_Constant;
23180     }
23181     break;
23182   case 'M':
23183     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23184       if (C->getZExtValue() <= 3)
23185         weight = CW_Constant;
23186     }
23187     break;
23188   case 'N':
23189     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23190       if (C->getZExtValue() <= 0xff)
23191         weight = CW_Constant;
23192     }
23193     break;
23194   case 'G':
23195   case 'C':
23196     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23197       weight = CW_Constant;
23198     }
23199     break;
23200   case 'e':
23201     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23202       if ((C->getSExtValue() >= -0x80000000LL) &&
23203           (C->getSExtValue() <= 0x7fffffffLL))
23204         weight = CW_Constant;
23205     }
23206     break;
23207   case 'Z':
23208     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23209       if (C->getZExtValue() <= 0xffffffff)
23210         weight = CW_Constant;
23211     }
23212     break;
23213   }
23214   return weight;
23215 }
23216
23217 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23218 /// with another that has more specific requirements based on the type of the
23219 /// corresponding operand.
23220 const char *X86TargetLowering::
23221 LowerXConstraint(EVT ConstraintVT) const {
23222   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23223   // 'f' like normal targets.
23224   if (ConstraintVT.isFloatingPoint()) {
23225     if (Subtarget->hasSSE2())
23226       return "Y";
23227     if (Subtarget->hasSSE1())
23228       return "x";
23229   }
23230
23231   return TargetLowering::LowerXConstraint(ConstraintVT);
23232 }
23233
23234 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23235 /// vector.  If it is invalid, don't add anything to Ops.
23236 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23237                                                      std::string &Constraint,
23238                                                      std::vector<SDValue>&Ops,
23239                                                      SelectionDAG &DAG) const {
23240   SDValue Result;
23241
23242   // Only support length 1 constraints for now.
23243   if (Constraint.length() > 1) return;
23244
23245   char ConstraintLetter = Constraint[0];
23246   switch (ConstraintLetter) {
23247   default: break;
23248   case 'I':
23249     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23250       if (C->getZExtValue() <= 31) {
23251         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23252         break;
23253       }
23254     }
23255     return;
23256   case 'J':
23257     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23258       if (C->getZExtValue() <= 63) {
23259         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23260         break;
23261       }
23262     }
23263     return;
23264   case 'K':
23265     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23266       if (isInt<8>(C->getSExtValue())) {
23267         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23268         break;
23269       }
23270     }
23271     return;
23272   case 'N':
23273     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23274       if (C->getZExtValue() <= 255) {
23275         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23276         break;
23277       }
23278     }
23279     return;
23280   case 'e': {
23281     // 32-bit signed value
23282     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23283       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23284                                            C->getSExtValue())) {
23285         // Widen to 64 bits here to get it sign extended.
23286         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23287         break;
23288       }
23289     // FIXME gcc accepts some relocatable values here too, but only in certain
23290     // memory models; it's complicated.
23291     }
23292     return;
23293   }
23294   case 'Z': {
23295     // 32-bit unsigned value
23296     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23297       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23298                                            C->getZExtValue())) {
23299         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23300         break;
23301       }
23302     }
23303     // FIXME gcc accepts some relocatable values here too, but only in certain
23304     // memory models; it's complicated.
23305     return;
23306   }
23307   case 'i': {
23308     // Literal immediates are always ok.
23309     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23310       // Widen to 64 bits here to get it sign extended.
23311       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23312       break;
23313     }
23314
23315     // In any sort of PIC mode addresses need to be computed at runtime by
23316     // adding in a register or some sort of table lookup.  These can't
23317     // be used as immediates.
23318     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23319       return;
23320
23321     // If we are in non-pic codegen mode, we allow the address of a global (with
23322     // an optional displacement) to be used with 'i'.
23323     GlobalAddressSDNode *GA = nullptr;
23324     int64_t Offset = 0;
23325
23326     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23327     while (1) {
23328       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23329         Offset += GA->getOffset();
23330         break;
23331       } else if (Op.getOpcode() == ISD::ADD) {
23332         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23333           Offset += C->getZExtValue();
23334           Op = Op.getOperand(0);
23335           continue;
23336         }
23337       } else if (Op.getOpcode() == ISD::SUB) {
23338         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23339           Offset += -C->getZExtValue();
23340           Op = Op.getOperand(0);
23341           continue;
23342         }
23343       }
23344
23345       // Otherwise, this isn't something we can handle, reject it.
23346       return;
23347     }
23348
23349     const GlobalValue *GV = GA->getGlobal();
23350     // If we require an extra load to get this address, as in PIC mode, we
23351     // can't accept it.
23352     if (isGlobalStubReference(
23353             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23354       return;
23355
23356     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23357                                         GA->getValueType(0), Offset);
23358     break;
23359   }
23360   }
23361
23362   if (Result.getNode()) {
23363     Ops.push_back(Result);
23364     return;
23365   }
23366   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23367 }
23368
23369 std::pair<unsigned, const TargetRegisterClass*>
23370 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23371                                                 MVT VT) const {
23372   // First, see if this is a constraint that directly corresponds to an LLVM
23373   // register class.
23374   if (Constraint.size() == 1) {
23375     // GCC Constraint Letters
23376     switch (Constraint[0]) {
23377     default: break;
23378       // TODO: Slight differences here in allocation order and leaving
23379       // RIP in the class. Do they matter any more here than they do
23380       // in the normal allocation?
23381     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23382       if (Subtarget->is64Bit()) {
23383         if (VT == MVT::i32 || VT == MVT::f32)
23384           return std::make_pair(0U, &X86::GR32RegClass);
23385         if (VT == MVT::i16)
23386           return std::make_pair(0U, &X86::GR16RegClass);
23387         if (VT == MVT::i8 || VT == MVT::i1)
23388           return std::make_pair(0U, &X86::GR8RegClass);
23389         if (VT == MVT::i64 || VT == MVT::f64)
23390           return std::make_pair(0U, &X86::GR64RegClass);
23391         break;
23392       }
23393       // 32-bit fallthrough
23394     case 'Q':   // Q_REGS
23395       if (VT == MVT::i32 || VT == MVT::f32)
23396         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23397       if (VT == MVT::i16)
23398         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23399       if (VT == MVT::i8 || VT == MVT::i1)
23400         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23401       if (VT == MVT::i64)
23402         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23403       break;
23404     case 'r':   // GENERAL_REGS
23405     case 'l':   // INDEX_REGS
23406       if (VT == MVT::i8 || VT == MVT::i1)
23407         return std::make_pair(0U, &X86::GR8RegClass);
23408       if (VT == MVT::i16)
23409         return std::make_pair(0U, &X86::GR16RegClass);
23410       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23411         return std::make_pair(0U, &X86::GR32RegClass);
23412       return std::make_pair(0U, &X86::GR64RegClass);
23413     case 'R':   // LEGACY_REGS
23414       if (VT == MVT::i8 || VT == MVT::i1)
23415         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23416       if (VT == MVT::i16)
23417         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23418       if (VT == MVT::i32 || !Subtarget->is64Bit())
23419         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23420       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23421     case 'f':  // FP Stack registers.
23422       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23423       // value to the correct fpstack register class.
23424       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23425         return std::make_pair(0U, &X86::RFP32RegClass);
23426       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23427         return std::make_pair(0U, &X86::RFP64RegClass);
23428       return std::make_pair(0U, &X86::RFP80RegClass);
23429     case 'y':   // MMX_REGS if MMX allowed.
23430       if (!Subtarget->hasMMX()) break;
23431       return std::make_pair(0U, &X86::VR64RegClass);
23432     case 'Y':   // SSE_REGS if SSE2 allowed
23433       if (!Subtarget->hasSSE2()) break;
23434       // FALL THROUGH.
23435     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23436       if (!Subtarget->hasSSE1()) break;
23437
23438       switch (VT.SimpleTy) {
23439       default: break;
23440       // Scalar SSE types.
23441       case MVT::f32:
23442       case MVT::i32:
23443         return std::make_pair(0U, &X86::FR32RegClass);
23444       case MVT::f64:
23445       case MVT::i64:
23446         return std::make_pair(0U, &X86::FR64RegClass);
23447       // Vector types.
23448       case MVT::v16i8:
23449       case MVT::v8i16:
23450       case MVT::v4i32:
23451       case MVT::v2i64:
23452       case MVT::v4f32:
23453       case MVT::v2f64:
23454         return std::make_pair(0U, &X86::VR128RegClass);
23455       // AVX types.
23456       case MVT::v32i8:
23457       case MVT::v16i16:
23458       case MVT::v8i32:
23459       case MVT::v4i64:
23460       case MVT::v8f32:
23461       case MVT::v4f64:
23462         return std::make_pair(0U, &X86::VR256RegClass);
23463       case MVT::v8f64:
23464       case MVT::v16f32:
23465       case MVT::v16i32:
23466       case MVT::v8i64:
23467         return std::make_pair(0U, &X86::VR512RegClass);
23468       }
23469       break;
23470     }
23471   }
23472
23473   // Use the default implementation in TargetLowering to convert the register
23474   // constraint into a member of a register class.
23475   std::pair<unsigned, const TargetRegisterClass*> Res;
23476   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23477
23478   // Not found as a standard register?
23479   if (!Res.second) {
23480     // Map st(0) -> st(7) -> ST0
23481     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23482         tolower(Constraint[1]) == 's' &&
23483         tolower(Constraint[2]) == 't' &&
23484         Constraint[3] == '(' &&
23485         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23486         Constraint[5] == ')' &&
23487         Constraint[6] == '}') {
23488
23489       Res.first = X86::FP0+Constraint[4]-'0';
23490       Res.second = &X86::RFP80RegClass;
23491       return Res;
23492     }
23493
23494     // GCC allows "st(0)" to be called just plain "st".
23495     if (StringRef("{st}").equals_lower(Constraint)) {
23496       Res.first = X86::FP0;
23497       Res.second = &X86::RFP80RegClass;
23498       return Res;
23499     }
23500
23501     // flags -> EFLAGS
23502     if (StringRef("{flags}").equals_lower(Constraint)) {
23503       Res.first = X86::EFLAGS;
23504       Res.second = &X86::CCRRegClass;
23505       return Res;
23506     }
23507
23508     // 'A' means EAX + EDX.
23509     if (Constraint == "A") {
23510       Res.first = X86::EAX;
23511       Res.second = &X86::GR32_ADRegClass;
23512       return Res;
23513     }
23514     return Res;
23515   }
23516
23517   // Otherwise, check to see if this is a register class of the wrong value
23518   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23519   // turn into {ax},{dx}.
23520   if (Res.second->hasType(VT))
23521     return Res;   // Correct type already, nothing to do.
23522
23523   // All of the single-register GCC register classes map their values onto
23524   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23525   // really want an 8-bit or 32-bit register, map to the appropriate register
23526   // class and return the appropriate register.
23527   if (Res.second == &X86::GR16RegClass) {
23528     if (VT == MVT::i8 || VT == MVT::i1) {
23529       unsigned DestReg = 0;
23530       switch (Res.first) {
23531       default: break;
23532       case X86::AX: DestReg = X86::AL; break;
23533       case X86::DX: DestReg = X86::DL; break;
23534       case X86::CX: DestReg = X86::CL; break;
23535       case X86::BX: DestReg = X86::BL; break;
23536       }
23537       if (DestReg) {
23538         Res.first = DestReg;
23539         Res.second = &X86::GR8RegClass;
23540       }
23541     } else if (VT == MVT::i32 || VT == MVT::f32) {
23542       unsigned DestReg = 0;
23543       switch (Res.first) {
23544       default: break;
23545       case X86::AX: DestReg = X86::EAX; break;
23546       case X86::DX: DestReg = X86::EDX; break;
23547       case X86::CX: DestReg = X86::ECX; break;
23548       case X86::BX: DestReg = X86::EBX; break;
23549       case X86::SI: DestReg = X86::ESI; break;
23550       case X86::DI: DestReg = X86::EDI; break;
23551       case X86::BP: DestReg = X86::EBP; break;
23552       case X86::SP: DestReg = X86::ESP; break;
23553       }
23554       if (DestReg) {
23555         Res.first = DestReg;
23556         Res.second = &X86::GR32RegClass;
23557       }
23558     } else if (VT == MVT::i64 || VT == MVT::f64) {
23559       unsigned DestReg = 0;
23560       switch (Res.first) {
23561       default: break;
23562       case X86::AX: DestReg = X86::RAX; break;
23563       case X86::DX: DestReg = X86::RDX; break;
23564       case X86::CX: DestReg = X86::RCX; break;
23565       case X86::BX: DestReg = X86::RBX; break;
23566       case X86::SI: DestReg = X86::RSI; break;
23567       case X86::DI: DestReg = X86::RDI; break;
23568       case X86::BP: DestReg = X86::RBP; break;
23569       case X86::SP: DestReg = X86::RSP; break;
23570       }
23571       if (DestReg) {
23572         Res.first = DestReg;
23573         Res.second = &X86::GR64RegClass;
23574       }
23575     }
23576   } else if (Res.second == &X86::FR32RegClass ||
23577              Res.second == &X86::FR64RegClass ||
23578              Res.second == &X86::VR128RegClass ||
23579              Res.second == &X86::VR256RegClass ||
23580              Res.second == &X86::FR32XRegClass ||
23581              Res.second == &X86::FR64XRegClass ||
23582              Res.second == &X86::VR128XRegClass ||
23583              Res.second == &X86::VR256XRegClass ||
23584              Res.second == &X86::VR512RegClass) {
23585     // Handle references to XMM physical registers that got mapped into the
23586     // wrong class.  This can happen with constraints like {xmm0} where the
23587     // target independent register mapper will just pick the first match it can
23588     // find, ignoring the required type.
23589
23590     if (VT == MVT::f32 || VT == MVT::i32)
23591       Res.second = &X86::FR32RegClass;
23592     else if (VT == MVT::f64 || VT == MVT::i64)
23593       Res.second = &X86::FR64RegClass;
23594     else if (X86::VR128RegClass.hasType(VT))
23595       Res.second = &X86::VR128RegClass;
23596     else if (X86::VR256RegClass.hasType(VT))
23597       Res.second = &X86::VR256RegClass;
23598     else if (X86::VR512RegClass.hasType(VT))
23599       Res.second = &X86::VR512RegClass;
23600   }
23601
23602   return Res;
23603 }
23604
23605 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23606                                             Type *Ty) const {
23607   // Scaling factors are not free at all.
23608   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23609   // will take 2 allocations in the out of order engine instead of 1
23610   // for plain addressing mode, i.e. inst (reg1).
23611   // E.g.,
23612   // vaddps (%rsi,%drx), %ymm0, %ymm1
23613   // Requires two allocations (one for the load, one for the computation)
23614   // whereas:
23615   // vaddps (%rsi), %ymm0, %ymm1
23616   // Requires just 1 allocation, i.e., freeing allocations for other operations
23617   // and having less micro operations to execute.
23618   //
23619   // For some X86 architectures, this is even worse because for instance for
23620   // stores, the complex addressing mode forces the instruction to use the
23621   // "load" ports instead of the dedicated "store" port.
23622   // E.g., on Haswell:
23623   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23624   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23625   if (isLegalAddressingMode(AM, Ty))
23626     // Scale represents reg2 * scale, thus account for 1
23627     // as soon as we use a second register.
23628     return AM.Scale != 0;
23629   return -1;
23630 }
23631
23632 bool X86TargetLowering::isTargetFTOL() const {
23633   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23634 }