[Statepoints 2/4] Statepoint infrastructure for garbage collection: MI & x86-64 Backend
[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/SmallBitVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/VariadicFunction.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
54 #include <bitset>
55 #include <numeric>
56 #include <cctype>
57 using namespace llvm;
58
59 #define DEBUG_TYPE "x86-isel"
60
61 STATISTIC(NumTailCalls, "Number of tail calls");
62
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64     "x86-experimental-vector-widening-legalization", cl::init(false),
65     cl::desc("Enable an experimental vector type legalization through widening "
66              "rather than promotion."),
67     cl::Hidden);
68
69 static cl::opt<bool> ExperimentalVectorShuffleLowering(
70     "x86-experimental-vector-shuffle-lowering", cl::init(true),
71     cl::desc("Enable an experimental vector shuffle lowering code path."),
72     cl::Hidden);
73
74 static cl::opt<int> ReciprocalEstimateRefinementSteps(
75     "x86-recip-refinement-steps", cl::init(1),
76     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
77              "result of the hardware reciprocal estimate instruction."),
78     cl::NotHidden);
79
80 // Forward declarations.
81 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
82                        SDValue V2);
83
84 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
85                                 SelectionDAG &DAG, SDLoc dl,
86                                 unsigned vectorWidth) {
87   assert((vectorWidth == 128 || vectorWidth == 256) &&
88          "Unsupported vector width");
89   EVT VT = Vec.getValueType();
90   EVT ElVT = VT.getVectorElementType();
91   unsigned Factor = VT.getSizeInBits()/vectorWidth;
92   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
93                                   VT.getVectorNumElements()/Factor);
94
95   // Extract from UNDEF is UNDEF.
96   if (Vec.getOpcode() == ISD::UNDEF)
97     return DAG.getUNDEF(ResultVT);
98
99   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
100   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
101
102   // This is the index of the first element of the vectorWidth-bit chunk
103   // we want.
104   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
105                                * ElemsPerChunk);
106
107   // If the input is a buildvector just emit a smaller one.
108   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
109     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
110                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
111                                     ElemsPerChunk));
112
113   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
114   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
115                                VecIdx);
116
117   return Result;
118
119 }
120 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
121 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
122 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
123 /// instructions or a simple subregister reference. Idx is an index in the
124 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
125 /// lowering EXTRACT_VECTOR_ELT operations easier.
126 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert((Vec.getValueType().is256BitVector() ||
129           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
130   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
131 }
132
133 /// Generate a DAG to grab 256-bits from a 512-bit vector.
134 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
135                                    SelectionDAG &DAG, SDLoc dl) {
136   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
137   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
138 }
139
140 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
141                                unsigned IdxVal, SelectionDAG &DAG,
142                                SDLoc dl, unsigned vectorWidth) {
143   assert((vectorWidth == 128 || vectorWidth == 256) &&
144          "Unsupported vector width");
145   // Inserting UNDEF is Result
146   if (Vec.getOpcode() == ISD::UNDEF)
147     return Result;
148   EVT VT = Vec.getValueType();
149   EVT ElVT = VT.getVectorElementType();
150   EVT ResultVT = Result.getValueType();
151
152   // Insert the relevant vectorWidth bits.
153   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
154
155   // This is the index of the first element of the vectorWidth-bit chunk
156   // we want.
157   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
158                                * ElemsPerChunk);
159
160   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
161   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
162                      VecIdx);
163 }
164 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
165 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
166 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
167 /// simple superregister reference.  Idx is an index in the 128 bits
168 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
169 /// lowering INSERT_VECTOR_ELT operations easier.
170 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
171                                   unsigned IdxVal, SelectionDAG &DAG,
172                                   SDLoc dl) {
173   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
174   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
175 }
176
177 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
178                                   unsigned IdxVal, SelectionDAG &DAG,
179                                   SDLoc dl) {
180   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
181   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
182 }
183
184 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
185 /// instructions. This is used because creating CONCAT_VECTOR nodes of
186 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
187 /// large BUILD_VECTORS.
188 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
189                                    unsigned NumElems, SelectionDAG &DAG,
190                                    SDLoc dl) {
191   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
192   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
193 }
194
195 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
196                                    unsigned NumElems, SelectionDAG &DAG,
197                                    SDLoc dl) {
198   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
199   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
200 }
201
202 // FIXME: This should stop caching the target machine as soon as
203 // we can remove resetOperationActions et al.
204 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM)
205     : TargetLowering(TM) {
206   Subtarget = &TM.getSubtarget<X86Subtarget>();
207   X86ScalarSSEf64 = Subtarget->hasSSE2();
208   X86ScalarSSEf32 = Subtarget->hasSSE1();
209   TD = getDataLayout();
210
211   resetOperationActions();
212 }
213
214 void X86TargetLowering::resetOperationActions() {
215   const TargetMachine &TM = getTargetMachine();
216   static bool FirstTimeThrough = true;
217
218   // If none of the target options have changed, then we don't need to reset the
219   // operation actions.
220   if (!FirstTimeThrough && TO == TM.Options) return;
221
222   if (!FirstTimeThrough) {
223     // Reinitialize the actions.
224     initActions();
225     FirstTimeThrough = false;
226   }
227
228   TO = TM.Options;
229
230   // Set up the TargetLowering object.
231   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
232
233   // X86 is weird, it always uses i8 for shift amounts and setcc results.
234   setBooleanContents(ZeroOrOneBooleanContent);
235   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
236   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
237
238   // For 64-bit since we have so many registers use the ILP scheduler, for
239   // 32-bit code use the register pressure specific scheduling.
240   // For Atom, always use ILP scheduling.
241   if (Subtarget->isAtom())
242     setSchedulingPreference(Sched::ILP);
243   else if (Subtarget->is64Bit())
244     setSchedulingPreference(Sched::ILP);
245   else
246     setSchedulingPreference(Sched::RegPressure);
247   const X86RegisterInfo *RegInfo =
248       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
249   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
250
251   // Bypass expensive divides on Atom when compiling with O2
252   if (TM.getOptLevel() >= CodeGenOpt::Default) {
253     if (Subtarget->hasSlowDivide32()) 
254       addBypassSlowDiv(32, 8);
255     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
256       addBypassSlowDiv(64, 16);
257   }
258
259   if (Subtarget->isTargetKnownWindowsMSVC()) {
260     // Setup Windows compiler runtime calls.
261     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
262     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
263     setLibcallName(RTLIB::SREM_I64, "_allrem");
264     setLibcallName(RTLIB::UREM_I64, "_aullrem");
265     setLibcallName(RTLIB::MUL_I64, "_allmul");
266     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
267     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
268     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
269     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
270     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
271
272     // The _ftol2 runtime function has an unusual calling conv, which
273     // is modeled by a special pseudo-instruction.
274     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
275     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
276     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
277     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
278   }
279
280   if (Subtarget->isTargetDarwin()) {
281     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
282     setUseUnderscoreSetJmp(false);
283     setUseUnderscoreLongJmp(false);
284   } else if (Subtarget->isTargetWindowsGNU()) {
285     // MS runtime is weird: it exports _setjmp, but longjmp!
286     setUseUnderscoreSetJmp(true);
287     setUseUnderscoreLongJmp(false);
288   } else {
289     setUseUnderscoreSetJmp(true);
290     setUseUnderscoreLongJmp(true);
291   }
292
293   // Set up the register classes.
294   addRegisterClass(MVT::i8, &X86::GR8RegClass);
295   addRegisterClass(MVT::i16, &X86::GR16RegClass);
296   addRegisterClass(MVT::i32, &X86::GR32RegClass);
297   if (Subtarget->is64Bit())
298     addRegisterClass(MVT::i64, &X86::GR64RegClass);
299
300   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
301
302   // We don't accept any truncstore of integer registers.
303   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
304   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
305   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
306   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
307   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
308   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
309
310   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
311
312   // SETOEQ and SETUNE require checking two conditions.
313   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
314   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
315   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
316   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
317   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
318   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
319
320   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
321   // operation.
322   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
323   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
324   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
325
326   if (Subtarget->is64Bit()) {
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
328     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
329   } else if (!TM.Options.UseSoftFloat) {
330     // We have an algorithm for SSE2->double, and we turn this into a
331     // 64-bit FILD followed by conditional FADD for other targets.
332     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
333     // We have an algorithm for SSE2, and we turn this into a 64-bit
334     // FILD for other targets.
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
336   }
337
338   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
339   // this operation.
340   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
341   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
342
343   if (!TM.Options.UseSoftFloat) {
344     // SSE has no i16 to fp conversion, only i32
345     if (X86ScalarSSEf32) {
346       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
347       // f32 and f64 cases are Legal, f80 case is not
348       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
349     } else {
350       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
351       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
352     }
353   } else {
354     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
355     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
356   }
357
358   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
359   // are Legal, f80 is custom lowered.
360   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
361   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
362
363   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
364   // this operation.
365   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
366   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
367
368   if (X86ScalarSSEf32) {
369     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
370     // f32 and f64 cases are Legal, f80 case is not
371     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
372   } else {
373     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
374     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
375   }
376
377   // Handle FP_TO_UINT by promoting the destination to a larger signed
378   // conversion.
379   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
380   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
381   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
382
383   if (Subtarget->is64Bit()) {
384     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
385     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
386   } else if (!TM.Options.UseSoftFloat) {
387     // Since AVX is a superset of SSE3, only check for SSE here.
388     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
389       // Expand FP_TO_UINT into a select.
390       // FIXME: We would like to use a Custom expander here eventually to do
391       // the optimal thing for SSE vs. the default expansion in the legalizer.
392       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
393     else
394       // With SSE3 we can use fisttpll to convert to a signed i64; without
395       // SSE, we're stuck with a fistpll.
396       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
397   }
398
399   if (isTargetFTOL()) {
400     // Use the _ftol2 runtime function, which has a pseudo-instruction
401     // to handle its weird calling convention.
402     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
403   }
404
405   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
406   if (!X86ScalarSSEf64) {
407     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
408     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
409     if (Subtarget->is64Bit()) {
410       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
411       // Without SSE, i64->f64 goes through memory.
412       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
413     }
414   }
415
416   // Scalar integer divide and remainder are lowered to use operations that
417   // produce two results, to match the available instructions. This exposes
418   // the two-result form to trivial CSE, which is able to combine x/y and x%y
419   // into a single instruction.
420   //
421   // Scalar integer multiply-high is also lowered to use two-result
422   // operations, to match the available instructions. However, plain multiply
423   // (low) operations are left as Legal, as there are single-result
424   // instructions for this in x86. Using the two-result multiply instructions
425   // when both high and low results are needed must be arranged by dagcombine.
426   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
427     MVT VT = IntVTs[i];
428     setOperationAction(ISD::MULHS, VT, Expand);
429     setOperationAction(ISD::MULHU, VT, Expand);
430     setOperationAction(ISD::SDIV, VT, Expand);
431     setOperationAction(ISD::UDIV, VT, Expand);
432     setOperationAction(ISD::SREM, VT, Expand);
433     setOperationAction(ISD::UREM, VT, Expand);
434
435     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
436     setOperationAction(ISD::ADDC, VT, Custom);
437     setOperationAction(ISD::ADDE, VT, Custom);
438     setOperationAction(ISD::SUBC, VT, Custom);
439     setOperationAction(ISD::SUBE, VT, Custom);
440   }
441
442   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
443   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
444   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
446   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
447   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
448   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
449   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
450   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
451   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
452   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
453   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
454   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
455   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
456   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
457   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
458   if (Subtarget->is64Bit())
459     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
460   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
461   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
462   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
463   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
464   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
465   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
466   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
467   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
468
469   // Promote the i8 variants and force them on up to i32 which has a shorter
470   // encoding.
471   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
472   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
473   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
474   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
475   if (Subtarget->hasBMI()) {
476     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
478     if (Subtarget->is64Bit())
479       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
480   } else {
481     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
482     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
483     if (Subtarget->is64Bit())
484       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
485   }
486
487   if (Subtarget->hasLZCNT()) {
488     // When promoting the i8 variants, force them to i32 for a shorter
489     // encoding.
490     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
491     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
492     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
493     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
494     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
495     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
496     if (Subtarget->is64Bit())
497       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
498   } else {
499     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
500     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
501     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
504     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
505     if (Subtarget->is64Bit()) {
506       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
507       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
508     }
509   }
510
511   // Special handling for half-precision floating point conversions.
512   // If we don't have F16C support, then lower half float conversions
513   // into library calls.
514   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
515     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
516     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
517   }
518
519   // There's never any support for operations beyond MVT::f32.
520   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
521   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
522   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
523   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
524
525   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
526   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
527   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
528   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
529
530   if (Subtarget->hasPOPCNT()) {
531     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
532   } else {
533     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
534     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
535     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
536     if (Subtarget->is64Bit())
537       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
538   }
539
540   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
541
542   if (!Subtarget->hasMOVBE())
543     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
544
545   // These should be promoted to a larger select which is supported.
546   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
547   // X86 wants to expand cmov itself.
548   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
549   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
550   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
551   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
552   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
553   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
554   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
555   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
556   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
557   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
558   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
559   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
560   if (Subtarget->is64Bit()) {
561     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
562     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
563   }
564   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
565   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
566   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
567   // support continuation, user-level threading, and etc.. As a result, no
568   // other SjLj exception interfaces are implemented and please don't build
569   // your own exception handling based on them.
570   // LLVM/Clang supports zero-cost DWARF exception handling.
571   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
572   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
573
574   // Darwin ABI issue.
575   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
576   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
577   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
578   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
579   if (Subtarget->is64Bit())
580     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
581   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
582   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
583   if (Subtarget->is64Bit()) {
584     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
585     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
586     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
587     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
588     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
589   }
590   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
591   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
592   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
593   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
594   if (Subtarget->is64Bit()) {
595     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
596     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
597     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
598   }
599
600   if (Subtarget->hasSSE1())
601     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
602
603   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
604
605   // Expand certain atomics
606   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
607     MVT VT = IntVTs[i];
608     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
609     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
610     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
611   }
612
613   if (Subtarget->hasCmpxchg16b()) {
614     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
615   }
616
617   // FIXME - use subtarget debug flags
618   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
619       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
620     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
621   }
622
623   if (Subtarget->is64Bit()) {
624     setExceptionPointerRegister(X86::RAX);
625     setExceptionSelectorRegister(X86::RDX);
626   } else {
627     setExceptionPointerRegister(X86::EAX);
628     setExceptionSelectorRegister(X86::EDX);
629   }
630   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
631   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
632
633   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
634   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
635
636   setOperationAction(ISD::TRAP, MVT::Other, Legal);
637   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
638
639   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
640   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
641   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
642   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
643     // TargetInfo::X86_64ABIBuiltinVaList
644     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
645     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
646   } else {
647     // TargetInfo::CharPtrBuiltinVaList
648     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
649     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
650   }
651
652   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
653   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
654
655   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
656
657   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
658     // f32 and f64 use SSE.
659     // Set up the FP register classes.
660     addRegisterClass(MVT::f32, &X86::FR32RegClass);
661     addRegisterClass(MVT::f64, &X86::FR64RegClass);
662
663     // Use ANDPD to simulate FABS.
664     setOperationAction(ISD::FABS , MVT::f64, Custom);
665     setOperationAction(ISD::FABS , MVT::f32, Custom);
666
667     // Use XORP to simulate FNEG.
668     setOperationAction(ISD::FNEG , MVT::f64, Custom);
669     setOperationAction(ISD::FNEG , MVT::f32, Custom);
670
671     // Use ANDPD and ORPD to simulate FCOPYSIGN.
672     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
673     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
674
675     // Lower this to FGETSIGNx86 plus an AND.
676     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
677     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
678
679     // We don't support sin/cos/fmod
680     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
681     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
682     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
683     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
684     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
685     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
686
687     // Expand FP immediates into loads from the stack, except for the special
688     // cases we handle.
689     addLegalFPImmediate(APFloat(+0.0)); // xorpd
690     addLegalFPImmediate(APFloat(+0.0f)); // xorps
691   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
692     // Use SSE for f32, x87 for f64.
693     // Set up the FP register classes.
694     addRegisterClass(MVT::f32, &X86::FR32RegClass);
695     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
696
697     // Use ANDPS to simulate FABS.
698     setOperationAction(ISD::FABS , MVT::f32, Custom);
699
700     // Use XORP to simulate FNEG.
701     setOperationAction(ISD::FNEG , MVT::f32, Custom);
702
703     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
704
705     // Use ANDPS and ORPS to simulate FCOPYSIGN.
706     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
707     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
708
709     // We don't support sin/cos/fmod
710     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
711     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
712     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
713
714     // Special cases we handle for FP constants.
715     addLegalFPImmediate(APFloat(+0.0f)); // xorps
716     addLegalFPImmediate(APFloat(+0.0)); // FLD0
717     addLegalFPImmediate(APFloat(+1.0)); // FLD1
718     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
719     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
720
721     if (!TM.Options.UnsafeFPMath) {
722       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
723       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
724       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
725     }
726   } else if (!TM.Options.UseSoftFloat) {
727     // f32 and f64 in x87.
728     // Set up the FP register classes.
729     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
730     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
731
732     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
733     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
734     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
735     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
736
737     if (!TM.Options.UnsafeFPMath) {
738       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
739       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
740       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
741       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
742       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
743       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
744     }
745     addLegalFPImmediate(APFloat(+0.0)); // FLD0
746     addLegalFPImmediate(APFloat(+1.0)); // FLD1
747     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
748     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
749     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
750     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
751     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
752     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
753   }
754
755   // We don't support FMA.
756   setOperationAction(ISD::FMA, MVT::f64, Expand);
757   setOperationAction(ISD::FMA, MVT::f32, Expand);
758
759   // Long double always uses X87.
760   if (!TM.Options.UseSoftFloat) {
761     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
762     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
763     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
764     {
765       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
766       addLegalFPImmediate(TmpFlt);  // FLD0
767       TmpFlt.changeSign();
768       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
769
770       bool ignored;
771       APFloat TmpFlt2(+1.0);
772       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
773                       &ignored);
774       addLegalFPImmediate(TmpFlt2);  // FLD1
775       TmpFlt2.changeSign();
776       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
777     }
778
779     if (!TM.Options.UnsafeFPMath) {
780       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
781       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
782       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
783     }
784
785     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
786     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
787     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
788     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
789     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
790     setOperationAction(ISD::FMA, MVT::f80, Expand);
791   }
792
793   // Always use a library call for pow.
794   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
795   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
796   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
797
798   setOperationAction(ISD::FLOG, MVT::f80, Expand);
799   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
800   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
801   setOperationAction(ISD::FEXP, MVT::f80, Expand);
802   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
803   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
804   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
805
806   // First set operation action for all vector types to either promote
807   // (for widening) or expand (for scalarization). Then we will selectively
808   // turn on ones that can be effectively codegen'd.
809   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
810            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
811     MVT VT = (MVT::SimpleValueType)i;
812     setOperationAction(ISD::ADD , VT, Expand);
813     setOperationAction(ISD::SUB , VT, Expand);
814     setOperationAction(ISD::FADD, VT, Expand);
815     setOperationAction(ISD::FNEG, VT, Expand);
816     setOperationAction(ISD::FSUB, VT, Expand);
817     setOperationAction(ISD::MUL , VT, Expand);
818     setOperationAction(ISD::FMUL, VT, Expand);
819     setOperationAction(ISD::SDIV, VT, Expand);
820     setOperationAction(ISD::UDIV, VT, Expand);
821     setOperationAction(ISD::FDIV, VT, Expand);
822     setOperationAction(ISD::SREM, VT, Expand);
823     setOperationAction(ISD::UREM, VT, Expand);
824     setOperationAction(ISD::LOAD, VT, Expand);
825     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
826     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
827     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
828     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
829     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
830     setOperationAction(ISD::FABS, VT, Expand);
831     setOperationAction(ISD::FSIN, VT, Expand);
832     setOperationAction(ISD::FSINCOS, VT, Expand);
833     setOperationAction(ISD::FCOS, VT, Expand);
834     setOperationAction(ISD::FSINCOS, VT, Expand);
835     setOperationAction(ISD::FREM, VT, Expand);
836     setOperationAction(ISD::FMA,  VT, Expand);
837     setOperationAction(ISD::FPOWI, VT, Expand);
838     setOperationAction(ISD::FSQRT, VT, Expand);
839     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
840     setOperationAction(ISD::FFLOOR, VT, Expand);
841     setOperationAction(ISD::FCEIL, VT, Expand);
842     setOperationAction(ISD::FTRUNC, VT, Expand);
843     setOperationAction(ISD::FRINT, VT, Expand);
844     setOperationAction(ISD::FNEARBYINT, VT, Expand);
845     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
846     setOperationAction(ISD::MULHS, VT, Expand);
847     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
848     setOperationAction(ISD::MULHU, VT, Expand);
849     setOperationAction(ISD::SDIVREM, VT, Expand);
850     setOperationAction(ISD::UDIVREM, VT, Expand);
851     setOperationAction(ISD::FPOW, VT, Expand);
852     setOperationAction(ISD::CTPOP, VT, Expand);
853     setOperationAction(ISD::CTTZ, VT, Expand);
854     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
855     setOperationAction(ISD::CTLZ, VT, Expand);
856     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
857     setOperationAction(ISD::SHL, VT, Expand);
858     setOperationAction(ISD::SRA, VT, Expand);
859     setOperationAction(ISD::SRL, VT, Expand);
860     setOperationAction(ISD::ROTL, VT, Expand);
861     setOperationAction(ISD::ROTR, VT, Expand);
862     setOperationAction(ISD::BSWAP, VT, Expand);
863     setOperationAction(ISD::SETCC, VT, Expand);
864     setOperationAction(ISD::FLOG, VT, Expand);
865     setOperationAction(ISD::FLOG2, VT, Expand);
866     setOperationAction(ISD::FLOG10, VT, Expand);
867     setOperationAction(ISD::FEXP, VT, Expand);
868     setOperationAction(ISD::FEXP2, VT, Expand);
869     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
870     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
871     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
872     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
873     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
874     setOperationAction(ISD::TRUNCATE, VT, Expand);
875     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
876     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
877     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
878     setOperationAction(ISD::VSELECT, VT, Expand);
879     setOperationAction(ISD::SELECT_CC, VT, Expand);
880     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
881              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
882       setTruncStoreAction(VT,
883                           (MVT::SimpleValueType)InnerVT, Expand);
884     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
885     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
886
887     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
888     // we have to deal with them whether we ask for Expansion or not. Setting
889     // Expand causes its own optimisation problems though, so leave them legal.
890     if (VT.getVectorElementType() == MVT::i1)
891       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
892   }
893
894   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
895   // with -msoft-float, disable use of MMX as well.
896   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
897     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
898     // No operations on x86mmx supported, everything uses intrinsics.
899   }
900
901   // MMX-sized vectors (other than x86mmx) are expected to be expanded
902   // into smaller operations.
903   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
904   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
905   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
906   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
907   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
908   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
909   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
910   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
911   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
912   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
913   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
914   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
915   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
916   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
917   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
918   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
919   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
920   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
921   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
922   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
923   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
924   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
925   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
926   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
927   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
928   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
929   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
930   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
931   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
932
933   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
934     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
935
936     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
937     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
938     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
939     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
940     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
941     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
942     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
943     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
944     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
945     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
947     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
948     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
949   }
950
951   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
952     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
953
954     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
955     // registers cannot be used even for integer operations.
956     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
957     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
958     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
959     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
960
961     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
962     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
963     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
964     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
965     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
966     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
967     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
968     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
969     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
970     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
971     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
972     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
973     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
974     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
975     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
976     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
977     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
978     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
979     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
980     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
981     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
982     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
983
984     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
985     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
986     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
987     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
988
989     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
990     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
992     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
993     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
994
995     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
996     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
997       MVT VT = (MVT::SimpleValueType)i;
998       // Do not attempt to custom lower non-power-of-2 vectors
999       if (!isPowerOf2_32(VT.getVectorNumElements()))
1000         continue;
1001       // Do not attempt to custom lower non-128-bit vectors
1002       if (!VT.is128BitVector())
1003         continue;
1004       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1005       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1006       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1007     }
1008
1009     // We support custom legalizing of sext and anyext loads for specific
1010     // memory vector types which we can load as a scalar (or sequence of
1011     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1012     // loads these must work with a single scalar load.
1013     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1014     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1015     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1016     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1017     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1018     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1019     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1020     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1021     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1022
1023     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1024     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1025     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1026     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1027     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1028     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1029
1030     if (Subtarget->is64Bit()) {
1031       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1032       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1033     }
1034
1035     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1036     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1037       MVT VT = (MVT::SimpleValueType)i;
1038
1039       // Do not attempt to promote non-128-bit vectors
1040       if (!VT.is128BitVector())
1041         continue;
1042
1043       setOperationAction(ISD::AND,    VT, Promote);
1044       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1045       setOperationAction(ISD::OR,     VT, Promote);
1046       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1047       setOperationAction(ISD::XOR,    VT, Promote);
1048       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1049       setOperationAction(ISD::LOAD,   VT, Promote);
1050       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1051       setOperationAction(ISD::SELECT, VT, Promote);
1052       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1053     }
1054
1055     // Custom lower v2i64 and v2f64 selects.
1056     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1057     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1058     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1059     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1060
1061     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1062     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1063
1064     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1065     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1066     // As there is no 64-bit GPR available, we need build a special custom
1067     // sequence to convert from v2i32 to v2f32.
1068     if (!Subtarget->is64Bit())
1069       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1070
1071     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1072     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1073
1074     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1075
1076     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1077     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1078     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1079   }
1080
1081   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1082     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1085     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1087     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1088     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1089     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1090     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1091     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1092
1093     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1094     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1095     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1096     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1097     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1098     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1099     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1100     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1101     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1102     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1103
1104     // FIXME: Do we need to handle scalar-to-vector here?
1105     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1106
1107     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1108     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1109     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1110     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1111     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1112     // There is no BLENDI for byte vectors. We don't need to custom lower
1113     // some vselects for now.
1114     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1115
1116     // SSE41 brings specific instructions for doing vector sign extend even in
1117     // cases where we don't have SRA.
1118     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1119     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1120     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1121
1122     // i8 and i16 vectors are custom because the source register and source
1123     // source memory operand types are not the same width.  f32 vectors are
1124     // custom since the immediate controlling the insert encodes additional
1125     // information.
1126     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1127     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1128     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1129     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1130
1131     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1132     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1133     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1134     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1135
1136     // FIXME: these should be Legal, but that's only for the case where
1137     // the index is constant.  For now custom expand to deal with that.
1138     if (Subtarget->is64Bit()) {
1139       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1140       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1141     }
1142   }
1143
1144   if (Subtarget->hasSSE2()) {
1145     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1146     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1147
1148     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1149     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1150
1151     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1152     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1153
1154     // In the customized shift lowering, the legal cases in AVX2 will be
1155     // recognized.
1156     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1157     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1158
1159     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1160     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1161
1162     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1163   }
1164
1165   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1166     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1167     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1168     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1169     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1170     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1171     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1172
1173     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1174     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1175     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1176
1177     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1178     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1179     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1180     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1181     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1182     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1183     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1184     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1185     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1186     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1187     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1188     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1189
1190     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1191     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1192     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1193     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1194     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1195     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1196     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1197     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1198     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1199     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1200     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1201     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1202
1203     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1204     // even though v8i16 is a legal type.
1205     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1206     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1207     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1208
1209     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1210     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1211     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1212
1213     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1214     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1215
1216     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1217
1218     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1219     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1220
1221     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1222     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1223
1224     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1225     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1226
1227     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1228     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1229     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1230     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1231
1232     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1233     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1234     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1235
1236     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1237     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1238     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1239     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1240
1241     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1242     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1243     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1244     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1245     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1246     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1247     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1248     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1249     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1250     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1251     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1252     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1253
1254     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1255       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1256       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1257       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1258       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1259       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1260       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1261     }
1262
1263     if (Subtarget->hasInt256()) {
1264       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1265       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1266       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1267       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1268
1269       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1270       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1271       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1272       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1273
1274       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1275       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1276       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1277       // Don't lower v32i8 because there is no 128-bit byte mul
1278
1279       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1280       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1281       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1282       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1283
1284       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1285       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1286
1287       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1288       // when we have a 256bit-wide blend with immediate.
1289       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1290     } else {
1291       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1292       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1293       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1294       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1295
1296       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1299       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1300
1301       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1302       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1303       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1304       // Don't lower v32i8 because there is no 128-bit byte mul
1305     }
1306
1307     // In the customized shift lowering, the legal cases in AVX2 will be
1308     // recognized.
1309     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1310     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1311
1312     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1313     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1314
1315     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1316
1317     // Custom lower several nodes for 256-bit types.
1318     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1319              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1320       MVT VT = (MVT::SimpleValueType)i;
1321
1322       // Extract subvector is special because the value type
1323       // (result) is 128-bit but the source is 256-bit wide.
1324       if (VT.is128BitVector())
1325         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1326
1327       // Do not attempt to custom lower other non-256-bit vectors
1328       if (!VT.is256BitVector())
1329         continue;
1330
1331       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1332       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1333       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1334       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1335       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1336       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1337       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1338     }
1339
1340     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1341     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1342       MVT VT = (MVT::SimpleValueType)i;
1343
1344       // Do not attempt to promote non-256-bit vectors
1345       if (!VT.is256BitVector())
1346         continue;
1347
1348       setOperationAction(ISD::AND,    VT, Promote);
1349       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1350       setOperationAction(ISD::OR,     VT, Promote);
1351       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1352       setOperationAction(ISD::XOR,    VT, Promote);
1353       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1354       setOperationAction(ISD::LOAD,   VT, Promote);
1355       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1356       setOperationAction(ISD::SELECT, VT, Promote);
1357       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1358     }
1359   }
1360
1361   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1362     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1363     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1364     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1365     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1366
1367     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1368     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1369     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1370
1371     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1372     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1373     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1374     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1375     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1376     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1377     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1378     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1379     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1380     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1382
1383     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1384     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1385     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1386     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1387     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1388     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1389
1390     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1391     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1392     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1393     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1394     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1395     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1396     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1397     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1398
1399     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1400     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1401     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1402     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1403     if (Subtarget->is64Bit()) {
1404       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1405       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1406       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1407       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1408     }
1409     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1410     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1411     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1412     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1413     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1415     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1416     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1417     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1421     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1422     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1423
1424     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1437
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1444
1445     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1446     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1447
1448     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1449
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1459
1460     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1461     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1469     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1470
1471     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1479     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1483
1484     if (Subtarget->hasCDI()) {
1485       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1486       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1487     }
1488
1489     // Custom lower several nodes.
1490     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1491              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1492       MVT VT = (MVT::SimpleValueType)i;
1493
1494       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1495       // Extract subvector is special because the value type
1496       // (result) is 256/128-bit but the source is 512-bit wide.
1497       if (VT.is128BitVector() || VT.is256BitVector())
1498         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1499
1500       if (VT.getVectorElementType() == MVT::i1)
1501         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1502
1503       // Do not attempt to custom lower other non-512-bit vectors
1504       if (!VT.is512BitVector())
1505         continue;
1506
1507       if ( EltSize >= 32) {
1508         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1509         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1510         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1511         setOperationAction(ISD::VSELECT,             VT, Legal);
1512         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1513         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1514         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1515       }
1516     }
1517     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1518       MVT VT = (MVT::SimpleValueType)i;
1519
1520       // Do not attempt to promote non-256-bit vectors
1521       if (!VT.is512BitVector())
1522         continue;
1523
1524       setOperationAction(ISD::SELECT, VT, Promote);
1525       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1526     }
1527   }// has  AVX-512
1528
1529   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1530     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1531     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1532
1533     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1534     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1535
1536     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1537     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1538     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1539     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1540
1541     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1542       const MVT VT = (MVT::SimpleValueType)i;
1543
1544       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1545
1546       // Do not attempt to promote non-256-bit vectors
1547       if (!VT.is512BitVector())
1548         continue;
1549
1550       if ( EltSize < 32) {
1551         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1552         setOperationAction(ISD::VSELECT,             VT, Legal);
1553       }
1554     }
1555   }
1556
1557   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1558     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1559     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1560
1561     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1562     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1563     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Legal);
1564   }
1565
1566   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1567   // of this type with custom code.
1568   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1569            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1570     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1571                        Custom);
1572   }
1573
1574   // We want to custom lower some of our intrinsics.
1575   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1576   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1577   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1578   if (!Subtarget->is64Bit())
1579     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1580
1581   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1582   // handle type legalization for these operations here.
1583   //
1584   // FIXME: We really should do custom legalization for addition and
1585   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1586   // than generic legalization for 64-bit multiplication-with-overflow, though.
1587   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1588     // Add/Sub/Mul with overflow operations are custom lowered.
1589     MVT VT = IntVTs[i];
1590     setOperationAction(ISD::SADDO, VT, Custom);
1591     setOperationAction(ISD::UADDO, VT, Custom);
1592     setOperationAction(ISD::SSUBO, VT, Custom);
1593     setOperationAction(ISD::USUBO, VT, Custom);
1594     setOperationAction(ISD::SMULO, VT, Custom);
1595     setOperationAction(ISD::UMULO, VT, Custom);
1596   }
1597
1598
1599   if (!Subtarget->is64Bit()) {
1600     // These libcalls are not available in 32-bit.
1601     setLibcallName(RTLIB::SHL_I128, nullptr);
1602     setLibcallName(RTLIB::SRL_I128, nullptr);
1603     setLibcallName(RTLIB::SRA_I128, nullptr);
1604   }
1605
1606   // Combine sin / cos into one node or libcall if possible.
1607   if (Subtarget->hasSinCos()) {
1608     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1609     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1610     if (Subtarget->isTargetDarwin()) {
1611       // For MacOSX, we don't want to the normal expansion of a libcall to
1612       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1613       // traffic.
1614       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1615       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1616     }
1617   }
1618
1619   if (Subtarget->isTargetWin64()) {
1620     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1621     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1622     setOperationAction(ISD::SREM, MVT::i128, Custom);
1623     setOperationAction(ISD::UREM, MVT::i128, Custom);
1624     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1625     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1626   }
1627
1628   // We have target-specific dag combine patterns for the following nodes:
1629   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1630   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1631   setTargetDAGCombine(ISD::VSELECT);
1632   setTargetDAGCombine(ISD::SELECT);
1633   setTargetDAGCombine(ISD::SHL);
1634   setTargetDAGCombine(ISD::SRA);
1635   setTargetDAGCombine(ISD::SRL);
1636   setTargetDAGCombine(ISD::OR);
1637   setTargetDAGCombine(ISD::AND);
1638   setTargetDAGCombine(ISD::ADD);
1639   setTargetDAGCombine(ISD::FADD);
1640   setTargetDAGCombine(ISD::FSUB);
1641   setTargetDAGCombine(ISD::FMA);
1642   setTargetDAGCombine(ISD::SUB);
1643   setTargetDAGCombine(ISD::LOAD);
1644   setTargetDAGCombine(ISD::STORE);
1645   setTargetDAGCombine(ISD::ZERO_EXTEND);
1646   setTargetDAGCombine(ISD::ANY_EXTEND);
1647   setTargetDAGCombine(ISD::SIGN_EXTEND);
1648   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1649   setTargetDAGCombine(ISD::TRUNCATE);
1650   setTargetDAGCombine(ISD::SINT_TO_FP);
1651   setTargetDAGCombine(ISD::SETCC);
1652   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1653   setTargetDAGCombine(ISD::BUILD_VECTOR);
1654   if (Subtarget->is64Bit())
1655     setTargetDAGCombine(ISD::MUL);
1656   setTargetDAGCombine(ISD::XOR);
1657
1658   computeRegisterProperties();
1659
1660   // On Darwin, -Os means optimize for size without hurting performance,
1661   // do not reduce the limit.
1662   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1663   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1664   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1665   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1666   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1667   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1668   setPrefLoopAlignment(4); // 2^4 bytes.
1669
1670   // Predictable cmov don't hurt on atom because it's in-order.
1671   PredictableSelectIsExpensive = !Subtarget->isAtom();
1672
1673   setPrefFunctionAlignment(4); // 2^4 bytes.
1674
1675   verifyIntrinsicTables();
1676 }
1677
1678 // This has so far only been implemented for 64-bit MachO.
1679 bool X86TargetLowering::useLoadStackGuardNode() const {
1680   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1681          Subtarget->is64Bit();
1682 }
1683
1684 TargetLoweringBase::LegalizeTypeAction
1685 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1686   if (ExperimentalVectorWideningLegalization &&
1687       VT.getVectorNumElements() != 1 &&
1688       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1689     return TypeWidenVector;
1690
1691   return TargetLoweringBase::getPreferredVectorAction(VT);
1692 }
1693
1694 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1695   if (!VT.isVector())
1696     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1697
1698   const unsigned NumElts = VT.getVectorNumElements();
1699   const EVT EltVT = VT.getVectorElementType();
1700   if (VT.is512BitVector()) {
1701     if (Subtarget->hasAVX512())
1702       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1703           EltVT == MVT::f32 || EltVT == MVT::f64)
1704         switch(NumElts) {
1705         case  8: return MVT::v8i1;
1706         case 16: return MVT::v16i1;
1707       }
1708     if (Subtarget->hasBWI())
1709       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1710         switch(NumElts) {
1711         case 32: return MVT::v32i1;
1712         case 64: return MVT::v64i1;
1713       }
1714   }
1715
1716   if (VT.is256BitVector() || VT.is128BitVector()) {
1717     if (Subtarget->hasVLX())
1718       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1719           EltVT == MVT::f32 || EltVT == MVT::f64)
1720         switch(NumElts) {
1721         case 2: return MVT::v2i1;
1722         case 4: return MVT::v4i1;
1723         case 8: return MVT::v8i1;
1724       }
1725     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1726       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1727         switch(NumElts) {
1728         case  8: return MVT::v8i1;
1729         case 16: return MVT::v16i1;
1730         case 32: return MVT::v32i1;
1731       }
1732   }
1733
1734   return VT.changeVectorElementTypeToInteger();
1735 }
1736
1737 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1738 /// the desired ByVal argument alignment.
1739 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1740   if (MaxAlign == 16)
1741     return;
1742   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1743     if (VTy->getBitWidth() == 128)
1744       MaxAlign = 16;
1745   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1746     unsigned EltAlign = 0;
1747     getMaxByValAlign(ATy->getElementType(), EltAlign);
1748     if (EltAlign > MaxAlign)
1749       MaxAlign = EltAlign;
1750   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1751     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1752       unsigned EltAlign = 0;
1753       getMaxByValAlign(STy->getElementType(i), EltAlign);
1754       if (EltAlign > MaxAlign)
1755         MaxAlign = EltAlign;
1756       if (MaxAlign == 16)
1757         break;
1758     }
1759   }
1760 }
1761
1762 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1763 /// function arguments in the caller parameter area. For X86, aggregates
1764 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1765 /// are at 4-byte boundaries.
1766 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1767   if (Subtarget->is64Bit()) {
1768     // Max of 8 and alignment of type.
1769     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1770     if (TyAlign > 8)
1771       return TyAlign;
1772     return 8;
1773   }
1774
1775   unsigned Align = 4;
1776   if (Subtarget->hasSSE1())
1777     getMaxByValAlign(Ty, Align);
1778   return Align;
1779 }
1780
1781 /// getOptimalMemOpType - Returns the target specific optimal type for load
1782 /// and store operations as a result of memset, memcpy, and memmove
1783 /// lowering. If DstAlign is zero that means it's safe to destination
1784 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1785 /// means there isn't a need to check it against alignment requirement,
1786 /// probably because the source does not need to be loaded. If 'IsMemset' is
1787 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1788 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1789 /// source is constant so it does not need to be loaded.
1790 /// It returns EVT::Other if the type should be determined using generic
1791 /// target-independent logic.
1792 EVT
1793 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1794                                        unsigned DstAlign, unsigned SrcAlign,
1795                                        bool IsMemset, bool ZeroMemset,
1796                                        bool MemcpyStrSrc,
1797                                        MachineFunction &MF) const {
1798   const Function *F = MF.getFunction();
1799   if ((!IsMemset || ZeroMemset) &&
1800       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1801                                        Attribute::NoImplicitFloat)) {
1802     if (Size >= 16 &&
1803         (Subtarget->isUnalignedMemAccessFast() ||
1804          ((DstAlign == 0 || DstAlign >= 16) &&
1805           (SrcAlign == 0 || SrcAlign >= 16)))) {
1806       if (Size >= 32) {
1807         if (Subtarget->hasInt256())
1808           return MVT::v8i32;
1809         if (Subtarget->hasFp256())
1810           return MVT::v8f32;
1811       }
1812       if (Subtarget->hasSSE2())
1813         return MVT::v4i32;
1814       if (Subtarget->hasSSE1())
1815         return MVT::v4f32;
1816     } else if (!MemcpyStrSrc && Size >= 8 &&
1817                !Subtarget->is64Bit() &&
1818                Subtarget->hasSSE2()) {
1819       // Do not use f64 to lower memcpy if source is string constant. It's
1820       // better to use i32 to avoid the loads.
1821       return MVT::f64;
1822     }
1823   }
1824   if (Subtarget->is64Bit() && Size >= 8)
1825     return MVT::i64;
1826   return MVT::i32;
1827 }
1828
1829 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1830   if (VT == MVT::f32)
1831     return X86ScalarSSEf32;
1832   else if (VT == MVT::f64)
1833     return X86ScalarSSEf64;
1834   return true;
1835 }
1836
1837 bool
1838 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1839                                                   unsigned,
1840                                                   unsigned,
1841                                                   bool *Fast) const {
1842   if (Fast)
1843     *Fast = Subtarget->isUnalignedMemAccessFast();
1844   return true;
1845 }
1846
1847 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1848 /// current function.  The returned value is a member of the
1849 /// MachineJumpTableInfo::JTEntryKind enum.
1850 unsigned X86TargetLowering::getJumpTableEncoding() const {
1851   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1852   // symbol.
1853   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1854       Subtarget->isPICStyleGOT())
1855     return MachineJumpTableInfo::EK_Custom32;
1856
1857   // Otherwise, use the normal jump table encoding heuristics.
1858   return TargetLowering::getJumpTableEncoding();
1859 }
1860
1861 const MCExpr *
1862 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1863                                              const MachineBasicBlock *MBB,
1864                                              unsigned uid,MCContext &Ctx) const{
1865   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1866          Subtarget->isPICStyleGOT());
1867   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1868   // entries.
1869   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1870                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1871 }
1872
1873 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1874 /// jumptable.
1875 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1876                                                     SelectionDAG &DAG) const {
1877   if (!Subtarget->is64Bit())
1878     // This doesn't have SDLoc associated with it, but is not really the
1879     // same as a Register.
1880     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1881   return Table;
1882 }
1883
1884 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1885 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1886 /// MCExpr.
1887 const MCExpr *X86TargetLowering::
1888 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1889                              MCContext &Ctx) const {
1890   // X86-64 uses RIP relative addressing based on the jump table label.
1891   if (Subtarget->isPICStyleRIPRel())
1892     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1893
1894   // Otherwise, the reference is relative to the PIC base.
1895   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1896 }
1897
1898 // FIXME: Why this routine is here? Move to RegInfo!
1899 std::pair<const TargetRegisterClass*, uint8_t>
1900 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1901   const TargetRegisterClass *RRC = nullptr;
1902   uint8_t Cost = 1;
1903   switch (VT.SimpleTy) {
1904   default:
1905     return TargetLowering::findRepresentativeClass(VT);
1906   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1907     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1908     break;
1909   case MVT::x86mmx:
1910     RRC = &X86::VR64RegClass;
1911     break;
1912   case MVT::f32: case MVT::f64:
1913   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1914   case MVT::v4f32: case MVT::v2f64:
1915   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1916   case MVT::v4f64:
1917     RRC = &X86::VR128RegClass;
1918     break;
1919   }
1920   return std::make_pair(RRC, Cost);
1921 }
1922
1923 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1924                                                unsigned &Offset) const {
1925   if (!Subtarget->isTargetLinux())
1926     return false;
1927
1928   if (Subtarget->is64Bit()) {
1929     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1930     Offset = 0x28;
1931     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1932       AddressSpace = 256;
1933     else
1934       AddressSpace = 257;
1935   } else {
1936     // %gs:0x14 on i386
1937     Offset = 0x14;
1938     AddressSpace = 256;
1939   }
1940   return true;
1941 }
1942
1943 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1944                                             unsigned DestAS) const {
1945   assert(SrcAS != DestAS && "Expected different address spaces!");
1946
1947   return SrcAS < 256 && DestAS < 256;
1948 }
1949
1950 //===----------------------------------------------------------------------===//
1951 //               Return Value Calling Convention Implementation
1952 //===----------------------------------------------------------------------===//
1953
1954 #include "X86GenCallingConv.inc"
1955
1956 bool
1957 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1958                                   MachineFunction &MF, bool isVarArg,
1959                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1960                         LLVMContext &Context) const {
1961   SmallVector<CCValAssign, 16> RVLocs;
1962   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1963   return CCInfo.CheckReturn(Outs, RetCC_X86);
1964 }
1965
1966 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1967   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1968   return ScratchRegs;
1969 }
1970
1971 SDValue
1972 X86TargetLowering::LowerReturn(SDValue Chain,
1973                                CallingConv::ID CallConv, bool isVarArg,
1974                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1975                                const SmallVectorImpl<SDValue> &OutVals,
1976                                SDLoc dl, SelectionDAG &DAG) const {
1977   MachineFunction &MF = DAG.getMachineFunction();
1978   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1979
1980   SmallVector<CCValAssign, 16> RVLocs;
1981   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1982   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1983
1984   SDValue Flag;
1985   SmallVector<SDValue, 6> RetOps;
1986   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1987   // Operand #1 = Bytes To Pop
1988   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1989                    MVT::i16));
1990
1991   // Copy the result values into the output registers.
1992   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1993     CCValAssign &VA = RVLocs[i];
1994     assert(VA.isRegLoc() && "Can only return in registers!");
1995     SDValue ValToCopy = OutVals[i];
1996     EVT ValVT = ValToCopy.getValueType();
1997
1998     // Promote values to the appropriate types
1999     if (VA.getLocInfo() == CCValAssign::SExt)
2000       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2001     else if (VA.getLocInfo() == CCValAssign::ZExt)
2002       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2003     else if (VA.getLocInfo() == CCValAssign::AExt)
2004       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2005     else if (VA.getLocInfo() == CCValAssign::BCvt)
2006       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2007
2008     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2009            "Unexpected FP-extend for return value.");  
2010
2011     // If this is x86-64, and we disabled SSE, we can't return FP values,
2012     // or SSE or MMX vectors.
2013     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2014          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2015           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2016       report_fatal_error("SSE register return with SSE disabled");
2017     }
2018     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2019     // llvm-gcc has never done it right and no one has noticed, so this
2020     // should be OK for now.
2021     if (ValVT == MVT::f64 &&
2022         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2023       report_fatal_error("SSE2 register return with SSE2 disabled");
2024
2025     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2026     // the RET instruction and handled by the FP Stackifier.
2027     if (VA.getLocReg() == X86::FP0 ||
2028         VA.getLocReg() == X86::FP1) {
2029       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2030       // change the value to the FP stack register class.
2031       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2032         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2033       RetOps.push_back(ValToCopy);
2034       // Don't emit a copytoreg.
2035       continue;
2036     }
2037
2038     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2039     // which is returned in RAX / RDX.
2040     if (Subtarget->is64Bit()) {
2041       if (ValVT == MVT::x86mmx) {
2042         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2043           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2044           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2045                                   ValToCopy);
2046           // If we don't have SSE2 available, convert to v4f32 so the generated
2047           // register is legal.
2048           if (!Subtarget->hasSSE2())
2049             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2050         }
2051       }
2052     }
2053
2054     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2055     Flag = Chain.getValue(1);
2056     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2057   }
2058
2059   // The x86-64 ABIs require that for returning structs by value we copy
2060   // the sret argument into %rax/%eax (depending on ABI) for the return.
2061   // Win32 requires us to put the sret argument to %eax as well.
2062   // We saved the argument into a virtual register in the entry block,
2063   // so now we copy the value out and into %rax/%eax.
2064   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2065       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2066     MachineFunction &MF = DAG.getMachineFunction();
2067     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2068     unsigned Reg = FuncInfo->getSRetReturnReg();
2069     assert(Reg &&
2070            "SRetReturnReg should have been set in LowerFormalArguments().");
2071     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2072
2073     unsigned RetValReg
2074         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2075           X86::RAX : X86::EAX;
2076     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2077     Flag = Chain.getValue(1);
2078
2079     // RAX/EAX now acts like a return value.
2080     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2081   }
2082
2083   RetOps[0] = Chain;  // Update chain.
2084
2085   // Add the flag if we have it.
2086   if (Flag.getNode())
2087     RetOps.push_back(Flag);
2088
2089   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2090 }
2091
2092 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2093   if (N->getNumValues() != 1)
2094     return false;
2095   if (!N->hasNUsesOfValue(1, 0))
2096     return false;
2097
2098   SDValue TCChain = Chain;
2099   SDNode *Copy = *N->use_begin();
2100   if (Copy->getOpcode() == ISD::CopyToReg) {
2101     // If the copy has a glue operand, we conservatively assume it isn't safe to
2102     // perform a tail call.
2103     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2104       return false;
2105     TCChain = Copy->getOperand(0);
2106   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2107     return false;
2108
2109   bool HasRet = false;
2110   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2111        UI != UE; ++UI) {
2112     if (UI->getOpcode() != X86ISD::RET_FLAG)
2113       return false;
2114     // If we are returning more than one value, we can definitely
2115     // not make a tail call see PR19530
2116     if (UI->getNumOperands() > 4)
2117       return false;
2118     if (UI->getNumOperands() == 4 &&
2119         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2120       return false;
2121     HasRet = true;
2122   }
2123
2124   if (!HasRet)
2125     return false;
2126
2127   Chain = TCChain;
2128   return true;
2129 }
2130
2131 EVT
2132 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2133                                             ISD::NodeType ExtendKind) const {
2134   MVT ReturnMVT;
2135   // TODO: Is this also valid on 32-bit?
2136   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2137     ReturnMVT = MVT::i8;
2138   else
2139     ReturnMVT = MVT::i32;
2140
2141   EVT MinVT = getRegisterType(Context, ReturnMVT);
2142   return VT.bitsLT(MinVT) ? MinVT : VT;
2143 }
2144
2145 /// LowerCallResult - Lower the result values of a call into the
2146 /// appropriate copies out of appropriate physical registers.
2147 ///
2148 SDValue
2149 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2150                                    CallingConv::ID CallConv, bool isVarArg,
2151                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2152                                    SDLoc dl, SelectionDAG &DAG,
2153                                    SmallVectorImpl<SDValue> &InVals) const {
2154
2155   // Assign locations to each value returned by this call.
2156   SmallVector<CCValAssign, 16> RVLocs;
2157   bool Is64Bit = Subtarget->is64Bit();
2158   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2159                  *DAG.getContext());
2160   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2161
2162   // Copy all of the result registers out of their specified physreg.
2163   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2164     CCValAssign &VA = RVLocs[i];
2165     EVT CopyVT = VA.getValVT();
2166
2167     // If this is x86-64, and we disabled SSE, we can't return FP values
2168     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2169         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2170       report_fatal_error("SSE register return with SSE disabled");
2171     }
2172
2173     // If we prefer to use the value in xmm registers, copy it out as f80 and
2174     // use a truncate to move it from fp stack reg to xmm reg.
2175     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2176         isScalarFPTypeInSSEReg(VA.getValVT()))
2177       CopyVT = MVT::f80;
2178
2179     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2180                                CopyVT, InFlag).getValue(1);
2181     SDValue Val = Chain.getValue(0);
2182
2183     if (CopyVT != VA.getValVT())
2184       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2185                         // This truncation won't change the value.
2186                         DAG.getIntPtrConstant(1));
2187
2188     InFlag = Chain.getValue(2);
2189     InVals.push_back(Val);
2190   }
2191
2192   return Chain;
2193 }
2194
2195 //===----------------------------------------------------------------------===//
2196 //                C & StdCall & Fast Calling Convention implementation
2197 //===----------------------------------------------------------------------===//
2198 //  StdCall calling convention seems to be standard for many Windows' API
2199 //  routines and around. It differs from C calling convention just a little:
2200 //  callee should clean up the stack, not caller. Symbols should be also
2201 //  decorated in some fancy way :) It doesn't support any vector arguments.
2202 //  For info on fast calling convention see Fast Calling Convention (tail call)
2203 //  implementation LowerX86_32FastCCCallTo.
2204
2205 /// CallIsStructReturn - Determines whether a call uses struct return
2206 /// semantics.
2207 enum StructReturnType {
2208   NotStructReturn,
2209   RegStructReturn,
2210   StackStructReturn
2211 };
2212 static StructReturnType
2213 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2214   if (Outs.empty())
2215     return NotStructReturn;
2216
2217   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2218   if (!Flags.isSRet())
2219     return NotStructReturn;
2220   if (Flags.isInReg())
2221     return RegStructReturn;
2222   return StackStructReturn;
2223 }
2224
2225 /// ArgsAreStructReturn - Determines whether a function uses struct
2226 /// return semantics.
2227 static StructReturnType
2228 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2229   if (Ins.empty())
2230     return NotStructReturn;
2231
2232   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2233   if (!Flags.isSRet())
2234     return NotStructReturn;
2235   if (Flags.isInReg())
2236     return RegStructReturn;
2237   return StackStructReturn;
2238 }
2239
2240 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2241 /// by "Src" to address "Dst" with size and alignment information specified by
2242 /// the specific parameter attribute. The copy will be passed as a byval
2243 /// function parameter.
2244 static SDValue
2245 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2246                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2247                           SDLoc dl) {
2248   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2249
2250   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2251                        /*isVolatile*/false, /*AlwaysInline=*/true,
2252                        MachinePointerInfo(), MachinePointerInfo());
2253 }
2254
2255 /// IsTailCallConvention - Return true if the calling convention is one that
2256 /// supports tail call optimization.
2257 static bool IsTailCallConvention(CallingConv::ID CC) {
2258   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2259           CC == CallingConv::HiPE);
2260 }
2261
2262 /// \brief Return true if the calling convention is a C calling convention.
2263 static bool IsCCallConvention(CallingConv::ID CC) {
2264   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2265           CC == CallingConv::X86_64_SysV);
2266 }
2267
2268 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2269   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2270     return false;
2271
2272   CallSite CS(CI);
2273   CallingConv::ID CalleeCC = CS.getCallingConv();
2274   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2275     return false;
2276
2277   return true;
2278 }
2279
2280 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2281 /// a tailcall target by changing its ABI.
2282 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2283                                    bool GuaranteedTailCallOpt) {
2284   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2285 }
2286
2287 SDValue
2288 X86TargetLowering::LowerMemArgument(SDValue Chain,
2289                                     CallingConv::ID CallConv,
2290                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2291                                     SDLoc dl, SelectionDAG &DAG,
2292                                     const CCValAssign &VA,
2293                                     MachineFrameInfo *MFI,
2294                                     unsigned i) const {
2295   // Create the nodes corresponding to a load from this parameter slot.
2296   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2297   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2298       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2299   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2300   EVT ValVT;
2301
2302   // If value is passed by pointer we have address passed instead of the value
2303   // itself.
2304   if (VA.getLocInfo() == CCValAssign::Indirect)
2305     ValVT = VA.getLocVT();
2306   else
2307     ValVT = VA.getValVT();
2308
2309   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2310   // changed with more analysis.
2311   // In case of tail call optimization mark all arguments mutable. Since they
2312   // could be overwritten by lowering of arguments in case of a tail call.
2313   if (Flags.isByVal()) {
2314     unsigned Bytes = Flags.getByValSize();
2315     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2316     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2317     return DAG.getFrameIndex(FI, getPointerTy());
2318   } else {
2319     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2320                                     VA.getLocMemOffset(), isImmutable);
2321     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2322     return DAG.getLoad(ValVT, dl, Chain, FIN,
2323                        MachinePointerInfo::getFixedStack(FI),
2324                        false, false, false, 0);
2325   }
2326 }
2327
2328 // FIXME: Get this from tablegen.
2329 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2330                                                 const X86Subtarget *Subtarget) {
2331   assert(Subtarget->is64Bit());
2332
2333   if (Subtarget->isCallingConvWin64(CallConv)) {
2334     static const MCPhysReg GPR64ArgRegsWin64[] = {
2335       X86::RCX, X86::RDX, X86::R8,  X86::R9
2336     };
2337     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2338   }
2339
2340   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2341     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2342   };
2343   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2344 }
2345
2346 // FIXME: Get this from tablegen.
2347 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2348                                                 CallingConv::ID CallConv,
2349                                                 const X86Subtarget *Subtarget) {
2350   assert(Subtarget->is64Bit());
2351   if (Subtarget->isCallingConvWin64(CallConv)) {
2352     // The XMM registers which might contain var arg parameters are shadowed
2353     // in their paired GPR.  So we only need to save the GPR to their home
2354     // slots.
2355     // TODO: __vectorcall will change this.
2356     return None;
2357   }
2358
2359   const Function *Fn = MF.getFunction();
2360   bool NoImplicitFloatOps = Fn->getAttributes().
2361       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2362   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2363          "SSE register cannot be used when SSE is disabled!");
2364   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2365       !Subtarget->hasSSE1())
2366     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2367     // registers.
2368     return None;
2369
2370   static const MCPhysReg XMMArgRegs64Bit[] = {
2371     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2372     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2373   };
2374   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2375 }
2376
2377 SDValue
2378 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2379                                         CallingConv::ID CallConv,
2380                                         bool isVarArg,
2381                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2382                                         SDLoc dl,
2383                                         SelectionDAG &DAG,
2384                                         SmallVectorImpl<SDValue> &InVals)
2385                                           const {
2386   MachineFunction &MF = DAG.getMachineFunction();
2387   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2388
2389   const Function* Fn = MF.getFunction();
2390   if (Fn->hasExternalLinkage() &&
2391       Subtarget->isTargetCygMing() &&
2392       Fn->getName() == "main")
2393     FuncInfo->setForceFramePointer(true);
2394
2395   MachineFrameInfo *MFI = MF.getFrameInfo();
2396   bool Is64Bit = Subtarget->is64Bit();
2397   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2398
2399   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2400          "Var args not supported with calling convention fastcc, ghc or hipe");
2401
2402   // Assign locations to all of the incoming arguments.
2403   SmallVector<CCValAssign, 16> ArgLocs;
2404   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2405
2406   // Allocate shadow area for Win64
2407   if (IsWin64)
2408     CCInfo.AllocateStack(32, 8);
2409
2410   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2411
2412   unsigned LastVal = ~0U;
2413   SDValue ArgValue;
2414   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2415     CCValAssign &VA = ArgLocs[i];
2416     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2417     // places.
2418     assert(VA.getValNo() != LastVal &&
2419            "Don't support value assigned to multiple locs yet");
2420     (void)LastVal;
2421     LastVal = VA.getValNo();
2422
2423     if (VA.isRegLoc()) {
2424       EVT RegVT = VA.getLocVT();
2425       const TargetRegisterClass *RC;
2426       if (RegVT == MVT::i32)
2427         RC = &X86::GR32RegClass;
2428       else if (Is64Bit && RegVT == MVT::i64)
2429         RC = &X86::GR64RegClass;
2430       else if (RegVT == MVT::f32)
2431         RC = &X86::FR32RegClass;
2432       else if (RegVT == MVT::f64)
2433         RC = &X86::FR64RegClass;
2434       else if (RegVT.is512BitVector())
2435         RC = &X86::VR512RegClass;
2436       else if (RegVT.is256BitVector())
2437         RC = &X86::VR256RegClass;
2438       else if (RegVT.is128BitVector())
2439         RC = &X86::VR128RegClass;
2440       else if (RegVT == MVT::x86mmx)
2441         RC = &X86::VR64RegClass;
2442       else if (RegVT == MVT::i1)
2443         RC = &X86::VK1RegClass;
2444       else if (RegVT == MVT::v8i1)
2445         RC = &X86::VK8RegClass;
2446       else if (RegVT == MVT::v16i1)
2447         RC = &X86::VK16RegClass;
2448       else if (RegVT == MVT::v32i1)
2449         RC = &X86::VK32RegClass;
2450       else if (RegVT == MVT::v64i1)
2451         RC = &X86::VK64RegClass;
2452       else
2453         llvm_unreachable("Unknown argument type!");
2454
2455       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2456       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2457
2458       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2459       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2460       // right size.
2461       if (VA.getLocInfo() == CCValAssign::SExt)
2462         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2463                                DAG.getValueType(VA.getValVT()));
2464       else if (VA.getLocInfo() == CCValAssign::ZExt)
2465         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2466                                DAG.getValueType(VA.getValVT()));
2467       else if (VA.getLocInfo() == CCValAssign::BCvt)
2468         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2469
2470       if (VA.isExtInLoc()) {
2471         // Handle MMX values passed in XMM regs.
2472         if (RegVT.isVector())
2473           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2474         else
2475           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2476       }
2477     } else {
2478       assert(VA.isMemLoc());
2479       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2480     }
2481
2482     // If value is passed via pointer - do a load.
2483     if (VA.getLocInfo() == CCValAssign::Indirect)
2484       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2485                              MachinePointerInfo(), false, false, false, 0);
2486
2487     InVals.push_back(ArgValue);
2488   }
2489
2490   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2491     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2492       // The x86-64 ABIs require that for returning structs by value we copy
2493       // the sret argument into %rax/%eax (depending on ABI) for the return.
2494       // Win32 requires us to put the sret argument to %eax as well.
2495       // Save the argument into a virtual register so that we can access it
2496       // from the return points.
2497       if (Ins[i].Flags.isSRet()) {
2498         unsigned Reg = FuncInfo->getSRetReturnReg();
2499         if (!Reg) {
2500           MVT PtrTy = getPointerTy();
2501           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2502           FuncInfo->setSRetReturnReg(Reg);
2503         }
2504         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2505         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2506         break;
2507       }
2508     }
2509   }
2510
2511   unsigned StackSize = CCInfo.getNextStackOffset();
2512   // Align stack specially for tail calls.
2513   if (FuncIsMadeTailCallSafe(CallConv,
2514                              MF.getTarget().Options.GuaranteedTailCallOpt))
2515     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2516
2517   // If the function takes variable number of arguments, make a frame index for
2518   // the start of the first vararg value... for expansion of llvm.va_start. We
2519   // can skip this if there are no va_start calls.
2520   if (MFI->hasVAStart() &&
2521       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2522                    CallConv != CallingConv::X86_ThisCall))) {
2523     FuncInfo->setVarArgsFrameIndex(
2524         MFI->CreateFixedObject(1, StackSize, true));
2525   }
2526
2527   // 64-bit calling conventions support varargs and register parameters, so we
2528   // have to do extra work to spill them in the prologue or forward them to
2529   // musttail calls.
2530   if (Is64Bit && isVarArg &&
2531       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2532     // Find the first unallocated argument registers.
2533     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2534     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2535     unsigned NumIntRegs =
2536         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2537     unsigned NumXMMRegs =
2538         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2539     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2540            "SSE register cannot be used when SSE is disabled!");
2541
2542     // Gather all the live in physical registers.
2543     SmallVector<SDValue, 6> LiveGPRs;
2544     SmallVector<SDValue, 8> LiveXMMRegs;
2545     SDValue ALVal;
2546     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2547       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2548       LiveGPRs.push_back(
2549           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2550     }
2551     if (!ArgXMMs.empty()) {
2552       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2553       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2554       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2555         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2556         LiveXMMRegs.push_back(
2557             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2558       }
2559     }
2560
2561     // Store them to the va_list returned by va_start.
2562     if (MFI->hasVAStart()) {
2563       if (IsWin64) {
2564         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2565         // Get to the caller-allocated home save location.  Add 8 to account
2566         // for the return address.
2567         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2568         FuncInfo->setRegSaveFrameIndex(
2569           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2570         // Fixup to set vararg frame on shadow area (4 x i64).
2571         if (NumIntRegs < 4)
2572           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2573       } else {
2574         // For X86-64, if there are vararg parameters that are passed via
2575         // registers, then we must store them to their spots on the stack so
2576         // they may be loaded by deferencing the result of va_next.
2577         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2578         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2579         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2580             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2581       }
2582
2583       // Store the integer parameter registers.
2584       SmallVector<SDValue, 8> MemOps;
2585       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2586                                         getPointerTy());
2587       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2588       for (SDValue Val : LiveGPRs) {
2589         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2590                                   DAG.getIntPtrConstant(Offset));
2591         SDValue Store =
2592           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2593                        MachinePointerInfo::getFixedStack(
2594                          FuncInfo->getRegSaveFrameIndex(), Offset),
2595                        false, false, 0);
2596         MemOps.push_back(Store);
2597         Offset += 8;
2598       }
2599
2600       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2601         // Now store the XMM (fp + vector) parameter registers.
2602         SmallVector<SDValue, 12> SaveXMMOps;
2603         SaveXMMOps.push_back(Chain);
2604         SaveXMMOps.push_back(ALVal);
2605         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2606                                FuncInfo->getRegSaveFrameIndex()));
2607         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2608                                FuncInfo->getVarArgsFPOffset()));
2609         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2610                           LiveXMMRegs.end());
2611         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2612                                      MVT::Other, SaveXMMOps));
2613       }
2614
2615       if (!MemOps.empty())
2616         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2617     } else {
2618       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2619       // to the liveout set on a musttail call.
2620       assert(MFI->hasMustTailInVarArgFunc());
2621       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2622       typedef X86MachineFunctionInfo::Forward Forward;
2623
2624       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2625         unsigned VReg =
2626             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2627         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2628         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2629       }
2630
2631       if (!ArgXMMs.empty()) {
2632         unsigned ALVReg =
2633             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2634         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2635         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2636
2637         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2638           unsigned VReg =
2639               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2640           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2641           Forwards.push_back(
2642               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2643         }
2644       }
2645     }
2646   }
2647
2648   // Some CCs need callee pop.
2649   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2650                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2651     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2652   } else {
2653     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2654     // If this is an sret function, the return should pop the hidden pointer.
2655     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2656         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2657         argsAreStructReturn(Ins) == StackStructReturn)
2658       FuncInfo->setBytesToPopOnReturn(4);
2659   }
2660
2661   if (!Is64Bit) {
2662     // RegSaveFrameIndex is X86-64 only.
2663     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2664     if (CallConv == CallingConv::X86_FastCall ||
2665         CallConv == CallingConv::X86_ThisCall)
2666       // fastcc functions can't have varargs.
2667       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2668   }
2669
2670   FuncInfo->setArgumentStackSize(StackSize);
2671
2672   return Chain;
2673 }
2674
2675 SDValue
2676 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2677                                     SDValue StackPtr, SDValue Arg,
2678                                     SDLoc dl, SelectionDAG &DAG,
2679                                     const CCValAssign &VA,
2680                                     ISD::ArgFlagsTy Flags) const {
2681   unsigned LocMemOffset = VA.getLocMemOffset();
2682   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2683   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2684   if (Flags.isByVal())
2685     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2686
2687   return DAG.getStore(Chain, dl, Arg, PtrOff,
2688                       MachinePointerInfo::getStack(LocMemOffset),
2689                       false, false, 0);
2690 }
2691
2692 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2693 /// optimization is performed and it is required.
2694 SDValue
2695 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2696                                            SDValue &OutRetAddr, SDValue Chain,
2697                                            bool IsTailCall, bool Is64Bit,
2698                                            int FPDiff, SDLoc dl) const {
2699   // Adjust the Return address stack slot.
2700   EVT VT = getPointerTy();
2701   OutRetAddr = getReturnAddressFrameIndex(DAG);
2702
2703   // Load the "old" Return address.
2704   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2705                            false, false, false, 0);
2706   return SDValue(OutRetAddr.getNode(), 1);
2707 }
2708
2709 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2710 /// optimization is performed and it is required (FPDiff!=0).
2711 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2712                                         SDValue Chain, SDValue RetAddrFrIdx,
2713                                         EVT PtrVT, unsigned SlotSize,
2714                                         int FPDiff, SDLoc dl) {
2715   // Store the return address to the appropriate stack slot.
2716   if (!FPDiff) return Chain;
2717   // Calculate the new stack slot for the return address.
2718   int NewReturnAddrFI =
2719     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2720                                          false);
2721   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2722   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2723                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2724                        false, false, 0);
2725   return Chain;
2726 }
2727
2728 SDValue
2729 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2730                              SmallVectorImpl<SDValue> &InVals) const {
2731   SelectionDAG &DAG                     = CLI.DAG;
2732   SDLoc &dl                             = CLI.DL;
2733   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2734   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2735   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2736   SDValue Chain                         = CLI.Chain;
2737   SDValue Callee                        = CLI.Callee;
2738   CallingConv::ID CallConv              = CLI.CallConv;
2739   bool &isTailCall                      = CLI.IsTailCall;
2740   bool isVarArg                         = CLI.IsVarArg;
2741
2742   MachineFunction &MF = DAG.getMachineFunction();
2743   bool Is64Bit        = Subtarget->is64Bit();
2744   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2745   StructReturnType SR = callIsStructReturn(Outs);
2746   bool IsSibcall      = false;
2747   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2748
2749   if (MF.getTarget().Options.DisableTailCalls)
2750     isTailCall = false;
2751
2752   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2753   if (IsMustTail) {
2754     // Force this to be a tail call.  The verifier rules are enough to ensure
2755     // that we can lower this successfully without moving the return address
2756     // around.
2757     isTailCall = true;
2758   } else if (isTailCall) {
2759     // Check if it's really possible to do a tail call.
2760     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2761                     isVarArg, SR != NotStructReturn,
2762                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2763                     Outs, OutVals, Ins, DAG);
2764
2765     // Sibcalls are automatically detected tailcalls which do not require
2766     // ABI changes.
2767     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2768       IsSibcall = true;
2769
2770     if (isTailCall)
2771       ++NumTailCalls;
2772   }
2773
2774   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2775          "Var args not supported with calling convention fastcc, ghc or hipe");
2776
2777   // Analyze operands of the call, assigning locations to each operand.
2778   SmallVector<CCValAssign, 16> ArgLocs;
2779   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2780
2781   // Allocate shadow area for Win64
2782   if (IsWin64)
2783     CCInfo.AllocateStack(32, 8);
2784
2785   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2786
2787   // Get a count of how many bytes are to be pushed on the stack.
2788   unsigned NumBytes = CCInfo.getNextStackOffset();
2789   if (IsSibcall)
2790     // This is a sibcall. The memory operands are available in caller's
2791     // own caller's stack.
2792     NumBytes = 0;
2793   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2794            IsTailCallConvention(CallConv))
2795     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2796
2797   int FPDiff = 0;
2798   if (isTailCall && !IsSibcall && !IsMustTail) {
2799     // Lower arguments at fp - stackoffset + fpdiff.
2800     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2801
2802     FPDiff = NumBytesCallerPushed - NumBytes;
2803
2804     // Set the delta of movement of the returnaddr stackslot.
2805     // But only set if delta is greater than previous delta.
2806     if (FPDiff < X86Info->getTCReturnAddrDelta())
2807       X86Info->setTCReturnAddrDelta(FPDiff);
2808   }
2809
2810   unsigned NumBytesToPush = NumBytes;
2811   unsigned NumBytesToPop = NumBytes;
2812
2813   // If we have an inalloca argument, all stack space has already been allocated
2814   // for us and be right at the top of the stack.  We don't support multiple
2815   // arguments passed in memory when using inalloca.
2816   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2817     NumBytesToPush = 0;
2818     if (!ArgLocs.back().isMemLoc())
2819       report_fatal_error("cannot use inalloca attribute on a register "
2820                          "parameter");
2821     if (ArgLocs.back().getLocMemOffset() != 0)
2822       report_fatal_error("any parameter with the inalloca attribute must be "
2823                          "the only memory argument");
2824   }
2825
2826   if (!IsSibcall)
2827     Chain = DAG.getCALLSEQ_START(
2828         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2829
2830   SDValue RetAddrFrIdx;
2831   // Load return address for tail calls.
2832   if (isTailCall && FPDiff)
2833     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2834                                     Is64Bit, FPDiff, dl);
2835
2836   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2837   SmallVector<SDValue, 8> MemOpChains;
2838   SDValue StackPtr;
2839
2840   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2841   // of tail call optimization arguments are handle later.
2842   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2843       DAG.getSubtarget().getRegisterInfo());
2844   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2845     // Skip inalloca arguments, they have already been written.
2846     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2847     if (Flags.isInAlloca())
2848       continue;
2849
2850     CCValAssign &VA = ArgLocs[i];
2851     EVT RegVT = VA.getLocVT();
2852     SDValue Arg = OutVals[i];
2853     bool isByVal = Flags.isByVal();
2854
2855     // Promote the value if needed.
2856     switch (VA.getLocInfo()) {
2857     default: llvm_unreachable("Unknown loc info!");
2858     case CCValAssign::Full: break;
2859     case CCValAssign::SExt:
2860       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2861       break;
2862     case CCValAssign::ZExt:
2863       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2864       break;
2865     case CCValAssign::AExt:
2866       if (RegVT.is128BitVector()) {
2867         // Special case: passing MMX values in XMM registers.
2868         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2869         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2870         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2871       } else
2872         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2873       break;
2874     case CCValAssign::BCvt:
2875       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2876       break;
2877     case CCValAssign::Indirect: {
2878       // Store the argument.
2879       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2880       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2881       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2882                            MachinePointerInfo::getFixedStack(FI),
2883                            false, false, 0);
2884       Arg = SpillSlot;
2885       break;
2886     }
2887     }
2888
2889     if (VA.isRegLoc()) {
2890       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2891       if (isVarArg && IsWin64) {
2892         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2893         // shadow reg if callee is a varargs function.
2894         unsigned ShadowReg = 0;
2895         switch (VA.getLocReg()) {
2896         case X86::XMM0: ShadowReg = X86::RCX; break;
2897         case X86::XMM1: ShadowReg = X86::RDX; break;
2898         case X86::XMM2: ShadowReg = X86::R8; break;
2899         case X86::XMM3: ShadowReg = X86::R9; break;
2900         }
2901         if (ShadowReg)
2902           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2903       }
2904     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2905       assert(VA.isMemLoc());
2906       if (!StackPtr.getNode())
2907         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2908                                       getPointerTy());
2909       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2910                                              dl, DAG, VA, Flags));
2911     }
2912   }
2913
2914   if (!MemOpChains.empty())
2915     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2916
2917   if (Subtarget->isPICStyleGOT()) {
2918     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2919     // GOT pointer.
2920     if (!isTailCall) {
2921       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2922                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2923     } else {
2924       // If we are tail calling and generating PIC/GOT style code load the
2925       // address of the callee into ECX. The value in ecx is used as target of
2926       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2927       // for tail calls on PIC/GOT architectures. Normally we would just put the
2928       // address of GOT into ebx and then call target@PLT. But for tail calls
2929       // ebx would be restored (since ebx is callee saved) before jumping to the
2930       // target@PLT.
2931
2932       // Note: The actual moving to ECX is done further down.
2933       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2934       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2935           !G->getGlobal()->hasProtectedVisibility())
2936         Callee = LowerGlobalAddress(Callee, DAG);
2937       else if (isa<ExternalSymbolSDNode>(Callee))
2938         Callee = LowerExternalSymbol(Callee, DAG);
2939     }
2940   }
2941
2942   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2943     // From AMD64 ABI document:
2944     // For calls that may call functions that use varargs or stdargs
2945     // (prototype-less calls or calls to functions containing ellipsis (...) in
2946     // the declaration) %al is used as hidden argument to specify the number
2947     // of SSE registers used. The contents of %al do not need to match exactly
2948     // the number of registers, but must be an ubound on the number of SSE
2949     // registers used and is in the range 0 - 8 inclusive.
2950
2951     // Count the number of XMM registers allocated.
2952     static const MCPhysReg XMMArgRegs[] = {
2953       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2954       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2955     };
2956     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2957     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2958            && "SSE registers cannot be used when SSE is disabled");
2959
2960     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2961                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2962   }
2963
2964   if (Is64Bit && isVarArg && IsMustTail) {
2965     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2966     for (const auto &F : Forwards) {
2967       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2968       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2969     }
2970   }
2971
2972   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2973   // don't need this because the eligibility check rejects calls that require
2974   // shuffling arguments passed in memory.
2975   if (!IsSibcall && isTailCall) {
2976     // Force all the incoming stack arguments to be loaded from the stack
2977     // before any new outgoing arguments are stored to the stack, because the
2978     // outgoing stack slots may alias the incoming argument stack slots, and
2979     // the alias isn't otherwise explicit. This is slightly more conservative
2980     // than necessary, because it means that each store effectively depends
2981     // on every argument instead of just those arguments it would clobber.
2982     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2983
2984     SmallVector<SDValue, 8> MemOpChains2;
2985     SDValue FIN;
2986     int FI = 0;
2987     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2988       CCValAssign &VA = ArgLocs[i];
2989       if (VA.isRegLoc())
2990         continue;
2991       assert(VA.isMemLoc());
2992       SDValue Arg = OutVals[i];
2993       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2994       // Skip inalloca arguments.  They don't require any work.
2995       if (Flags.isInAlloca())
2996         continue;
2997       // Create frame index.
2998       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2999       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3000       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3001       FIN = DAG.getFrameIndex(FI, getPointerTy());
3002
3003       if (Flags.isByVal()) {
3004         // Copy relative to framepointer.
3005         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3006         if (!StackPtr.getNode())
3007           StackPtr = DAG.getCopyFromReg(Chain, dl,
3008                                         RegInfo->getStackRegister(),
3009                                         getPointerTy());
3010         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3011
3012         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3013                                                          ArgChain,
3014                                                          Flags, DAG, dl));
3015       } else {
3016         // Store relative to framepointer.
3017         MemOpChains2.push_back(
3018           DAG.getStore(ArgChain, dl, Arg, FIN,
3019                        MachinePointerInfo::getFixedStack(FI),
3020                        false, false, 0));
3021       }
3022     }
3023
3024     if (!MemOpChains2.empty())
3025       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3026
3027     // Store the return address to the appropriate stack slot.
3028     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3029                                      getPointerTy(), RegInfo->getSlotSize(),
3030                                      FPDiff, dl);
3031   }
3032
3033   // Build a sequence of copy-to-reg nodes chained together with token chain
3034   // and flag operands which copy the outgoing args into registers.
3035   SDValue InFlag;
3036   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3037     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3038                              RegsToPass[i].second, InFlag);
3039     InFlag = Chain.getValue(1);
3040   }
3041
3042   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3043     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3044     // In the 64-bit large code model, we have to make all calls
3045     // through a register, since the call instruction's 32-bit
3046     // pc-relative offset may not be large enough to hold the whole
3047     // address.
3048   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3049     // If the callee is a GlobalAddress node (quite common, every direct call
3050     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3051     // it.
3052
3053     // We should use extra load for direct calls to dllimported functions in
3054     // non-JIT mode.
3055     const GlobalValue *GV = G->getGlobal();
3056     if (!GV->hasDLLImportStorageClass()) {
3057       unsigned char OpFlags = 0;
3058       bool ExtraLoad = false;
3059       unsigned WrapperKind = ISD::DELETED_NODE;
3060
3061       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3062       // external symbols most go through the PLT in PIC mode.  If the symbol
3063       // has hidden or protected visibility, or if it is static or local, then
3064       // we don't need to use the PLT - we can directly call it.
3065       if (Subtarget->isTargetELF() &&
3066           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3067           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3068         OpFlags = X86II::MO_PLT;
3069       } else if (Subtarget->isPICStyleStubAny() &&
3070                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3071                  (!Subtarget->getTargetTriple().isMacOSX() ||
3072                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3073         // PC-relative references to external symbols should go through $stub,
3074         // unless we're building with the leopard linker or later, which
3075         // automatically synthesizes these stubs.
3076         OpFlags = X86II::MO_DARWIN_STUB;
3077       } else if (Subtarget->isPICStyleRIPRel() &&
3078                  isa<Function>(GV) &&
3079                  cast<Function>(GV)->getAttributes().
3080                    hasAttribute(AttributeSet::FunctionIndex,
3081                                 Attribute::NonLazyBind)) {
3082         // If the function is marked as non-lazy, generate an indirect call
3083         // which loads from the GOT directly. This avoids runtime overhead
3084         // at the cost of eager binding (and one extra byte of encoding).
3085         OpFlags = X86II::MO_GOTPCREL;
3086         WrapperKind = X86ISD::WrapperRIP;
3087         ExtraLoad = true;
3088       }
3089
3090       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3091                                           G->getOffset(), OpFlags);
3092
3093       // Add a wrapper if needed.
3094       if (WrapperKind != ISD::DELETED_NODE)
3095         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3096       // Add extra indirection if needed.
3097       if (ExtraLoad)
3098         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3099                              MachinePointerInfo::getGOT(),
3100                              false, false, false, 0);
3101     }
3102   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3103     unsigned char OpFlags = 0;
3104
3105     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3106     // external symbols should go through the PLT.
3107     if (Subtarget->isTargetELF() &&
3108         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3109       OpFlags = X86II::MO_PLT;
3110     } else if (Subtarget->isPICStyleStubAny() &&
3111                (!Subtarget->getTargetTriple().isMacOSX() ||
3112                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3113       // PC-relative references to external symbols should go through $stub,
3114       // unless we're building with the leopard linker or later, which
3115       // automatically synthesizes these stubs.
3116       OpFlags = X86II::MO_DARWIN_STUB;
3117     }
3118
3119     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3120                                          OpFlags);
3121   } else if (Subtarget->isTarget64BitILP32() && Callee->getValueType(0) == MVT::i32) {
3122     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3123     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3124   }
3125
3126   // Returns a chain & a flag for retval copy to use.
3127   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3128   SmallVector<SDValue, 8> Ops;
3129
3130   if (!IsSibcall && isTailCall) {
3131     Chain = DAG.getCALLSEQ_END(Chain,
3132                                DAG.getIntPtrConstant(NumBytesToPop, true),
3133                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3134     InFlag = Chain.getValue(1);
3135   }
3136
3137   Ops.push_back(Chain);
3138   Ops.push_back(Callee);
3139
3140   if (isTailCall)
3141     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3142
3143   // Add argument registers to the end of the list so that they are known live
3144   // into the call.
3145   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3146     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3147                                   RegsToPass[i].second.getValueType()));
3148
3149   // Add a register mask operand representing the call-preserved registers.
3150   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3151   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3152   assert(Mask && "Missing call preserved mask for calling convention");
3153   Ops.push_back(DAG.getRegisterMask(Mask));
3154
3155   if (InFlag.getNode())
3156     Ops.push_back(InFlag);
3157
3158   if (isTailCall) {
3159     // We used to do:
3160     //// If this is the first return lowered for this function, add the regs
3161     //// to the liveout set for the function.
3162     // This isn't right, although it's probably harmless on x86; liveouts
3163     // should be computed from returns not tail calls.  Consider a void
3164     // function making a tail call to a function returning int.
3165     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3166   }
3167
3168   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3169   InFlag = Chain.getValue(1);
3170
3171   // Create the CALLSEQ_END node.
3172   unsigned NumBytesForCalleeToPop;
3173   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3174                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3175     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3176   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3177            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3178            SR == StackStructReturn)
3179     // If this is a call to a struct-return function, the callee
3180     // pops the hidden struct pointer, so we have to push it back.
3181     // This is common for Darwin/X86, Linux & Mingw32 targets.
3182     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3183     NumBytesForCalleeToPop = 4;
3184   else
3185     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3186
3187   // Returns a flag for retval copy to use.
3188   if (!IsSibcall) {
3189     Chain = DAG.getCALLSEQ_END(Chain,
3190                                DAG.getIntPtrConstant(NumBytesToPop, true),
3191                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3192                                                      true),
3193                                InFlag, dl);
3194     InFlag = Chain.getValue(1);
3195   }
3196
3197   // Handle result values, copying them out of physregs into vregs that we
3198   // return.
3199   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3200                          Ins, dl, DAG, InVals);
3201 }
3202
3203 //===----------------------------------------------------------------------===//
3204 //                Fast Calling Convention (tail call) implementation
3205 //===----------------------------------------------------------------------===//
3206
3207 //  Like std call, callee cleans arguments, convention except that ECX is
3208 //  reserved for storing the tail called function address. Only 2 registers are
3209 //  free for argument passing (inreg). Tail call optimization is performed
3210 //  provided:
3211 //                * tailcallopt is enabled
3212 //                * caller/callee are fastcc
3213 //  On X86_64 architecture with GOT-style position independent code only local
3214 //  (within module) calls are supported at the moment.
3215 //  To keep the stack aligned according to platform abi the function
3216 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3217 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3218 //  If a tail called function callee has more arguments than the caller the
3219 //  caller needs to make sure that there is room to move the RETADDR to. This is
3220 //  achieved by reserving an area the size of the argument delta right after the
3221 //  original RETADDR, but before the saved framepointer or the spilled registers
3222 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3223 //  stack layout:
3224 //    arg1
3225 //    arg2
3226 //    RETADDR
3227 //    [ new RETADDR
3228 //      move area ]
3229 //    (possible EBP)
3230 //    ESI
3231 //    EDI
3232 //    local1 ..
3233
3234 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3235 /// for a 16 byte align requirement.
3236 unsigned
3237 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3238                                                SelectionDAG& DAG) const {
3239   MachineFunction &MF = DAG.getMachineFunction();
3240   const TargetMachine &TM = MF.getTarget();
3241   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3242       TM.getSubtargetImpl()->getRegisterInfo());
3243   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3244   unsigned StackAlignment = TFI.getStackAlignment();
3245   uint64_t AlignMask = StackAlignment - 1;
3246   int64_t Offset = StackSize;
3247   unsigned SlotSize = RegInfo->getSlotSize();
3248   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3249     // Number smaller than 12 so just add the difference.
3250     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3251   } else {
3252     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3253     Offset = ((~AlignMask) & Offset) + StackAlignment +
3254       (StackAlignment-SlotSize);
3255   }
3256   return Offset;
3257 }
3258
3259 /// MatchingStackOffset - Return true if the given stack call argument is
3260 /// already available in the same position (relatively) of the caller's
3261 /// incoming argument stack.
3262 static
3263 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3264                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3265                          const X86InstrInfo *TII) {
3266   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3267   int FI = INT_MAX;
3268   if (Arg.getOpcode() == ISD::CopyFromReg) {
3269     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3270     if (!TargetRegisterInfo::isVirtualRegister(VR))
3271       return false;
3272     MachineInstr *Def = MRI->getVRegDef(VR);
3273     if (!Def)
3274       return false;
3275     if (!Flags.isByVal()) {
3276       if (!TII->isLoadFromStackSlot(Def, FI))
3277         return false;
3278     } else {
3279       unsigned Opcode = Def->getOpcode();
3280       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3281           Def->getOperand(1).isFI()) {
3282         FI = Def->getOperand(1).getIndex();
3283         Bytes = Flags.getByValSize();
3284       } else
3285         return false;
3286     }
3287   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3288     if (Flags.isByVal())
3289       // ByVal argument is passed in as a pointer but it's now being
3290       // dereferenced. e.g.
3291       // define @foo(%struct.X* %A) {
3292       //   tail call @bar(%struct.X* byval %A)
3293       // }
3294       return false;
3295     SDValue Ptr = Ld->getBasePtr();
3296     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3297     if (!FINode)
3298       return false;
3299     FI = FINode->getIndex();
3300   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3301     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3302     FI = FINode->getIndex();
3303     Bytes = Flags.getByValSize();
3304   } else
3305     return false;
3306
3307   assert(FI != INT_MAX);
3308   if (!MFI->isFixedObjectIndex(FI))
3309     return false;
3310   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3311 }
3312
3313 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3314 /// for tail call optimization. Targets which want to do tail call
3315 /// optimization should implement this function.
3316 bool
3317 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3318                                                      CallingConv::ID CalleeCC,
3319                                                      bool isVarArg,
3320                                                      bool isCalleeStructRet,
3321                                                      bool isCallerStructRet,
3322                                                      Type *RetTy,
3323                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3324                                     const SmallVectorImpl<SDValue> &OutVals,
3325                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3326                                                      SelectionDAG &DAG) const {
3327   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3328     return false;
3329
3330   // If -tailcallopt is specified, make fastcc functions tail-callable.
3331   const MachineFunction &MF = DAG.getMachineFunction();
3332   const Function *CallerF = MF.getFunction();
3333
3334   // If the function return type is x86_fp80 and the callee return type is not,
3335   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3336   // perform a tailcall optimization here.
3337   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3338     return false;
3339
3340   CallingConv::ID CallerCC = CallerF->getCallingConv();
3341   bool CCMatch = CallerCC == CalleeCC;
3342   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3343   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3344
3345   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3346     if (IsTailCallConvention(CalleeCC) && CCMatch)
3347       return true;
3348     return false;
3349   }
3350
3351   // Look for obvious safe cases to perform tail call optimization that do not
3352   // require ABI changes. This is what gcc calls sibcall.
3353
3354   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3355   // emit a special epilogue.
3356   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3357       DAG.getSubtarget().getRegisterInfo());
3358   if (RegInfo->needsStackRealignment(MF))
3359     return false;
3360
3361   // Also avoid sibcall optimization if either caller or callee uses struct
3362   // return semantics.
3363   if (isCalleeStructRet || isCallerStructRet)
3364     return false;
3365
3366   // An stdcall/thiscall caller is expected to clean up its arguments; the
3367   // callee isn't going to do that.
3368   // FIXME: this is more restrictive than needed. We could produce a tailcall
3369   // when the stack adjustment matches. For example, with a thiscall that takes
3370   // only one argument.
3371   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3372                    CallerCC == CallingConv::X86_ThisCall))
3373     return false;
3374
3375   // Do not sibcall optimize vararg calls unless all arguments are passed via
3376   // registers.
3377   if (isVarArg && !Outs.empty()) {
3378
3379     // Optimizing for varargs on Win64 is unlikely to be safe without
3380     // additional testing.
3381     if (IsCalleeWin64 || IsCallerWin64)
3382       return false;
3383
3384     SmallVector<CCValAssign, 16> ArgLocs;
3385     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3386                    *DAG.getContext());
3387
3388     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3389     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3390       if (!ArgLocs[i].isRegLoc())
3391         return false;
3392   }
3393
3394   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3395   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3396   // this into a sibcall.
3397   bool Unused = false;
3398   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3399     if (!Ins[i].Used) {
3400       Unused = true;
3401       break;
3402     }
3403   }
3404   if (Unused) {
3405     SmallVector<CCValAssign, 16> RVLocs;
3406     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3407                    *DAG.getContext());
3408     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3409     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3410       CCValAssign &VA = RVLocs[i];
3411       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3412         return false;
3413     }
3414   }
3415
3416   // If the calling conventions do not match, then we'd better make sure the
3417   // results are returned in the same way as what the caller expects.
3418   if (!CCMatch) {
3419     SmallVector<CCValAssign, 16> RVLocs1;
3420     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3421                     *DAG.getContext());
3422     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3423
3424     SmallVector<CCValAssign, 16> RVLocs2;
3425     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3426                     *DAG.getContext());
3427     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3428
3429     if (RVLocs1.size() != RVLocs2.size())
3430       return false;
3431     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3432       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3433         return false;
3434       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3435         return false;
3436       if (RVLocs1[i].isRegLoc()) {
3437         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3438           return false;
3439       } else {
3440         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3441           return false;
3442       }
3443     }
3444   }
3445
3446   // If the callee takes no arguments then go on to check the results of the
3447   // call.
3448   if (!Outs.empty()) {
3449     // Check if stack adjustment is needed. For now, do not do this if any
3450     // argument is passed on the stack.
3451     SmallVector<CCValAssign, 16> ArgLocs;
3452     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3453                    *DAG.getContext());
3454
3455     // Allocate shadow area for Win64
3456     if (IsCalleeWin64)
3457       CCInfo.AllocateStack(32, 8);
3458
3459     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3460     if (CCInfo.getNextStackOffset()) {
3461       MachineFunction &MF = DAG.getMachineFunction();
3462       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3463         return false;
3464
3465       // Check if the arguments are already laid out in the right way as
3466       // the caller's fixed stack objects.
3467       MachineFrameInfo *MFI = MF.getFrameInfo();
3468       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3469       const X86InstrInfo *TII =
3470           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3471       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3472         CCValAssign &VA = ArgLocs[i];
3473         SDValue Arg = OutVals[i];
3474         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3475         if (VA.getLocInfo() == CCValAssign::Indirect)
3476           return false;
3477         if (!VA.isRegLoc()) {
3478           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3479                                    MFI, MRI, TII))
3480             return false;
3481         }
3482       }
3483     }
3484
3485     // If the tailcall address may be in a register, then make sure it's
3486     // possible to register allocate for it. In 32-bit, the call address can
3487     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3488     // callee-saved registers are restored. These happen to be the same
3489     // registers used to pass 'inreg' arguments so watch out for those.
3490     if (!Subtarget->is64Bit() &&
3491         ((!isa<GlobalAddressSDNode>(Callee) &&
3492           !isa<ExternalSymbolSDNode>(Callee)) ||
3493          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3494       unsigned NumInRegs = 0;
3495       // In PIC we need an extra register to formulate the address computation
3496       // for the callee.
3497       unsigned MaxInRegs =
3498         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3499
3500       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3501         CCValAssign &VA = ArgLocs[i];
3502         if (!VA.isRegLoc())
3503           continue;
3504         unsigned Reg = VA.getLocReg();
3505         switch (Reg) {
3506         default: break;
3507         case X86::EAX: case X86::EDX: case X86::ECX:
3508           if (++NumInRegs == MaxInRegs)
3509             return false;
3510           break;
3511         }
3512       }
3513     }
3514   }
3515
3516   return true;
3517 }
3518
3519 FastISel *
3520 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3521                                   const TargetLibraryInfo *libInfo) const {
3522   return X86::createFastISel(funcInfo, libInfo);
3523 }
3524
3525 //===----------------------------------------------------------------------===//
3526 //                           Other Lowering Hooks
3527 //===----------------------------------------------------------------------===//
3528
3529 static bool MayFoldLoad(SDValue Op) {
3530   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3531 }
3532
3533 static bool MayFoldIntoStore(SDValue Op) {
3534   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3535 }
3536
3537 static bool isTargetShuffle(unsigned Opcode) {
3538   switch(Opcode) {
3539   default: return false;
3540   case X86ISD::BLENDI:
3541   case X86ISD::PSHUFB:
3542   case X86ISD::PSHUFD:
3543   case X86ISD::PSHUFHW:
3544   case X86ISD::PSHUFLW:
3545   case X86ISD::SHUFP:
3546   case X86ISD::PALIGNR:
3547   case X86ISD::MOVLHPS:
3548   case X86ISD::MOVLHPD:
3549   case X86ISD::MOVHLPS:
3550   case X86ISD::MOVLPS:
3551   case X86ISD::MOVLPD:
3552   case X86ISD::MOVSHDUP:
3553   case X86ISD::MOVSLDUP:
3554   case X86ISD::MOVDDUP:
3555   case X86ISD::MOVSS:
3556   case X86ISD::MOVSD:
3557   case X86ISD::UNPCKL:
3558   case X86ISD::UNPCKH:
3559   case X86ISD::VPERMILPI:
3560   case X86ISD::VPERM2X128:
3561   case X86ISD::VPERMI:
3562     return true;
3563   }
3564 }
3565
3566 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3567                                     SDValue V1, SelectionDAG &DAG) {
3568   switch(Opc) {
3569   default: llvm_unreachable("Unknown x86 shuffle node");
3570   case X86ISD::MOVSHDUP:
3571   case X86ISD::MOVSLDUP:
3572   case X86ISD::MOVDDUP:
3573     return DAG.getNode(Opc, dl, VT, V1);
3574   }
3575 }
3576
3577 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3578                                     SDValue V1, unsigned TargetMask,
3579                                     SelectionDAG &DAG) {
3580   switch(Opc) {
3581   default: llvm_unreachable("Unknown x86 shuffle node");
3582   case X86ISD::PSHUFD:
3583   case X86ISD::PSHUFHW:
3584   case X86ISD::PSHUFLW:
3585   case X86ISD::VPERMILPI:
3586   case X86ISD::VPERMI:
3587     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3588   }
3589 }
3590
3591 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3592                                     SDValue V1, SDValue V2, unsigned TargetMask,
3593                                     SelectionDAG &DAG) {
3594   switch(Opc) {
3595   default: llvm_unreachable("Unknown x86 shuffle node");
3596   case X86ISD::PALIGNR:
3597   case X86ISD::VALIGN:
3598   case X86ISD::SHUFP:
3599   case X86ISD::VPERM2X128:
3600     return DAG.getNode(Opc, dl, VT, V1, V2,
3601                        DAG.getConstant(TargetMask, MVT::i8));
3602   }
3603 }
3604
3605 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3606                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3607   switch(Opc) {
3608   default: llvm_unreachable("Unknown x86 shuffle node");
3609   case X86ISD::MOVLHPS:
3610   case X86ISD::MOVLHPD:
3611   case X86ISD::MOVHLPS:
3612   case X86ISD::MOVLPS:
3613   case X86ISD::MOVLPD:
3614   case X86ISD::MOVSS:
3615   case X86ISD::MOVSD:
3616   case X86ISD::UNPCKL:
3617   case X86ISD::UNPCKH:
3618     return DAG.getNode(Opc, dl, VT, V1, V2);
3619   }
3620 }
3621
3622 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3623   MachineFunction &MF = DAG.getMachineFunction();
3624   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3625       DAG.getSubtarget().getRegisterInfo());
3626   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3627   int ReturnAddrIndex = FuncInfo->getRAIndex();
3628
3629   if (ReturnAddrIndex == 0) {
3630     // Set up a frame object for the return address.
3631     unsigned SlotSize = RegInfo->getSlotSize();
3632     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3633                                                            -(int64_t)SlotSize,
3634                                                            false);
3635     FuncInfo->setRAIndex(ReturnAddrIndex);
3636   }
3637
3638   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3639 }
3640
3641 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3642                                        bool hasSymbolicDisplacement) {
3643   // Offset should fit into 32 bit immediate field.
3644   if (!isInt<32>(Offset))
3645     return false;
3646
3647   // If we don't have a symbolic displacement - we don't have any extra
3648   // restrictions.
3649   if (!hasSymbolicDisplacement)
3650     return true;
3651
3652   // FIXME: Some tweaks might be needed for medium code model.
3653   if (M != CodeModel::Small && M != CodeModel::Kernel)
3654     return false;
3655
3656   // For small code model we assume that latest object is 16MB before end of 31
3657   // bits boundary. We may also accept pretty large negative constants knowing
3658   // that all objects are in the positive half of address space.
3659   if (M == CodeModel::Small && Offset < 16*1024*1024)
3660     return true;
3661
3662   // For kernel code model we know that all object resist in the negative half
3663   // of 32bits address space. We may not accept negative offsets, since they may
3664   // be just off and we may accept pretty large positive ones.
3665   if (M == CodeModel::Kernel && Offset > 0)
3666     return true;
3667
3668   return false;
3669 }
3670
3671 /// isCalleePop - Determines whether the callee is required to pop its
3672 /// own arguments. Callee pop is necessary to support tail calls.
3673 bool X86::isCalleePop(CallingConv::ID CallingConv,
3674                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3675   switch (CallingConv) {
3676   default:
3677     return false;
3678   case CallingConv::X86_StdCall:
3679   case CallingConv::X86_FastCall:
3680   case CallingConv::X86_ThisCall:
3681     return !is64Bit;
3682   case CallingConv::Fast:
3683   case CallingConv::GHC:
3684   case CallingConv::HiPE:
3685     if (IsVarArg)
3686       return false;
3687     return TailCallOpt;
3688   }
3689 }
3690
3691 /// \brief Return true if the condition is an unsigned comparison operation.
3692 static bool isX86CCUnsigned(unsigned X86CC) {
3693   switch (X86CC) {
3694   default: llvm_unreachable("Invalid integer condition!");
3695   case X86::COND_E:     return true;
3696   case X86::COND_G:     return false;
3697   case X86::COND_GE:    return false;
3698   case X86::COND_L:     return false;
3699   case X86::COND_LE:    return false;
3700   case X86::COND_NE:    return true;
3701   case X86::COND_B:     return true;
3702   case X86::COND_A:     return true;
3703   case X86::COND_BE:    return true;
3704   case X86::COND_AE:    return true;
3705   }
3706   llvm_unreachable("covered switch fell through?!");
3707 }
3708
3709 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3710 /// specific condition code, returning the condition code and the LHS/RHS of the
3711 /// comparison to make.
3712 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3713                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3714   if (!isFP) {
3715     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3716       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3717         // X > -1   -> X == 0, jump !sign.
3718         RHS = DAG.getConstant(0, RHS.getValueType());
3719         return X86::COND_NS;
3720       }
3721       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3722         // X < 0   -> X == 0, jump on sign.
3723         return X86::COND_S;
3724       }
3725       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3726         // X < 1   -> X <= 0
3727         RHS = DAG.getConstant(0, RHS.getValueType());
3728         return X86::COND_LE;
3729       }
3730     }
3731
3732     switch (SetCCOpcode) {
3733     default: llvm_unreachable("Invalid integer condition!");
3734     case ISD::SETEQ:  return X86::COND_E;
3735     case ISD::SETGT:  return X86::COND_G;
3736     case ISD::SETGE:  return X86::COND_GE;
3737     case ISD::SETLT:  return X86::COND_L;
3738     case ISD::SETLE:  return X86::COND_LE;
3739     case ISD::SETNE:  return X86::COND_NE;
3740     case ISD::SETULT: return X86::COND_B;
3741     case ISD::SETUGT: return X86::COND_A;
3742     case ISD::SETULE: return X86::COND_BE;
3743     case ISD::SETUGE: return X86::COND_AE;
3744     }
3745   }
3746
3747   // First determine if it is required or is profitable to flip the operands.
3748
3749   // If LHS is a foldable load, but RHS is not, flip the condition.
3750   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3751       !ISD::isNON_EXTLoad(RHS.getNode())) {
3752     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3753     std::swap(LHS, RHS);
3754   }
3755
3756   switch (SetCCOpcode) {
3757   default: break;
3758   case ISD::SETOLT:
3759   case ISD::SETOLE:
3760   case ISD::SETUGT:
3761   case ISD::SETUGE:
3762     std::swap(LHS, RHS);
3763     break;
3764   }
3765
3766   // On a floating point condition, the flags are set as follows:
3767   // ZF  PF  CF   op
3768   //  0 | 0 | 0 | X > Y
3769   //  0 | 0 | 1 | X < Y
3770   //  1 | 0 | 0 | X == Y
3771   //  1 | 1 | 1 | unordered
3772   switch (SetCCOpcode) {
3773   default: llvm_unreachable("Condcode should be pre-legalized away");
3774   case ISD::SETUEQ:
3775   case ISD::SETEQ:   return X86::COND_E;
3776   case ISD::SETOLT:              // flipped
3777   case ISD::SETOGT:
3778   case ISD::SETGT:   return X86::COND_A;
3779   case ISD::SETOLE:              // flipped
3780   case ISD::SETOGE:
3781   case ISD::SETGE:   return X86::COND_AE;
3782   case ISD::SETUGT:              // flipped
3783   case ISD::SETULT:
3784   case ISD::SETLT:   return X86::COND_B;
3785   case ISD::SETUGE:              // flipped
3786   case ISD::SETULE:
3787   case ISD::SETLE:   return X86::COND_BE;
3788   case ISD::SETONE:
3789   case ISD::SETNE:   return X86::COND_NE;
3790   case ISD::SETUO:   return X86::COND_P;
3791   case ISD::SETO:    return X86::COND_NP;
3792   case ISD::SETOEQ:
3793   case ISD::SETUNE:  return X86::COND_INVALID;
3794   }
3795 }
3796
3797 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3798 /// code. Current x86 isa includes the following FP cmov instructions:
3799 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3800 static bool hasFPCMov(unsigned X86CC) {
3801   switch (X86CC) {
3802   default:
3803     return false;
3804   case X86::COND_B:
3805   case X86::COND_BE:
3806   case X86::COND_E:
3807   case X86::COND_P:
3808   case X86::COND_A:
3809   case X86::COND_AE:
3810   case X86::COND_NE:
3811   case X86::COND_NP:
3812     return true;
3813   }
3814 }
3815
3816 /// isFPImmLegal - Returns true if the target can instruction select the
3817 /// specified FP immediate natively. If false, the legalizer will
3818 /// materialize the FP immediate as a load from a constant pool.
3819 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3820   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3821     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3822       return true;
3823   }
3824   return false;
3825 }
3826
3827 /// \brief Returns true if it is beneficial to convert a load of a constant
3828 /// to just the constant itself.
3829 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3830                                                           Type *Ty) const {
3831   assert(Ty->isIntegerTy());
3832
3833   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3834   if (BitSize == 0 || BitSize > 64)
3835     return false;
3836   return true;
3837 }
3838
3839 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3840 /// the specified range (L, H].
3841 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3842   return (Val < 0) || (Val >= Low && Val < Hi);
3843 }
3844
3845 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3846 /// specified value.
3847 static bool isUndefOrEqual(int Val, int CmpVal) {
3848   return (Val < 0 || Val == CmpVal);
3849 }
3850
3851 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3852 /// from position Pos and ending in Pos+Size, falls within the specified
3853 /// sequential range (L, L+Pos]. or is undef.
3854 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3855                                        unsigned Pos, unsigned Size, int Low) {
3856   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3857     if (!isUndefOrEqual(Mask[i], Low))
3858       return false;
3859   return true;
3860 }
3861
3862 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3863 /// is suitable for input to PSHUFD. That is, it doesn't reference the other
3864 /// operand - by default will match for first operand.
3865 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT,
3866                          bool TestSecondOperand = false) {
3867   if (VT != MVT::v4f32 && VT != MVT::v4i32 &&
3868       VT != MVT::v2f64 && VT != MVT::v2i64)
3869     return false;
3870
3871   unsigned NumElems = VT.getVectorNumElements();
3872   unsigned Lo = TestSecondOperand ? NumElems : 0;
3873   unsigned Hi = Lo + NumElems;
3874
3875   for (unsigned i = 0; i < NumElems; ++i)
3876     if (!isUndefOrInRange(Mask[i], (int)Lo, (int)Hi))
3877       return false;
3878
3879   return true;
3880 }
3881
3882 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3883 /// is suitable for input to PSHUFHW.
3884 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3885   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3886     return false;
3887
3888   // Lower quadword copied in order or undef.
3889   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3890     return false;
3891
3892   // Upper quadword shuffled.
3893   for (unsigned i = 4; i != 8; ++i)
3894     if (!isUndefOrInRange(Mask[i], 4, 8))
3895       return false;
3896
3897   if (VT == MVT::v16i16) {
3898     // Lower quadword copied in order or undef.
3899     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3900       return false;
3901
3902     // Upper quadword shuffled.
3903     for (unsigned i = 12; i != 16; ++i)
3904       if (!isUndefOrInRange(Mask[i], 12, 16))
3905         return false;
3906   }
3907
3908   return true;
3909 }
3910
3911 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3912 /// is suitable for input to PSHUFLW.
3913 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3914   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3915     return false;
3916
3917   // Upper quadword copied in order.
3918   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3919     return false;
3920
3921   // Lower quadword shuffled.
3922   for (unsigned i = 0; i != 4; ++i)
3923     if (!isUndefOrInRange(Mask[i], 0, 4))
3924       return false;
3925
3926   if (VT == MVT::v16i16) {
3927     // Upper quadword copied in order.
3928     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3929       return false;
3930
3931     // Lower quadword shuffled.
3932     for (unsigned i = 8; i != 12; ++i)
3933       if (!isUndefOrInRange(Mask[i], 8, 12))
3934         return false;
3935   }
3936
3937   return true;
3938 }
3939
3940 /// \brief Return true if the mask specifies a shuffle of elements that is
3941 /// suitable for input to intralane (palignr) or interlane (valign) vector
3942 /// right-shift.
3943 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3944   unsigned NumElts = VT.getVectorNumElements();
3945   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3946   unsigned NumLaneElts = NumElts/NumLanes;
3947
3948   // Do not handle 64-bit element shuffles with palignr.
3949   if (NumLaneElts == 2)
3950     return false;
3951
3952   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3953     unsigned i;
3954     for (i = 0; i != NumLaneElts; ++i) {
3955       if (Mask[i+l] >= 0)
3956         break;
3957     }
3958
3959     // Lane is all undef, go to next lane
3960     if (i == NumLaneElts)
3961       continue;
3962
3963     int Start = Mask[i+l];
3964
3965     // Make sure its in this lane in one of the sources
3966     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3967         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3968       return false;
3969
3970     // If not lane 0, then we must match lane 0
3971     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3972       return false;
3973
3974     // Correct second source to be contiguous with first source
3975     if (Start >= (int)NumElts)
3976       Start -= NumElts - NumLaneElts;
3977
3978     // Make sure we're shifting in the right direction.
3979     if (Start <= (int)(i+l))
3980       return false;
3981
3982     Start -= i;
3983
3984     // Check the rest of the elements to see if they are consecutive.
3985     for (++i; i != NumLaneElts; ++i) {
3986       int Idx = Mask[i+l];
3987
3988       // Make sure its in this lane
3989       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3990           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3991         return false;
3992
3993       // If not lane 0, then we must match lane 0
3994       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3995         return false;
3996
3997       if (Idx >= (int)NumElts)
3998         Idx -= NumElts - NumLaneElts;
3999
4000       if (!isUndefOrEqual(Idx, Start+i))
4001         return false;
4002
4003     }
4004   }
4005
4006   return true;
4007 }
4008
4009 /// \brief Return true if the node specifies a shuffle of elements that is
4010 /// suitable for input to PALIGNR.
4011 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4012                           const X86Subtarget *Subtarget) {
4013   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4014       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4015       VT.is512BitVector())
4016     // FIXME: Add AVX512BW.
4017     return false;
4018
4019   return isAlignrMask(Mask, VT, false);
4020 }
4021
4022 /// \brief Return true if the node specifies a shuffle of elements that is
4023 /// suitable for input to VALIGN.
4024 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4025                           const X86Subtarget *Subtarget) {
4026   // FIXME: Add AVX512VL.
4027   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4028     return false;
4029   return isAlignrMask(Mask, VT, true);
4030 }
4031
4032 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4033 /// the two vector operands have swapped position.
4034 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4035                                      unsigned NumElems) {
4036   for (unsigned i = 0; i != NumElems; ++i) {
4037     int idx = Mask[i];
4038     if (idx < 0)
4039       continue;
4040     else if (idx < (int)NumElems)
4041       Mask[i] = idx + NumElems;
4042     else
4043       Mask[i] = idx - NumElems;
4044   }
4045 }
4046
4047 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4048 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4049 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4050 /// reverse of what x86 shuffles want.
4051 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4052
4053   unsigned NumElems = VT.getVectorNumElements();
4054   unsigned NumLanes = VT.getSizeInBits()/128;
4055   unsigned NumLaneElems = NumElems/NumLanes;
4056
4057   if (NumLaneElems != 2 && NumLaneElems != 4)
4058     return false;
4059
4060   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4061   bool symetricMaskRequired =
4062     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4063
4064   // VSHUFPSY divides the resulting vector into 4 chunks.
4065   // The sources are also splitted into 4 chunks, and each destination
4066   // chunk must come from a different source chunk.
4067   //
4068   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4069   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4070   //
4071   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4072   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4073   //
4074   // VSHUFPDY divides the resulting vector into 4 chunks.
4075   // The sources are also splitted into 4 chunks, and each destination
4076   // chunk must come from a different source chunk.
4077   //
4078   //  SRC1 =>      X3       X2       X1       X0
4079   //  SRC2 =>      Y3       Y2       Y1       Y0
4080   //
4081   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4082   //
4083   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4084   unsigned HalfLaneElems = NumLaneElems/2;
4085   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4086     for (unsigned i = 0; i != NumLaneElems; ++i) {
4087       int Idx = Mask[i+l];
4088       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4089       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4090         return false;
4091       // For VSHUFPSY, the mask of the second half must be the same as the
4092       // first but with the appropriate offsets. This works in the same way as
4093       // VPERMILPS works with masks.
4094       if (!symetricMaskRequired || Idx < 0)
4095         continue;
4096       if (MaskVal[i] < 0) {
4097         MaskVal[i] = Idx - l;
4098         continue;
4099       }
4100       if ((signed)(Idx - l) != MaskVal[i])
4101         return false;
4102     }
4103   }
4104
4105   return true;
4106 }
4107
4108 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4109 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4110 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4111   if (!VT.is128BitVector())
4112     return false;
4113
4114   unsigned NumElems = VT.getVectorNumElements();
4115
4116   if (NumElems != 4)
4117     return false;
4118
4119   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4120   return isUndefOrEqual(Mask[0], 6) &&
4121          isUndefOrEqual(Mask[1], 7) &&
4122          isUndefOrEqual(Mask[2], 2) &&
4123          isUndefOrEqual(Mask[3], 3);
4124 }
4125
4126 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4127 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4128 /// <2, 3, 2, 3>
4129 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4130   if (!VT.is128BitVector())
4131     return false;
4132
4133   unsigned NumElems = VT.getVectorNumElements();
4134
4135   if (NumElems != 4)
4136     return false;
4137
4138   return isUndefOrEqual(Mask[0], 2) &&
4139          isUndefOrEqual(Mask[1], 3) &&
4140          isUndefOrEqual(Mask[2], 2) &&
4141          isUndefOrEqual(Mask[3], 3);
4142 }
4143
4144 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4145 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4146 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4147   if (!VT.is128BitVector())
4148     return false;
4149
4150   unsigned NumElems = VT.getVectorNumElements();
4151
4152   if (NumElems != 2 && NumElems != 4)
4153     return false;
4154
4155   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4156     if (!isUndefOrEqual(Mask[i], i + NumElems))
4157       return false;
4158
4159   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4160     if (!isUndefOrEqual(Mask[i], i))
4161       return false;
4162
4163   return true;
4164 }
4165
4166 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4167 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4168 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4169   if (!VT.is128BitVector())
4170     return false;
4171
4172   unsigned NumElems = VT.getVectorNumElements();
4173
4174   if (NumElems != 2 && NumElems != 4)
4175     return false;
4176
4177   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4178     if (!isUndefOrEqual(Mask[i], i))
4179       return false;
4180
4181   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4182     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4183       return false;
4184
4185   return true;
4186 }
4187
4188 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4189 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4190 /// i. e: If all but one element come from the same vector.
4191 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4192   // TODO: Deal with AVX's VINSERTPS
4193   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4194     return false;
4195
4196   unsigned CorrectPosV1 = 0;
4197   unsigned CorrectPosV2 = 0;
4198   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4199     if (Mask[i] == -1) {
4200       ++CorrectPosV1;
4201       ++CorrectPosV2;
4202       continue;
4203     }
4204
4205     if (Mask[i] == i)
4206       ++CorrectPosV1;
4207     else if (Mask[i] == i + 4)
4208       ++CorrectPosV2;
4209   }
4210
4211   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4212     // We have 3 elements (undefs count as elements from any vector) from one
4213     // vector, and one from another.
4214     return true;
4215
4216   return false;
4217 }
4218
4219 //
4220 // Some special combinations that can be optimized.
4221 //
4222 static
4223 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4224                                SelectionDAG &DAG) {
4225   MVT VT = SVOp->getSimpleValueType(0);
4226   SDLoc dl(SVOp);
4227
4228   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4229     return SDValue();
4230
4231   ArrayRef<int> Mask = SVOp->getMask();
4232
4233   // These are the special masks that may be optimized.
4234   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4235   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4236   bool MatchEvenMask = true;
4237   bool MatchOddMask  = true;
4238   for (int i=0; i<8; ++i) {
4239     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4240       MatchEvenMask = false;
4241     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4242       MatchOddMask = false;
4243   }
4244
4245   if (!MatchEvenMask && !MatchOddMask)
4246     return SDValue();
4247
4248   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4249
4250   SDValue Op0 = SVOp->getOperand(0);
4251   SDValue Op1 = SVOp->getOperand(1);
4252
4253   if (MatchEvenMask) {
4254     // Shift the second operand right to 32 bits.
4255     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4256     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4257   } else {
4258     // Shift the first operand left to 32 bits.
4259     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4260     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4261   }
4262   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4263   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4264 }
4265
4266 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4267 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4268 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4269                          bool HasInt256, bool V2IsSplat = false) {
4270
4271   assert(VT.getSizeInBits() >= 128 &&
4272          "Unsupported vector type for unpckl");
4273
4274   unsigned NumElts = VT.getVectorNumElements();
4275   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4276       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4277     return false;
4278
4279   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4280          "Unsupported vector type for unpckh");
4281
4282   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4283   unsigned NumLanes = VT.getSizeInBits()/128;
4284   unsigned NumLaneElts = NumElts/NumLanes;
4285
4286   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4287     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4288       int BitI  = Mask[l+i];
4289       int BitI1 = Mask[l+i+1];
4290       if (!isUndefOrEqual(BitI, j))
4291         return false;
4292       if (V2IsSplat) {
4293         if (!isUndefOrEqual(BitI1, NumElts))
4294           return false;
4295       } else {
4296         if (!isUndefOrEqual(BitI1, j + NumElts))
4297           return false;
4298       }
4299     }
4300   }
4301
4302   return true;
4303 }
4304
4305 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4306 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4307 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4308                          bool HasInt256, bool V2IsSplat = false) {
4309   assert(VT.getSizeInBits() >= 128 &&
4310          "Unsupported vector type for unpckh");
4311
4312   unsigned NumElts = VT.getVectorNumElements();
4313   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4314       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4315     return false;
4316
4317   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4318          "Unsupported vector type for unpckh");
4319
4320   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4321   unsigned NumLanes = VT.getSizeInBits()/128;
4322   unsigned NumLaneElts = NumElts/NumLanes;
4323
4324   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4325     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4326       int BitI  = Mask[l+i];
4327       int BitI1 = Mask[l+i+1];
4328       if (!isUndefOrEqual(BitI, j))
4329         return false;
4330       if (V2IsSplat) {
4331         if (isUndefOrEqual(BitI1, NumElts))
4332           return false;
4333       } else {
4334         if (!isUndefOrEqual(BitI1, j+NumElts))
4335           return false;
4336       }
4337     }
4338   }
4339   return true;
4340 }
4341
4342 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4343 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4344 /// <0, 0, 1, 1>
4345 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4346   unsigned NumElts = VT.getVectorNumElements();
4347   bool Is256BitVec = VT.is256BitVector();
4348
4349   if (VT.is512BitVector())
4350     return false;
4351   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4352          "Unsupported vector type for unpckh");
4353
4354   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4355       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4356     return false;
4357
4358   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4359   // FIXME: Need a better way to get rid of this, there's no latency difference
4360   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4361   // the former later. We should also remove the "_undef" special mask.
4362   if (NumElts == 4 && Is256BitVec)
4363     return false;
4364
4365   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4366   // independently on 128-bit lanes.
4367   unsigned NumLanes = VT.getSizeInBits()/128;
4368   unsigned NumLaneElts = NumElts/NumLanes;
4369
4370   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4371     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4372       int BitI  = Mask[l+i];
4373       int BitI1 = Mask[l+i+1];
4374
4375       if (!isUndefOrEqual(BitI, j))
4376         return false;
4377       if (!isUndefOrEqual(BitI1, j))
4378         return false;
4379     }
4380   }
4381
4382   return true;
4383 }
4384
4385 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4386 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4387 /// <2, 2, 3, 3>
4388 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4389   unsigned NumElts = VT.getVectorNumElements();
4390
4391   if (VT.is512BitVector())
4392     return false;
4393
4394   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4395          "Unsupported vector type for unpckh");
4396
4397   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4398       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4399     return false;
4400
4401   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4402   // independently on 128-bit lanes.
4403   unsigned NumLanes = VT.getSizeInBits()/128;
4404   unsigned NumLaneElts = NumElts/NumLanes;
4405
4406   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4407     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4408       int BitI  = Mask[l+i];
4409       int BitI1 = Mask[l+i+1];
4410       if (!isUndefOrEqual(BitI, j))
4411         return false;
4412       if (!isUndefOrEqual(BitI1, j))
4413         return false;
4414     }
4415   }
4416   return true;
4417 }
4418
4419 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4420 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4421 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4422   if (!VT.is512BitVector())
4423     return false;
4424
4425   unsigned NumElts = VT.getVectorNumElements();
4426   unsigned HalfSize = NumElts/2;
4427   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4428     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4429       *Imm = 1;
4430       return true;
4431     }
4432   }
4433   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4434     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4435       *Imm = 0;
4436       return true;
4437     }
4438   }
4439   return false;
4440 }
4441
4442 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4443 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4444 /// MOVSD, and MOVD, i.e. setting the lowest element.
4445 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4446   if (VT.getVectorElementType().getSizeInBits() < 32)
4447     return false;
4448   if (!VT.is128BitVector())
4449     return false;
4450
4451   unsigned NumElts = VT.getVectorNumElements();
4452
4453   if (!isUndefOrEqual(Mask[0], NumElts))
4454     return false;
4455
4456   for (unsigned i = 1; i != NumElts; ++i)
4457     if (!isUndefOrEqual(Mask[i], i))
4458       return false;
4459
4460   return true;
4461 }
4462
4463 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4464 /// as permutations between 128-bit chunks or halves. As an example: this
4465 /// shuffle bellow:
4466 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4467 /// The first half comes from the second half of V1 and the second half from the
4468 /// the second half of V2.
4469 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4470   if (!HasFp256 || !VT.is256BitVector())
4471     return false;
4472
4473   // The shuffle result is divided into half A and half B. In total the two
4474   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4475   // B must come from C, D, E or F.
4476   unsigned HalfSize = VT.getVectorNumElements()/2;
4477   bool MatchA = false, MatchB = false;
4478
4479   // Check if A comes from one of C, D, E, F.
4480   for (unsigned Half = 0; Half != 4; ++Half) {
4481     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4482       MatchA = true;
4483       break;
4484     }
4485   }
4486
4487   // Check if B comes from one of C, D, E, F.
4488   for (unsigned Half = 0; Half != 4; ++Half) {
4489     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4490       MatchB = true;
4491       break;
4492     }
4493   }
4494
4495   return MatchA && MatchB;
4496 }
4497
4498 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4499 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4500 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4501   MVT VT = SVOp->getSimpleValueType(0);
4502
4503   unsigned HalfSize = VT.getVectorNumElements()/2;
4504
4505   unsigned FstHalf = 0, SndHalf = 0;
4506   for (unsigned i = 0; i < HalfSize; ++i) {
4507     if (SVOp->getMaskElt(i) > 0) {
4508       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4509       break;
4510     }
4511   }
4512   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4513     if (SVOp->getMaskElt(i) > 0) {
4514       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4515       break;
4516     }
4517   }
4518
4519   return (FstHalf | (SndHalf << 4));
4520 }
4521
4522 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4523 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4524   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4525   if (EltSize < 32)
4526     return false;
4527
4528   unsigned NumElts = VT.getVectorNumElements();
4529   Imm8 = 0;
4530   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4531     for (unsigned i = 0; i != NumElts; ++i) {
4532       if (Mask[i] < 0)
4533         continue;
4534       Imm8 |= Mask[i] << (i*2);
4535     }
4536     return true;
4537   }
4538
4539   unsigned LaneSize = 4;
4540   SmallVector<int, 4> MaskVal(LaneSize, -1);
4541
4542   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4543     for (unsigned i = 0; i != LaneSize; ++i) {
4544       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4545         return false;
4546       if (Mask[i+l] < 0)
4547         continue;
4548       if (MaskVal[i] < 0) {
4549         MaskVal[i] = Mask[i+l] - l;
4550         Imm8 |= MaskVal[i] << (i*2);
4551         continue;
4552       }
4553       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4554         return false;
4555     }
4556   }
4557   return true;
4558 }
4559
4560 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4561 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4562 /// Note that VPERMIL mask matching is different depending whether theunderlying
4563 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4564 /// to the same elements of the low, but to the higher half of the source.
4565 /// In VPERMILPD the two lanes could be shuffled independently of each other
4566 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4567 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4568   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4569   if (VT.getSizeInBits() < 256 || EltSize < 32)
4570     return false;
4571   bool symetricMaskRequired = (EltSize == 32);
4572   unsigned NumElts = VT.getVectorNumElements();
4573
4574   unsigned NumLanes = VT.getSizeInBits()/128;
4575   unsigned LaneSize = NumElts/NumLanes;
4576   // 2 or 4 elements in one lane
4577
4578   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4579   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4580     for (unsigned i = 0; i != LaneSize; ++i) {
4581       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4582         return false;
4583       if (symetricMaskRequired) {
4584         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4585           ExpectedMaskVal[i] = Mask[i+l] - l;
4586           continue;
4587         }
4588         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4589           return false;
4590       }
4591     }
4592   }
4593   return true;
4594 }
4595
4596 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4597 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4598 /// element of vector 2 and the other elements to come from vector 1 in order.
4599 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4600                                bool V2IsSplat = false, bool V2IsUndef = false) {
4601   if (!VT.is128BitVector())
4602     return false;
4603
4604   unsigned NumOps = VT.getVectorNumElements();
4605   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4606     return false;
4607
4608   if (!isUndefOrEqual(Mask[0], 0))
4609     return false;
4610
4611   for (unsigned i = 1; i != NumOps; ++i)
4612     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4613           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4614           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4615       return false;
4616
4617   return true;
4618 }
4619
4620 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4621 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4622 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4623 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4624                            const X86Subtarget *Subtarget) {
4625   if (!Subtarget->hasSSE3())
4626     return false;
4627
4628   unsigned NumElems = VT.getVectorNumElements();
4629
4630   if ((VT.is128BitVector() && NumElems != 4) ||
4631       (VT.is256BitVector() && NumElems != 8) ||
4632       (VT.is512BitVector() && NumElems != 16))
4633     return false;
4634
4635   // "i+1" is the value the indexed mask element must have
4636   for (unsigned i = 0; i != NumElems; i += 2)
4637     if (!isUndefOrEqual(Mask[i], i+1) ||
4638         !isUndefOrEqual(Mask[i+1], i+1))
4639       return false;
4640
4641   return true;
4642 }
4643
4644 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4645 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4646 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4647 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4648                            const X86Subtarget *Subtarget) {
4649   if (!Subtarget->hasSSE3())
4650     return false;
4651
4652   unsigned NumElems = VT.getVectorNumElements();
4653
4654   if ((VT.is128BitVector() && NumElems != 4) ||
4655       (VT.is256BitVector() && NumElems != 8) ||
4656       (VT.is512BitVector() && NumElems != 16))
4657     return false;
4658
4659   // "i" is the value the indexed mask element must have
4660   for (unsigned i = 0; i != NumElems; i += 2)
4661     if (!isUndefOrEqual(Mask[i], i) ||
4662         !isUndefOrEqual(Mask[i+1], i))
4663       return false;
4664
4665   return true;
4666 }
4667
4668 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4669 /// specifies a shuffle of elements that is suitable for input to 256-bit
4670 /// version of MOVDDUP.
4671 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4672   if (!HasFp256 || !VT.is256BitVector())
4673     return false;
4674
4675   unsigned NumElts = VT.getVectorNumElements();
4676   if (NumElts != 4)
4677     return false;
4678
4679   for (unsigned i = 0; i != NumElts/2; ++i)
4680     if (!isUndefOrEqual(Mask[i], 0))
4681       return false;
4682   for (unsigned i = NumElts/2; i != NumElts; ++i)
4683     if (!isUndefOrEqual(Mask[i], NumElts/2))
4684       return false;
4685   return true;
4686 }
4687
4688 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4689 /// specifies a shuffle of elements that is suitable for input to 128-bit
4690 /// version of MOVDDUP.
4691 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4692   if (!VT.is128BitVector())
4693     return false;
4694
4695   unsigned e = VT.getVectorNumElements() / 2;
4696   for (unsigned i = 0; i != e; ++i)
4697     if (!isUndefOrEqual(Mask[i], i))
4698       return false;
4699   for (unsigned i = 0; i != e; ++i)
4700     if (!isUndefOrEqual(Mask[e+i], i))
4701       return false;
4702   return true;
4703 }
4704
4705 /// isVEXTRACTIndex - Return true if the specified
4706 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4707 /// suitable for instruction that extract 128 or 256 bit vectors
4708 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4709   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4710   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4711     return false;
4712
4713   // The index should be aligned on a vecWidth-bit boundary.
4714   uint64_t Index =
4715     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4716
4717   MVT VT = N->getSimpleValueType(0);
4718   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4719   bool Result = (Index * ElSize) % vecWidth == 0;
4720
4721   return Result;
4722 }
4723
4724 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4725 /// operand specifies a subvector insert that is suitable for input to
4726 /// insertion of 128 or 256-bit subvectors
4727 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4728   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4729   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4730     return false;
4731   // The index should be aligned on a vecWidth-bit boundary.
4732   uint64_t Index =
4733     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4734
4735   MVT VT = N->getSimpleValueType(0);
4736   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4737   bool Result = (Index * ElSize) % vecWidth == 0;
4738
4739   return Result;
4740 }
4741
4742 bool X86::isVINSERT128Index(SDNode *N) {
4743   return isVINSERTIndex(N, 128);
4744 }
4745
4746 bool X86::isVINSERT256Index(SDNode *N) {
4747   return isVINSERTIndex(N, 256);
4748 }
4749
4750 bool X86::isVEXTRACT128Index(SDNode *N) {
4751   return isVEXTRACTIndex(N, 128);
4752 }
4753
4754 bool X86::isVEXTRACT256Index(SDNode *N) {
4755   return isVEXTRACTIndex(N, 256);
4756 }
4757
4758 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4759 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4760 /// Handles 128-bit and 256-bit.
4761 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4762   MVT VT = N->getSimpleValueType(0);
4763
4764   assert((VT.getSizeInBits() >= 128) &&
4765          "Unsupported vector type for PSHUF/SHUFP");
4766
4767   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4768   // independently on 128-bit lanes.
4769   unsigned NumElts = VT.getVectorNumElements();
4770   unsigned NumLanes = VT.getSizeInBits()/128;
4771   unsigned NumLaneElts = NumElts/NumLanes;
4772
4773   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4774          "Only supports 2, 4 or 8 elements per lane");
4775
4776   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4777   unsigned Mask = 0;
4778   for (unsigned i = 0; i != NumElts; ++i) {
4779     int Elt = N->getMaskElt(i);
4780     if (Elt < 0) continue;
4781     Elt &= NumLaneElts - 1;
4782     unsigned ShAmt = (i << Shift) % 8;
4783     Mask |= Elt << ShAmt;
4784   }
4785
4786   return Mask;
4787 }
4788
4789 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4790 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4791 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4792   MVT VT = N->getSimpleValueType(0);
4793
4794   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4795          "Unsupported vector type for PSHUFHW");
4796
4797   unsigned NumElts = VT.getVectorNumElements();
4798
4799   unsigned Mask = 0;
4800   for (unsigned l = 0; l != NumElts; l += 8) {
4801     // 8 nodes per lane, but we only care about the last 4.
4802     for (unsigned i = 0; i < 4; ++i) {
4803       int Elt = N->getMaskElt(l+i+4);
4804       if (Elt < 0) continue;
4805       Elt &= 0x3; // only 2-bits.
4806       Mask |= Elt << (i * 2);
4807     }
4808   }
4809
4810   return Mask;
4811 }
4812
4813 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4814 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4815 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4816   MVT VT = N->getSimpleValueType(0);
4817
4818   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4819          "Unsupported vector type for PSHUFHW");
4820
4821   unsigned NumElts = VT.getVectorNumElements();
4822
4823   unsigned Mask = 0;
4824   for (unsigned l = 0; l != NumElts; l += 8) {
4825     // 8 nodes per lane, but we only care about the first 4.
4826     for (unsigned i = 0; i < 4; ++i) {
4827       int Elt = N->getMaskElt(l+i);
4828       if (Elt < 0) continue;
4829       Elt &= 0x3; // only 2-bits
4830       Mask |= Elt << (i * 2);
4831     }
4832   }
4833
4834   return Mask;
4835 }
4836
4837 /// \brief Return the appropriate immediate to shuffle the specified
4838 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4839 /// VALIGN (if Interlane is true) instructions.
4840 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4841                                            bool InterLane) {
4842   MVT VT = SVOp->getSimpleValueType(0);
4843   unsigned EltSize = InterLane ? 1 :
4844     VT.getVectorElementType().getSizeInBits() >> 3;
4845
4846   unsigned NumElts = VT.getVectorNumElements();
4847   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4848   unsigned NumLaneElts = NumElts/NumLanes;
4849
4850   int Val = 0;
4851   unsigned i;
4852   for (i = 0; i != NumElts; ++i) {
4853     Val = SVOp->getMaskElt(i);
4854     if (Val >= 0)
4855       break;
4856   }
4857   if (Val >= (int)NumElts)
4858     Val -= NumElts - NumLaneElts;
4859
4860   assert(Val - i > 0 && "PALIGNR imm should be positive");
4861   return (Val - i) * EltSize;
4862 }
4863
4864 /// \brief Return the appropriate immediate to shuffle the specified
4865 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4866 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4867   return getShuffleAlignrImmediate(SVOp, false);
4868 }
4869
4870 /// \brief Return the appropriate immediate to shuffle the specified
4871 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4872 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4873   return getShuffleAlignrImmediate(SVOp, true);
4874 }
4875
4876
4877 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4878   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4879   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4880     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4881
4882   uint64_t Index =
4883     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4884
4885   MVT VecVT = N->getOperand(0).getSimpleValueType();
4886   MVT ElVT = VecVT.getVectorElementType();
4887
4888   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4889   return Index / NumElemsPerChunk;
4890 }
4891
4892 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4893   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4894   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4895     llvm_unreachable("Illegal insert subvector for VINSERT");
4896
4897   uint64_t Index =
4898     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4899
4900   MVT VecVT = N->getSimpleValueType(0);
4901   MVT ElVT = VecVT.getVectorElementType();
4902
4903   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4904   return Index / NumElemsPerChunk;
4905 }
4906
4907 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4908 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4909 /// and VINSERTI128 instructions.
4910 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4911   return getExtractVEXTRACTImmediate(N, 128);
4912 }
4913
4914 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4915 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4916 /// and VINSERTI64x4 instructions.
4917 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4918   return getExtractVEXTRACTImmediate(N, 256);
4919 }
4920
4921 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4922 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4923 /// and VINSERTI128 instructions.
4924 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4925   return getInsertVINSERTImmediate(N, 128);
4926 }
4927
4928 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4929 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4930 /// and VINSERTI64x4 instructions.
4931 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4932   return getInsertVINSERTImmediate(N, 256);
4933 }
4934
4935 /// isZero - Returns true if Elt is a constant integer zero
4936 static bool isZero(SDValue V) {
4937   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4938   return C && C->isNullValue();
4939 }
4940
4941 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4942 /// constant +0.0.
4943 bool X86::isZeroNode(SDValue Elt) {
4944   if (isZero(Elt))
4945     return true;
4946   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4947     return CFP->getValueAPF().isPosZero();
4948   return false;
4949 }
4950
4951 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4952 /// match movhlps. The lower half elements should come from upper half of
4953 /// V1 (and in order), and the upper half elements should come from the upper
4954 /// half of V2 (and in order).
4955 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4956   if (!VT.is128BitVector())
4957     return false;
4958   if (VT.getVectorNumElements() != 4)
4959     return false;
4960   for (unsigned i = 0, e = 2; i != e; ++i)
4961     if (!isUndefOrEqual(Mask[i], i+2))
4962       return false;
4963   for (unsigned i = 2; i != 4; ++i)
4964     if (!isUndefOrEqual(Mask[i], i+4))
4965       return false;
4966   return true;
4967 }
4968
4969 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4970 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4971 /// required.
4972 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4973   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4974     return false;
4975   N = N->getOperand(0).getNode();
4976   if (!ISD::isNON_EXTLoad(N))
4977     return false;
4978   if (LD)
4979     *LD = cast<LoadSDNode>(N);
4980   return true;
4981 }
4982
4983 // Test whether the given value is a vector value which will be legalized
4984 // into a load.
4985 static bool WillBeConstantPoolLoad(SDNode *N) {
4986   if (N->getOpcode() != ISD::BUILD_VECTOR)
4987     return false;
4988
4989   // Check for any non-constant elements.
4990   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4991     switch (N->getOperand(i).getNode()->getOpcode()) {
4992     case ISD::UNDEF:
4993     case ISD::ConstantFP:
4994     case ISD::Constant:
4995       break;
4996     default:
4997       return false;
4998     }
4999
5000   // Vectors of all-zeros and all-ones are materialized with special
5001   // instructions rather than being loaded.
5002   return !ISD::isBuildVectorAllZeros(N) &&
5003          !ISD::isBuildVectorAllOnes(N);
5004 }
5005
5006 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5007 /// match movlp{s|d}. The lower half elements should come from lower half of
5008 /// V1 (and in order), and the upper half elements should come from the upper
5009 /// half of V2 (and in order). And since V1 will become the source of the
5010 /// MOVLP, it must be either a vector load or a scalar load to vector.
5011 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5012                                ArrayRef<int> Mask, MVT VT) {
5013   if (!VT.is128BitVector())
5014     return false;
5015
5016   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5017     return false;
5018   // Is V2 is a vector load, don't do this transformation. We will try to use
5019   // load folding shufps op.
5020   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5021     return false;
5022
5023   unsigned NumElems = VT.getVectorNumElements();
5024
5025   if (NumElems != 2 && NumElems != 4)
5026     return false;
5027   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5028     if (!isUndefOrEqual(Mask[i], i))
5029       return false;
5030   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5031     if (!isUndefOrEqual(Mask[i], i+NumElems))
5032       return false;
5033   return true;
5034 }
5035
5036 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5037 /// to an zero vector.
5038 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5039 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5040   SDValue V1 = N->getOperand(0);
5041   SDValue V2 = N->getOperand(1);
5042   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5043   for (unsigned i = 0; i != NumElems; ++i) {
5044     int Idx = N->getMaskElt(i);
5045     if (Idx >= (int)NumElems) {
5046       unsigned Opc = V2.getOpcode();
5047       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5048         continue;
5049       if (Opc != ISD::BUILD_VECTOR ||
5050           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5051         return false;
5052     } else if (Idx >= 0) {
5053       unsigned Opc = V1.getOpcode();
5054       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5055         continue;
5056       if (Opc != ISD::BUILD_VECTOR ||
5057           !X86::isZeroNode(V1.getOperand(Idx)))
5058         return false;
5059     }
5060   }
5061   return true;
5062 }
5063
5064 /// getZeroVector - Returns a vector of specified type with all zero elements.
5065 ///
5066 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5067                              SelectionDAG &DAG, SDLoc dl) {
5068   assert(VT.isVector() && "Expected a vector type");
5069
5070   // Always build SSE zero vectors as <4 x i32> bitcasted
5071   // to their dest type. This ensures they get CSE'd.
5072   SDValue Vec;
5073   if (VT.is128BitVector()) {  // SSE
5074     if (Subtarget->hasSSE2()) {  // SSE2
5075       SDValue Cst = DAG.getConstant(0, MVT::i32);
5076       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5077     } else { // SSE1
5078       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5079       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5080     }
5081   } else if (VT.is256BitVector()) { // AVX
5082     if (Subtarget->hasInt256()) { // AVX2
5083       SDValue Cst = DAG.getConstant(0, MVT::i32);
5084       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5085       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5086     } else {
5087       // 256-bit logic and arithmetic instructions in AVX are all
5088       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5089       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
5090       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5091       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5092     }
5093   } else if (VT.is512BitVector()) { // AVX-512
5094       SDValue Cst = DAG.getConstant(0, MVT::i32);
5095       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5096                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5097       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5098   } else if (VT.getScalarType() == MVT::i1) {
5099     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5100     SDValue Cst = DAG.getConstant(0, MVT::i1);
5101     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5102     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5103   } else
5104     llvm_unreachable("Unexpected vector type");
5105
5106   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5107 }
5108
5109 /// getOnesVector - Returns a vector of specified type with all bits set.
5110 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5111 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5112 /// Then bitcast to their original type, ensuring they get CSE'd.
5113 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5114                              SDLoc dl) {
5115   assert(VT.isVector() && "Expected a vector type");
5116
5117   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
5118   SDValue Vec;
5119   if (VT.is256BitVector()) {
5120     if (HasInt256) { // AVX2
5121       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5122       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5123     } else { // AVX
5124       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5125       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5126     }
5127   } else if (VT.is128BitVector()) {
5128     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5129   } else
5130     llvm_unreachable("Unexpected vector type");
5131
5132   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5133 }
5134
5135 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5136 /// that point to V2 points to its first element.
5137 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5138   for (unsigned i = 0; i != NumElems; ++i) {
5139     if (Mask[i] > (int)NumElems) {
5140       Mask[i] = NumElems;
5141     }
5142   }
5143 }
5144
5145 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5146 /// operation of specified width.
5147 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5148                        SDValue V2) {
5149   unsigned NumElems = VT.getVectorNumElements();
5150   SmallVector<int, 8> Mask;
5151   Mask.push_back(NumElems);
5152   for (unsigned i = 1; i != NumElems; ++i)
5153     Mask.push_back(i);
5154   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5155 }
5156
5157 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5158 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5159                           SDValue V2) {
5160   unsigned NumElems = VT.getVectorNumElements();
5161   SmallVector<int, 8> Mask;
5162   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5163     Mask.push_back(i);
5164     Mask.push_back(i + NumElems);
5165   }
5166   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5167 }
5168
5169 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5170 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5171                           SDValue V2) {
5172   unsigned NumElems = VT.getVectorNumElements();
5173   SmallVector<int, 8> Mask;
5174   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5175     Mask.push_back(i + Half);
5176     Mask.push_back(i + NumElems + Half);
5177   }
5178   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5179 }
5180
5181 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5182 // a generic shuffle instruction because the target has no such instructions.
5183 // Generate shuffles which repeat i16 and i8 several times until they can be
5184 // represented by v4f32 and then be manipulated by target suported shuffles.
5185 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5186   MVT VT = V.getSimpleValueType();
5187   int NumElems = VT.getVectorNumElements();
5188   SDLoc dl(V);
5189
5190   while (NumElems > 4) {
5191     if (EltNo < NumElems/2) {
5192       V = getUnpackl(DAG, dl, VT, V, V);
5193     } else {
5194       V = getUnpackh(DAG, dl, VT, V, V);
5195       EltNo -= NumElems/2;
5196     }
5197     NumElems >>= 1;
5198   }
5199   return V;
5200 }
5201
5202 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5203 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5204   MVT VT = V.getSimpleValueType();
5205   SDLoc dl(V);
5206
5207   if (VT.is128BitVector()) {
5208     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5209     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5210     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5211                              &SplatMask[0]);
5212   } else if (VT.is256BitVector()) {
5213     // To use VPERMILPS to splat scalars, the second half of indicies must
5214     // refer to the higher part, which is a duplication of the lower one,
5215     // because VPERMILPS can only handle in-lane permutations.
5216     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5217                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5218
5219     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5220     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5221                              &SplatMask[0]);
5222   } else
5223     llvm_unreachable("Vector size not supported");
5224
5225   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5226 }
5227
5228 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5229 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5230   MVT SrcVT = SV->getSimpleValueType(0);
5231   SDValue V1 = SV->getOperand(0);
5232   SDLoc dl(SV);
5233
5234   int EltNo = SV->getSplatIndex();
5235   int NumElems = SrcVT.getVectorNumElements();
5236   bool Is256BitVec = SrcVT.is256BitVector();
5237
5238   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5239          "Unknown how to promote splat for type");
5240
5241   // Extract the 128-bit part containing the splat element and update
5242   // the splat element index when it refers to the higher register.
5243   if (Is256BitVec) {
5244     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5245     if (EltNo >= NumElems/2)
5246       EltNo -= NumElems/2;
5247   }
5248
5249   // All i16 and i8 vector types can't be used directly by a generic shuffle
5250   // instruction because the target has no such instruction. Generate shuffles
5251   // which repeat i16 and i8 several times until they fit in i32, and then can
5252   // be manipulated by target suported shuffles.
5253   MVT EltVT = SrcVT.getVectorElementType();
5254   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5255     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5256
5257   // Recreate the 256-bit vector and place the same 128-bit vector
5258   // into the low and high part. This is necessary because we want
5259   // to use VPERM* to shuffle the vectors
5260   if (Is256BitVec) {
5261     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5262   }
5263
5264   return getLegalSplat(DAG, V1, EltNo);
5265 }
5266
5267 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5268 /// vector of zero or undef vector.  This produces a shuffle where the low
5269 /// element of V2 is swizzled into the zero/undef vector, landing at element
5270 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5271 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5272                                            bool IsZero,
5273                                            const X86Subtarget *Subtarget,
5274                                            SelectionDAG &DAG) {
5275   MVT VT = V2.getSimpleValueType();
5276   SDValue V1 = IsZero
5277     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5278   unsigned NumElems = VT.getVectorNumElements();
5279   SmallVector<int, 16> MaskVec;
5280   for (unsigned i = 0; i != NumElems; ++i)
5281     // If this is the insertion idx, put the low elt of V2 here.
5282     MaskVec.push_back(i == Idx ? NumElems : i);
5283   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5284 }
5285
5286 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5287 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5288 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5289 /// shuffles which use a single input multiple times, and in those cases it will
5290 /// adjust the mask to only have indices within that single input.
5291 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5292                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5293   unsigned NumElems = VT.getVectorNumElements();
5294   SDValue ImmN;
5295
5296   IsUnary = false;
5297   bool IsFakeUnary = false;
5298   switch(N->getOpcode()) {
5299   case X86ISD::BLENDI:
5300     ImmN = N->getOperand(N->getNumOperands()-1);
5301     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5302     break;
5303   case X86ISD::SHUFP:
5304     ImmN = N->getOperand(N->getNumOperands()-1);
5305     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5306     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5307     break;
5308   case X86ISD::UNPCKH:
5309     DecodeUNPCKHMask(VT, Mask);
5310     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5311     break;
5312   case X86ISD::UNPCKL:
5313     DecodeUNPCKLMask(VT, Mask);
5314     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5315     break;
5316   case X86ISD::MOVHLPS:
5317     DecodeMOVHLPSMask(NumElems, Mask);
5318     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5319     break;
5320   case X86ISD::MOVLHPS:
5321     DecodeMOVLHPSMask(NumElems, Mask);
5322     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5323     break;
5324   case X86ISD::PALIGNR:
5325     ImmN = N->getOperand(N->getNumOperands()-1);
5326     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5327     break;
5328   case X86ISD::PSHUFD:
5329   case X86ISD::VPERMILPI:
5330     ImmN = N->getOperand(N->getNumOperands()-1);
5331     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5332     IsUnary = true;
5333     break;
5334   case X86ISD::PSHUFHW:
5335     ImmN = N->getOperand(N->getNumOperands()-1);
5336     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5337     IsUnary = true;
5338     break;
5339   case X86ISD::PSHUFLW:
5340     ImmN = N->getOperand(N->getNumOperands()-1);
5341     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5342     IsUnary = true;
5343     break;
5344   case X86ISD::PSHUFB: {
5345     IsUnary = true;
5346     SDValue MaskNode = N->getOperand(1);
5347     while (MaskNode->getOpcode() == ISD::BITCAST)
5348       MaskNode = MaskNode->getOperand(0);
5349
5350     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5351       // If we have a build-vector, then things are easy.
5352       EVT VT = MaskNode.getValueType();
5353       assert(VT.isVector() &&
5354              "Can't produce a non-vector with a build_vector!");
5355       if (!VT.isInteger())
5356         return false;
5357
5358       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5359
5360       SmallVector<uint64_t, 32> RawMask;
5361       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5362         SDValue Op = MaskNode->getOperand(i);
5363         if (Op->getOpcode() == ISD::UNDEF) {
5364           RawMask.push_back((uint64_t)SM_SentinelUndef);
5365           continue;
5366         }
5367         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5368         if (!CN)
5369           return false;
5370         APInt MaskElement = CN->getAPIntValue();
5371
5372         // We now have to decode the element which could be any integer size and
5373         // extract each byte of it.
5374         for (int j = 0; j < NumBytesPerElement; ++j) {
5375           // Note that this is x86 and so always little endian: the low byte is
5376           // the first byte of the mask.
5377           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5378           MaskElement = MaskElement.lshr(8);
5379         }
5380       }
5381       DecodePSHUFBMask(RawMask, Mask);
5382       break;
5383     }
5384
5385     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5386     if (!MaskLoad)
5387       return false;
5388
5389     SDValue Ptr = MaskLoad->getBasePtr();
5390     if (Ptr->getOpcode() == X86ISD::Wrapper)
5391       Ptr = Ptr->getOperand(0);
5392
5393     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5394     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5395       return false;
5396
5397     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5398       // FIXME: Support AVX-512 here.
5399       Type *Ty = C->getType();
5400       if (!Ty->isVectorTy() || (Ty->getVectorNumElements() != 16 &&
5401                                 Ty->getVectorNumElements() != 32))
5402         return false;
5403
5404       DecodePSHUFBMask(C, Mask);
5405       break;
5406     }
5407
5408     return false;
5409   }
5410   case X86ISD::VPERMI:
5411     ImmN = N->getOperand(N->getNumOperands()-1);
5412     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5413     IsUnary = true;
5414     break;
5415   case X86ISD::MOVSS:
5416   case X86ISD::MOVSD: {
5417     // The index 0 always comes from the first element of the second source,
5418     // this is why MOVSS and MOVSD are used in the first place. The other
5419     // elements come from the other positions of the first source vector
5420     Mask.push_back(NumElems);
5421     for (unsigned i = 1; i != NumElems; ++i) {
5422       Mask.push_back(i);
5423     }
5424     break;
5425   }
5426   case X86ISD::VPERM2X128:
5427     ImmN = N->getOperand(N->getNumOperands()-1);
5428     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5429     if (Mask.empty()) return false;
5430     break;
5431   case X86ISD::MOVSLDUP:
5432     DecodeMOVSLDUPMask(VT, Mask);
5433     break;
5434   case X86ISD::MOVSHDUP:
5435     DecodeMOVSHDUPMask(VT, Mask);
5436     break;
5437   case X86ISD::MOVDDUP:
5438   case X86ISD::MOVLHPD:
5439   case X86ISD::MOVLPD:
5440   case X86ISD::MOVLPS:
5441     // Not yet implemented
5442     return false;
5443   default: llvm_unreachable("unknown target shuffle node");
5444   }
5445
5446   // If we have a fake unary shuffle, the shuffle mask is spread across two
5447   // inputs that are actually the same node. Re-map the mask to always point
5448   // into the first input.
5449   if (IsFakeUnary)
5450     for (int &M : Mask)
5451       if (M >= (int)Mask.size())
5452         M -= Mask.size();
5453
5454   return true;
5455 }
5456
5457 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5458 /// element of the result of the vector shuffle.
5459 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5460                                    unsigned Depth) {
5461   if (Depth == 6)
5462     return SDValue();  // Limit search depth.
5463
5464   SDValue V = SDValue(N, 0);
5465   EVT VT = V.getValueType();
5466   unsigned Opcode = V.getOpcode();
5467
5468   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5469   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5470     int Elt = SV->getMaskElt(Index);
5471
5472     if (Elt < 0)
5473       return DAG.getUNDEF(VT.getVectorElementType());
5474
5475     unsigned NumElems = VT.getVectorNumElements();
5476     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5477                                          : SV->getOperand(1);
5478     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5479   }
5480
5481   // Recurse into target specific vector shuffles to find scalars.
5482   if (isTargetShuffle(Opcode)) {
5483     MVT ShufVT = V.getSimpleValueType();
5484     unsigned NumElems = ShufVT.getVectorNumElements();
5485     SmallVector<int, 16> ShuffleMask;
5486     bool IsUnary;
5487
5488     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5489       return SDValue();
5490
5491     int Elt = ShuffleMask[Index];
5492     if (Elt < 0)
5493       return DAG.getUNDEF(ShufVT.getVectorElementType());
5494
5495     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5496                                          : N->getOperand(1);
5497     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5498                                Depth+1);
5499   }
5500
5501   // Actual nodes that may contain scalar elements
5502   if (Opcode == ISD::BITCAST) {
5503     V = V.getOperand(0);
5504     EVT SrcVT = V.getValueType();
5505     unsigned NumElems = VT.getVectorNumElements();
5506
5507     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5508       return SDValue();
5509   }
5510
5511   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5512     return (Index == 0) ? V.getOperand(0)
5513                         : DAG.getUNDEF(VT.getVectorElementType());
5514
5515   if (V.getOpcode() == ISD::BUILD_VECTOR)
5516     return V.getOperand(Index);
5517
5518   return SDValue();
5519 }
5520
5521 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5522 /// shuffle operation which come from a consecutively from a zero. The
5523 /// search can start in two different directions, from left or right.
5524 /// We count undefs as zeros until PreferredNum is reached.
5525 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5526                                          unsigned NumElems, bool ZerosFromLeft,
5527                                          SelectionDAG &DAG,
5528                                          unsigned PreferredNum = -1U) {
5529   unsigned NumZeros = 0;
5530   for (unsigned i = 0; i != NumElems; ++i) {
5531     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5532     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5533     if (!Elt.getNode())
5534       break;
5535
5536     if (X86::isZeroNode(Elt))
5537       ++NumZeros;
5538     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5539       NumZeros = std::min(NumZeros + 1, PreferredNum);
5540     else
5541       break;
5542   }
5543
5544   return NumZeros;
5545 }
5546
5547 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5548 /// correspond consecutively to elements from one of the vector operands,
5549 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5550 static
5551 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5552                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5553                               unsigned NumElems, unsigned &OpNum) {
5554   bool SeenV1 = false;
5555   bool SeenV2 = false;
5556
5557   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5558     int Idx = SVOp->getMaskElt(i);
5559     // Ignore undef indicies
5560     if (Idx < 0)
5561       continue;
5562
5563     if (Idx < (int)NumElems)
5564       SeenV1 = true;
5565     else
5566       SeenV2 = true;
5567
5568     // Only accept consecutive elements from the same vector
5569     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5570       return false;
5571   }
5572
5573   OpNum = SeenV1 ? 0 : 1;
5574   return true;
5575 }
5576
5577 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5578 /// logical left shift of a vector.
5579 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5580                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5581   unsigned NumElems =
5582     SVOp->getSimpleValueType(0).getVectorNumElements();
5583   unsigned NumZeros = getNumOfConsecutiveZeros(
5584       SVOp, NumElems, false /* check zeros from right */, DAG,
5585       SVOp->getMaskElt(0));
5586   unsigned OpSrc;
5587
5588   if (!NumZeros)
5589     return false;
5590
5591   // Considering the elements in the mask that are not consecutive zeros,
5592   // check if they consecutively come from only one of the source vectors.
5593   //
5594   //               V1 = {X, A, B, C}     0
5595   //                         \  \  \    /
5596   //   vector_shuffle V1, V2 <1, 2, 3, X>
5597   //
5598   if (!isShuffleMaskConsecutive(SVOp,
5599             0,                   // Mask Start Index
5600             NumElems-NumZeros,   // Mask End Index(exclusive)
5601             NumZeros,            // Where to start looking in the src vector
5602             NumElems,            // Number of elements in vector
5603             OpSrc))              // Which source operand ?
5604     return false;
5605
5606   isLeft = false;
5607   ShAmt = NumZeros;
5608   ShVal = SVOp->getOperand(OpSrc);
5609   return true;
5610 }
5611
5612 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5613 /// logical left shift of a vector.
5614 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5615                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5616   unsigned NumElems =
5617     SVOp->getSimpleValueType(0).getVectorNumElements();
5618   unsigned NumZeros = getNumOfConsecutiveZeros(
5619       SVOp, NumElems, true /* check zeros from left */, DAG,
5620       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5621   unsigned OpSrc;
5622
5623   if (!NumZeros)
5624     return false;
5625
5626   // Considering the elements in the mask that are not consecutive zeros,
5627   // check if they consecutively come from only one of the source vectors.
5628   //
5629   //                           0    { A, B, X, X } = V2
5630   //                          / \    /  /
5631   //   vector_shuffle V1, V2 <X, X, 4, 5>
5632   //
5633   if (!isShuffleMaskConsecutive(SVOp,
5634             NumZeros,     // Mask Start Index
5635             NumElems,     // Mask End Index(exclusive)
5636             0,            // Where to start looking in the src vector
5637             NumElems,     // Number of elements in vector
5638             OpSrc))       // Which source operand ?
5639     return false;
5640
5641   isLeft = true;
5642   ShAmt = NumZeros;
5643   ShVal = SVOp->getOperand(OpSrc);
5644   return true;
5645 }
5646
5647 /// isVectorShift - Returns true if the shuffle can be implemented as a
5648 /// logical left or right shift of a vector.
5649 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5650                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5651   // Although the logic below support any bitwidth size, there are no
5652   // shift instructions which handle more than 128-bit vectors.
5653   if (!SVOp->getSimpleValueType(0).is128BitVector())
5654     return false;
5655
5656   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5657       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5658     return true;
5659
5660   return false;
5661 }
5662
5663 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5664 ///
5665 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5666                                        unsigned NumNonZero, unsigned NumZero,
5667                                        SelectionDAG &DAG,
5668                                        const X86Subtarget* Subtarget,
5669                                        const TargetLowering &TLI) {
5670   if (NumNonZero > 8)
5671     return SDValue();
5672
5673   SDLoc dl(Op);
5674   SDValue V;
5675   bool First = true;
5676   for (unsigned i = 0; i < 16; ++i) {
5677     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5678     if (ThisIsNonZero && First) {
5679       if (NumZero)
5680         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5681       else
5682         V = DAG.getUNDEF(MVT::v8i16);
5683       First = false;
5684     }
5685
5686     if ((i & 1) != 0) {
5687       SDValue ThisElt, LastElt;
5688       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5689       if (LastIsNonZero) {
5690         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5691                               MVT::i16, Op.getOperand(i-1));
5692       }
5693       if (ThisIsNonZero) {
5694         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5695         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5696                               ThisElt, DAG.getConstant(8, MVT::i8));
5697         if (LastIsNonZero)
5698           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5699       } else
5700         ThisElt = LastElt;
5701
5702       if (ThisElt.getNode())
5703         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5704                         DAG.getIntPtrConstant(i/2));
5705     }
5706   }
5707
5708   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5709 }
5710
5711 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5712 ///
5713 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5714                                      unsigned NumNonZero, unsigned NumZero,
5715                                      SelectionDAG &DAG,
5716                                      const X86Subtarget* Subtarget,
5717                                      const TargetLowering &TLI) {
5718   if (NumNonZero > 4)
5719     return SDValue();
5720
5721   SDLoc dl(Op);
5722   SDValue V;
5723   bool First = true;
5724   for (unsigned i = 0; i < 8; ++i) {
5725     bool isNonZero = (NonZeros & (1 << i)) != 0;
5726     if (isNonZero) {
5727       if (First) {
5728         if (NumZero)
5729           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5730         else
5731           V = DAG.getUNDEF(MVT::v8i16);
5732         First = false;
5733       }
5734       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5735                       MVT::v8i16, V, Op.getOperand(i),
5736                       DAG.getIntPtrConstant(i));
5737     }
5738   }
5739
5740   return V;
5741 }
5742
5743 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5744 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5745                                      const X86Subtarget *Subtarget,
5746                                      const TargetLowering &TLI) {
5747   // Find all zeroable elements.
5748   bool Zeroable[4];
5749   for (int i=0; i < 4; ++i) {
5750     SDValue Elt = Op->getOperand(i);
5751     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5752   }
5753   assert(std::count_if(&Zeroable[0], &Zeroable[4],
5754                        [](bool M) { return !M; }) > 1 &&
5755          "We expect at least two non-zero elements!");
5756
5757   // We only know how to deal with build_vector nodes where elements are either
5758   // zeroable or extract_vector_elt with constant index.
5759   SDValue FirstNonZero;
5760   unsigned FirstNonZeroIdx;
5761   for (unsigned i=0; i < 4; ++i) {
5762     if (Zeroable[i])
5763       continue;
5764     SDValue Elt = Op->getOperand(i);
5765     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5766         !isa<ConstantSDNode>(Elt.getOperand(1)))
5767       return SDValue();
5768     // Make sure that this node is extracting from a 128-bit vector.
5769     MVT VT = Elt.getOperand(0).getSimpleValueType();
5770     if (!VT.is128BitVector())
5771       return SDValue();
5772     if (!FirstNonZero.getNode()) {
5773       FirstNonZero = Elt;
5774       FirstNonZeroIdx = i;
5775     }
5776   }
5777
5778   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5779   SDValue V1 = FirstNonZero.getOperand(0);
5780   MVT VT = V1.getSimpleValueType();
5781
5782   // See if this build_vector can be lowered as a blend with zero.
5783   SDValue Elt;
5784   unsigned EltMaskIdx, EltIdx;
5785   int Mask[4];
5786   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5787     if (Zeroable[EltIdx]) {
5788       // The zero vector will be on the right hand side.
5789       Mask[EltIdx] = EltIdx+4;
5790       continue;
5791     }
5792
5793     Elt = Op->getOperand(EltIdx);
5794     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5795     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5796     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5797       break;
5798     Mask[EltIdx] = EltIdx;
5799   }
5800
5801   if (EltIdx == 4) {
5802     // Let the shuffle legalizer deal with blend operations.
5803     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5804     if (V1.getSimpleValueType() != VT)
5805       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5806     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5807   }
5808
5809   // See if we can lower this build_vector to a INSERTPS.
5810   if (!Subtarget->hasSSE41())
5811     return SDValue();
5812
5813   SDValue V2 = Elt.getOperand(0);
5814   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5815     V1 = SDValue();
5816
5817   bool CanFold = true;
5818   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5819     if (Zeroable[i])
5820       continue;
5821     
5822     SDValue Current = Op->getOperand(i);
5823     SDValue SrcVector = Current->getOperand(0);
5824     if (!V1.getNode())
5825       V1 = SrcVector;
5826     CanFold = SrcVector == V1 &&
5827       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5828   }
5829
5830   if (!CanFold)
5831     return SDValue();
5832
5833   assert(V1.getNode() && "Expected at least two non-zero elements!");
5834   if (V1.getSimpleValueType() != MVT::v4f32)
5835     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5836   if (V2.getSimpleValueType() != MVT::v4f32)
5837     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5838
5839   // Ok, we can emit an INSERTPS instruction.
5840   unsigned ZMask = 0;
5841   for (int i = 0; i < 4; ++i)
5842     if (Zeroable[i])
5843       ZMask |= 1 << i;
5844
5845   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5846   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5847   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
5848                                DAG.getIntPtrConstant(InsertPSMask));
5849   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
5850 }
5851
5852 /// getVShift - Return a vector logical shift node.
5853 ///
5854 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5855                          unsigned NumBits, SelectionDAG &DAG,
5856                          const TargetLowering &TLI, SDLoc dl) {
5857   assert(VT.is128BitVector() && "Unknown type for VShift");
5858   EVT ShVT = MVT::v2i64;
5859   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5860   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5861   return DAG.getNode(ISD::BITCAST, dl, VT,
5862                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5863                              DAG.getConstant(NumBits,
5864                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5865 }
5866
5867 static SDValue
5868 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5869
5870   // Check if the scalar load can be widened into a vector load. And if
5871   // the address is "base + cst" see if the cst can be "absorbed" into
5872   // the shuffle mask.
5873   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5874     SDValue Ptr = LD->getBasePtr();
5875     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5876       return SDValue();
5877     EVT PVT = LD->getValueType(0);
5878     if (PVT != MVT::i32 && PVT != MVT::f32)
5879       return SDValue();
5880
5881     int FI = -1;
5882     int64_t Offset = 0;
5883     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5884       FI = FINode->getIndex();
5885       Offset = 0;
5886     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5887                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5888       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5889       Offset = Ptr.getConstantOperandVal(1);
5890       Ptr = Ptr.getOperand(0);
5891     } else {
5892       return SDValue();
5893     }
5894
5895     // FIXME: 256-bit vector instructions don't require a strict alignment,
5896     // improve this code to support it better.
5897     unsigned RequiredAlign = VT.getSizeInBits()/8;
5898     SDValue Chain = LD->getChain();
5899     // Make sure the stack object alignment is at least 16 or 32.
5900     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5901     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5902       if (MFI->isFixedObjectIndex(FI)) {
5903         // Can't change the alignment. FIXME: It's possible to compute
5904         // the exact stack offset and reference FI + adjust offset instead.
5905         // If someone *really* cares about this. That's the way to implement it.
5906         return SDValue();
5907       } else {
5908         MFI->setObjectAlignment(FI, RequiredAlign);
5909       }
5910     }
5911
5912     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5913     // Ptr + (Offset & ~15).
5914     if (Offset < 0)
5915       return SDValue();
5916     if ((Offset % RequiredAlign) & 3)
5917       return SDValue();
5918     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5919     if (StartOffset)
5920       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5921                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5922
5923     int EltNo = (Offset - StartOffset) >> 2;
5924     unsigned NumElems = VT.getVectorNumElements();
5925
5926     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5927     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5928                              LD->getPointerInfo().getWithOffset(StartOffset),
5929                              false, false, false, 0);
5930
5931     SmallVector<int, 8> Mask;
5932     for (unsigned i = 0; i != NumElems; ++i)
5933       Mask.push_back(EltNo);
5934
5935     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5936   }
5937
5938   return SDValue();
5939 }
5940
5941 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5942 /// vector of type 'VT', see if the elements can be replaced by a single large
5943 /// load which has the same value as a build_vector whose operands are 'elts'.
5944 ///
5945 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5946 ///
5947 /// FIXME: we'd also like to handle the case where the last elements are zero
5948 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5949 /// There's even a handy isZeroNode for that purpose.
5950 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5951                                         SDLoc &DL, SelectionDAG &DAG,
5952                                         bool isAfterLegalize) {
5953   EVT EltVT = VT.getVectorElementType();
5954   unsigned NumElems = Elts.size();
5955
5956   LoadSDNode *LDBase = nullptr;
5957   unsigned LastLoadedElt = -1U;
5958
5959   // For each element in the initializer, see if we've found a load or an undef.
5960   // If we don't find an initial load element, or later load elements are
5961   // non-consecutive, bail out.
5962   for (unsigned i = 0; i < NumElems; ++i) {
5963     SDValue Elt = Elts[i];
5964
5965     if (!Elt.getNode() ||
5966         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5967       return SDValue();
5968     if (!LDBase) {
5969       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5970         return SDValue();
5971       LDBase = cast<LoadSDNode>(Elt.getNode());
5972       LastLoadedElt = i;
5973       continue;
5974     }
5975     if (Elt.getOpcode() == ISD::UNDEF)
5976       continue;
5977
5978     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5979     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5980       return SDValue();
5981     LastLoadedElt = i;
5982   }
5983
5984   // If we have found an entire vector of loads and undefs, then return a large
5985   // load of the entire vector width starting at the base pointer.  If we found
5986   // consecutive loads for the low half, generate a vzext_load node.
5987   if (LastLoadedElt == NumElems - 1) {
5988
5989     if (isAfterLegalize &&
5990         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5991       return SDValue();
5992
5993     SDValue NewLd = SDValue();
5994
5995     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5996       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5997                           LDBase->getPointerInfo(),
5998                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5999                           LDBase->isInvariant(), 0);
6000     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6001                         LDBase->getPointerInfo(),
6002                         LDBase->isVolatile(), LDBase->isNonTemporal(),
6003                         LDBase->isInvariant(), LDBase->getAlignment());
6004
6005     if (LDBase->hasAnyUseOfValue(1)) {
6006       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6007                                      SDValue(LDBase, 1),
6008                                      SDValue(NewLd.getNode(), 1));
6009       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6010       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6011                              SDValue(NewLd.getNode(), 1));
6012     }
6013
6014     return NewLd;
6015   }
6016   if (NumElems == 4 && LastLoadedElt == 1 &&
6017       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
6018     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
6019     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
6020     SDValue ResNode =
6021         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
6022                                 LDBase->getPointerInfo(),
6023                                 LDBase->getAlignment(),
6024                                 false/*isVolatile*/, true/*ReadMem*/,
6025                                 false/*WriteMem*/);
6026
6027     // Make sure the newly-created LOAD is in the same position as LDBase in
6028     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
6029     // update uses of LDBase's output chain to use the TokenFactor.
6030     if (LDBase->hasAnyUseOfValue(1)) {
6031       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
6032                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
6033       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
6034       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
6035                              SDValue(ResNode.getNode(), 1));
6036     }
6037
6038     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
6039   }
6040   return SDValue();
6041 }
6042
6043 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6044 /// to generate a splat value for the following cases:
6045 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6046 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6047 /// a scalar load, or a constant.
6048 /// The VBROADCAST node is returned when a pattern is found,
6049 /// or SDValue() otherwise.
6050 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6051                                     SelectionDAG &DAG) {
6052   // VBROADCAST requires AVX.
6053   // TODO: Splats could be generated for non-AVX CPUs using SSE
6054   // instructions, but there's less potential gain for only 128-bit vectors.
6055   if (!Subtarget->hasAVX())
6056     return SDValue();
6057
6058   MVT VT = Op.getSimpleValueType();
6059   SDLoc dl(Op);
6060
6061   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6062          "Unsupported vector type for broadcast.");
6063
6064   SDValue Ld;
6065   bool ConstSplatVal;
6066
6067   switch (Op.getOpcode()) {
6068     default:
6069       // Unknown pattern found.
6070       return SDValue();
6071
6072     case ISD::BUILD_VECTOR: {
6073       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6074       BitVector UndefElements;
6075       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6076
6077       // We need a splat of a single value to use broadcast, and it doesn't
6078       // make any sense if the value is only in one element of the vector.
6079       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6080         return SDValue();
6081
6082       Ld = Splat;
6083       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6084                        Ld.getOpcode() == ISD::ConstantFP);
6085
6086       // Make sure that all of the users of a non-constant load are from the
6087       // BUILD_VECTOR node.
6088       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6089         return SDValue();
6090       break;
6091     }
6092
6093     case ISD::VECTOR_SHUFFLE: {
6094       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6095
6096       // Shuffles must have a splat mask where the first element is
6097       // broadcasted.
6098       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6099         return SDValue();
6100
6101       SDValue Sc = Op.getOperand(0);
6102       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6103           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6104
6105         if (!Subtarget->hasInt256())
6106           return SDValue();
6107
6108         // Use the register form of the broadcast instruction available on AVX2.
6109         if (VT.getSizeInBits() >= 256)
6110           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6111         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6112       }
6113
6114       Ld = Sc.getOperand(0);
6115       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6116                        Ld.getOpcode() == ISD::ConstantFP);
6117
6118       // The scalar_to_vector node and the suspected
6119       // load node must have exactly one user.
6120       // Constants may have multiple users.
6121
6122       // AVX-512 has register version of the broadcast
6123       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6124         Ld.getValueType().getSizeInBits() >= 32;
6125       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6126           !hasRegVer))
6127         return SDValue();
6128       break;
6129     }
6130   }
6131
6132   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6133   bool IsGE256 = (VT.getSizeInBits() >= 256);
6134
6135   // When optimizing for size, generate up to 5 extra bytes for a broadcast
6136   // instruction to save 8 or more bytes of constant pool data.
6137   // TODO: If multiple splats are generated to load the same constant,
6138   // it may be detrimental to overall size. There needs to be a way to detect
6139   // that condition to know if this is truly a size win.
6140   const Function *F = DAG.getMachineFunction().getFunction();
6141   bool OptForSize = F->getAttributes().
6142     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6143
6144   // Handle broadcasting a single constant scalar from the constant pool
6145   // into a vector.
6146   // On Sandybridge (no AVX2), it is still better to load a constant vector
6147   // from the constant pool and not to broadcast it from a scalar.
6148   // But override that restriction when optimizing for size.
6149   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6150   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6151     EVT CVT = Ld.getValueType();
6152     assert(!CVT.isVector() && "Must not broadcast a vector type");
6153
6154     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6155     // For size optimization, also splat v2f64 and v2i64, and for size opt
6156     // with AVX2, also splat i8 and i16.
6157     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6158     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6159         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6160       const Constant *C = nullptr;
6161       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6162         C = CI->getConstantIntValue();
6163       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6164         C = CF->getConstantFPValue();
6165
6166       assert(C && "Invalid constant type");
6167
6168       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6169       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6170       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6171       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6172                        MachinePointerInfo::getConstantPool(),
6173                        false, false, false, Alignment);
6174
6175       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6176     }
6177   }
6178
6179   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6180
6181   // Handle AVX2 in-register broadcasts.
6182   if (!IsLoad && Subtarget->hasInt256() &&
6183       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6184     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6185
6186   // The scalar source must be a normal load.
6187   if (!IsLoad)
6188     return SDValue();
6189
6190   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6191     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6192
6193   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6194   // double since there is no vbroadcastsd xmm
6195   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6196     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6197       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6198   }
6199
6200   // Unsupported broadcast.
6201   return SDValue();
6202 }
6203
6204 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6205 /// underlying vector and index.
6206 ///
6207 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6208 /// index.
6209 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6210                                          SDValue ExtIdx) {
6211   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6212   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6213     return Idx;
6214
6215   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6216   // lowered this:
6217   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6218   // to:
6219   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6220   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6221   //                           undef)
6222   //                       Constant<0>)
6223   // In this case the vector is the extract_subvector expression and the index
6224   // is 2, as specified by the shuffle.
6225   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6226   SDValue ShuffleVec = SVOp->getOperand(0);
6227   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6228   assert(ShuffleVecVT.getVectorElementType() ==
6229          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6230
6231   int ShuffleIdx = SVOp->getMaskElt(Idx);
6232   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6233     ExtractedFromVec = ShuffleVec;
6234     return ShuffleIdx;
6235   }
6236   return Idx;
6237 }
6238
6239 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6240   MVT VT = Op.getSimpleValueType();
6241
6242   // Skip if insert_vec_elt is not supported.
6243   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6244   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6245     return SDValue();
6246
6247   SDLoc DL(Op);
6248   unsigned NumElems = Op.getNumOperands();
6249
6250   SDValue VecIn1;
6251   SDValue VecIn2;
6252   SmallVector<unsigned, 4> InsertIndices;
6253   SmallVector<int, 8> Mask(NumElems, -1);
6254
6255   for (unsigned i = 0; i != NumElems; ++i) {
6256     unsigned Opc = Op.getOperand(i).getOpcode();
6257
6258     if (Opc == ISD::UNDEF)
6259       continue;
6260
6261     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6262       // Quit if more than 1 elements need inserting.
6263       if (InsertIndices.size() > 1)
6264         return SDValue();
6265
6266       InsertIndices.push_back(i);
6267       continue;
6268     }
6269
6270     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6271     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6272     // Quit if non-constant index.
6273     if (!isa<ConstantSDNode>(ExtIdx))
6274       return SDValue();
6275     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6276
6277     // Quit if extracted from vector of different type.
6278     if (ExtractedFromVec.getValueType() != VT)
6279       return SDValue();
6280
6281     if (!VecIn1.getNode())
6282       VecIn1 = ExtractedFromVec;
6283     else if (VecIn1 != ExtractedFromVec) {
6284       if (!VecIn2.getNode())
6285         VecIn2 = ExtractedFromVec;
6286       else if (VecIn2 != ExtractedFromVec)
6287         // Quit if more than 2 vectors to shuffle
6288         return SDValue();
6289     }
6290
6291     if (ExtractedFromVec == VecIn1)
6292       Mask[i] = Idx;
6293     else if (ExtractedFromVec == VecIn2)
6294       Mask[i] = Idx + NumElems;
6295   }
6296
6297   if (!VecIn1.getNode())
6298     return SDValue();
6299
6300   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6301   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6302   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6303     unsigned Idx = InsertIndices[i];
6304     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6305                      DAG.getIntPtrConstant(Idx));
6306   }
6307
6308   return NV;
6309 }
6310
6311 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6312 SDValue
6313 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6314
6315   MVT VT = Op.getSimpleValueType();
6316   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6317          "Unexpected type in LowerBUILD_VECTORvXi1!");
6318
6319   SDLoc dl(Op);
6320   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6321     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6322     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6323     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6324   }
6325
6326   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6327     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6328     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6329     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6330   }
6331
6332   bool AllContants = true;
6333   uint64_t Immediate = 0;
6334   int NonConstIdx = -1;
6335   bool IsSplat = true;
6336   unsigned NumNonConsts = 0;
6337   unsigned NumConsts = 0;
6338   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6339     SDValue In = Op.getOperand(idx);
6340     if (In.getOpcode() == ISD::UNDEF)
6341       continue;
6342     if (!isa<ConstantSDNode>(In)) {
6343       AllContants = false;
6344       NonConstIdx = idx;
6345       NumNonConsts++;
6346     }
6347     else {
6348       NumConsts++;
6349       if (cast<ConstantSDNode>(In)->getZExtValue())
6350       Immediate |= (1ULL << idx);
6351     }
6352     if (In != Op.getOperand(0))
6353       IsSplat = false;
6354   }
6355
6356   if (AllContants) {
6357     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6358       DAG.getConstant(Immediate, MVT::i16));
6359     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6360                        DAG.getIntPtrConstant(0));
6361   }
6362
6363   if (NumNonConsts == 1 && NonConstIdx != 0) {
6364     SDValue DstVec;
6365     if (NumConsts) {
6366       SDValue VecAsImm = DAG.getConstant(Immediate,
6367                                          MVT::getIntegerVT(VT.getSizeInBits()));
6368       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6369     }
6370     else 
6371       DstVec = DAG.getUNDEF(VT);
6372     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6373                        Op.getOperand(NonConstIdx),
6374                        DAG.getIntPtrConstant(NonConstIdx));
6375   }
6376   if (!IsSplat && (NonConstIdx != 0))
6377     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6378   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6379   SDValue Select;
6380   if (IsSplat)
6381     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6382                           DAG.getConstant(-1, SelectVT),
6383                           DAG.getConstant(0, SelectVT));
6384   else
6385     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6386                          DAG.getConstant((Immediate | 1), SelectVT),
6387                          DAG.getConstant(Immediate, SelectVT));
6388   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6389 }
6390
6391 /// \brief Return true if \p N implements a horizontal binop and return the
6392 /// operands for the horizontal binop into V0 and V1.
6393 /// 
6394 /// This is a helper function of PerformBUILD_VECTORCombine.
6395 /// This function checks that the build_vector \p N in input implements a
6396 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6397 /// operation to match.
6398 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6399 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6400 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6401 /// arithmetic sub.
6402 ///
6403 /// This function only analyzes elements of \p N whose indices are
6404 /// in range [BaseIdx, LastIdx).
6405 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6406                               SelectionDAG &DAG,
6407                               unsigned BaseIdx, unsigned LastIdx,
6408                               SDValue &V0, SDValue &V1) {
6409   EVT VT = N->getValueType(0);
6410
6411   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6412   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6413          "Invalid Vector in input!");
6414   
6415   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6416   bool CanFold = true;
6417   unsigned ExpectedVExtractIdx = BaseIdx;
6418   unsigned NumElts = LastIdx - BaseIdx;
6419   V0 = DAG.getUNDEF(VT);
6420   V1 = DAG.getUNDEF(VT);
6421
6422   // Check if N implements a horizontal binop.
6423   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6424     SDValue Op = N->getOperand(i + BaseIdx);
6425
6426     // Skip UNDEFs.
6427     if (Op->getOpcode() == ISD::UNDEF) {
6428       // Update the expected vector extract index.
6429       if (i * 2 == NumElts)
6430         ExpectedVExtractIdx = BaseIdx;
6431       ExpectedVExtractIdx += 2;
6432       continue;
6433     }
6434
6435     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6436
6437     if (!CanFold)
6438       break;
6439
6440     SDValue Op0 = Op.getOperand(0);
6441     SDValue Op1 = Op.getOperand(1);
6442
6443     // Try to match the following pattern:
6444     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6445     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6446         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6447         Op0.getOperand(0) == Op1.getOperand(0) &&
6448         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6449         isa<ConstantSDNode>(Op1.getOperand(1)));
6450     if (!CanFold)
6451       break;
6452
6453     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6454     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6455
6456     if (i * 2 < NumElts) {
6457       if (V0.getOpcode() == ISD::UNDEF)
6458         V0 = Op0.getOperand(0);
6459     } else {
6460       if (V1.getOpcode() == ISD::UNDEF)
6461         V1 = Op0.getOperand(0);
6462       if (i * 2 == NumElts)
6463         ExpectedVExtractIdx = BaseIdx;
6464     }
6465
6466     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6467     if (I0 == ExpectedVExtractIdx)
6468       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6469     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6470       // Try to match the following dag sequence:
6471       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6472       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6473     } else
6474       CanFold = false;
6475
6476     ExpectedVExtractIdx += 2;
6477   }
6478
6479   return CanFold;
6480 }
6481
6482 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6483 /// a concat_vector. 
6484 ///
6485 /// This is a helper function of PerformBUILD_VECTORCombine.
6486 /// This function expects two 256-bit vectors called V0 and V1.
6487 /// At first, each vector is split into two separate 128-bit vectors.
6488 /// Then, the resulting 128-bit vectors are used to implement two
6489 /// horizontal binary operations. 
6490 ///
6491 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6492 ///
6493 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6494 /// the two new horizontal binop.
6495 /// When Mode is set, the first horizontal binop dag node would take as input
6496 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6497 /// horizontal binop dag node would take as input the lower 128-bit of V1
6498 /// and the upper 128-bit of V1.
6499 ///   Example:
6500 ///     HADD V0_LO, V0_HI
6501 ///     HADD V1_LO, V1_HI
6502 ///
6503 /// Otherwise, the first horizontal binop dag node takes as input the lower
6504 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6505 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6506 ///   Example:
6507 ///     HADD V0_LO, V1_LO
6508 ///     HADD V0_HI, V1_HI
6509 ///
6510 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6511 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6512 /// the upper 128-bits of the result.
6513 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6514                                      SDLoc DL, SelectionDAG &DAG,
6515                                      unsigned X86Opcode, bool Mode,
6516                                      bool isUndefLO, bool isUndefHI) {
6517   EVT VT = V0.getValueType();
6518   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6519          "Invalid nodes in input!");
6520
6521   unsigned NumElts = VT.getVectorNumElements();
6522   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6523   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6524   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6525   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6526   EVT NewVT = V0_LO.getValueType();
6527
6528   SDValue LO = DAG.getUNDEF(NewVT);
6529   SDValue HI = DAG.getUNDEF(NewVT);
6530
6531   if (Mode) {
6532     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6533     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6534       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6535     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6536       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6537   } else {
6538     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6539     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6540                        V1_LO->getOpcode() != ISD::UNDEF))
6541       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6542
6543     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6544                        V1_HI->getOpcode() != ISD::UNDEF))
6545       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6546   }
6547
6548   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6549 }
6550
6551 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6552 /// sequence of 'vadd + vsub + blendi'.
6553 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6554                            const X86Subtarget *Subtarget) {
6555   SDLoc DL(BV);
6556   EVT VT = BV->getValueType(0);
6557   unsigned NumElts = VT.getVectorNumElements();
6558   SDValue InVec0 = DAG.getUNDEF(VT);
6559   SDValue InVec1 = DAG.getUNDEF(VT);
6560
6561   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6562           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6563
6564   // Odd-numbered elements in the input build vector are obtained from
6565   // adding two integer/float elements.
6566   // Even-numbered elements in the input build vector are obtained from
6567   // subtracting two integer/float elements.
6568   unsigned ExpectedOpcode = ISD::FSUB;
6569   unsigned NextExpectedOpcode = ISD::FADD;
6570   bool AddFound = false;
6571   bool SubFound = false;
6572
6573   for (unsigned i = 0, e = NumElts; i != e; i++) {
6574     SDValue Op = BV->getOperand(i);
6575
6576     // Skip 'undef' values.
6577     unsigned Opcode = Op.getOpcode();
6578     if (Opcode == ISD::UNDEF) {
6579       std::swap(ExpectedOpcode, NextExpectedOpcode);
6580       continue;
6581     }
6582
6583     // Early exit if we found an unexpected opcode.
6584     if (Opcode != ExpectedOpcode)
6585       return SDValue();
6586
6587     SDValue Op0 = Op.getOperand(0);
6588     SDValue Op1 = Op.getOperand(1);
6589
6590     // Try to match the following pattern:
6591     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6592     // Early exit if we cannot match that sequence.
6593     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6594         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6595         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6596         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6597         Op0.getOperand(1) != Op1.getOperand(1))
6598       return SDValue();
6599
6600     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6601     if (I0 != i)
6602       return SDValue();
6603
6604     // We found a valid add/sub node. Update the information accordingly.
6605     if (i & 1)
6606       AddFound = true;
6607     else
6608       SubFound = true;
6609
6610     // Update InVec0 and InVec1.
6611     if (InVec0.getOpcode() == ISD::UNDEF)
6612       InVec0 = Op0.getOperand(0);
6613     if (InVec1.getOpcode() == ISD::UNDEF)
6614       InVec1 = Op1.getOperand(0);
6615
6616     // Make sure that operands in input to each add/sub node always
6617     // come from a same pair of vectors.
6618     if (InVec0 != Op0.getOperand(0)) {
6619       if (ExpectedOpcode == ISD::FSUB)
6620         return SDValue();
6621
6622       // FADD is commutable. Try to commute the operands
6623       // and then test again.
6624       std::swap(Op0, Op1);
6625       if (InVec0 != Op0.getOperand(0))
6626         return SDValue();
6627     }
6628
6629     if (InVec1 != Op1.getOperand(0))
6630       return SDValue();
6631
6632     // Update the pair of expected opcodes.
6633     std::swap(ExpectedOpcode, NextExpectedOpcode);
6634   }
6635
6636   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6637   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6638       InVec1.getOpcode() != ISD::UNDEF)
6639     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6640
6641   return SDValue();
6642 }
6643
6644 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6645                                           const X86Subtarget *Subtarget) {
6646   SDLoc DL(N);
6647   EVT VT = N->getValueType(0);
6648   unsigned NumElts = VT.getVectorNumElements();
6649   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6650   SDValue InVec0, InVec1;
6651
6652   // Try to match an ADDSUB.
6653   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6654       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6655     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6656     if (Value.getNode())
6657       return Value;
6658   }
6659
6660   // Try to match horizontal ADD/SUB.
6661   unsigned NumUndefsLO = 0;
6662   unsigned NumUndefsHI = 0;
6663   unsigned Half = NumElts/2;
6664
6665   // Count the number of UNDEF operands in the build_vector in input.
6666   for (unsigned i = 0, e = Half; i != e; ++i)
6667     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6668       NumUndefsLO++;
6669
6670   for (unsigned i = Half, e = NumElts; i != e; ++i)
6671     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6672       NumUndefsHI++;
6673
6674   // Early exit if this is either a build_vector of all UNDEFs or all the
6675   // operands but one are UNDEF.
6676   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6677     return SDValue();
6678
6679   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6680     // Try to match an SSE3 float HADD/HSUB.
6681     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6682       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6683     
6684     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6685       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6686   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6687     // Try to match an SSSE3 integer HADD/HSUB.
6688     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6689       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6690     
6691     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6692       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6693   }
6694   
6695   if (!Subtarget->hasAVX())
6696     return SDValue();
6697
6698   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6699     // Try to match an AVX horizontal add/sub of packed single/double
6700     // precision floating point values from 256-bit vectors.
6701     SDValue InVec2, InVec3;
6702     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6703         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6704         ((InVec0.getOpcode() == ISD::UNDEF ||
6705           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6706         ((InVec1.getOpcode() == ISD::UNDEF ||
6707           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6708       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6709
6710     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6711         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6712         ((InVec0.getOpcode() == ISD::UNDEF ||
6713           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6714         ((InVec1.getOpcode() == ISD::UNDEF ||
6715           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6716       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6717   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6718     // Try to match an AVX2 horizontal add/sub of signed integers.
6719     SDValue InVec2, InVec3;
6720     unsigned X86Opcode;
6721     bool CanFold = true;
6722
6723     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6724         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6725         ((InVec0.getOpcode() == ISD::UNDEF ||
6726           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6727         ((InVec1.getOpcode() == ISD::UNDEF ||
6728           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6729       X86Opcode = X86ISD::HADD;
6730     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6731         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6732         ((InVec0.getOpcode() == ISD::UNDEF ||
6733           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6734         ((InVec1.getOpcode() == ISD::UNDEF ||
6735           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6736       X86Opcode = X86ISD::HSUB;
6737     else
6738       CanFold = false;
6739
6740     if (CanFold) {
6741       // Fold this build_vector into a single horizontal add/sub.
6742       // Do this only if the target has AVX2.
6743       if (Subtarget->hasAVX2())
6744         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6745  
6746       // Do not try to expand this build_vector into a pair of horizontal
6747       // add/sub if we can emit a pair of scalar add/sub.
6748       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6749         return SDValue();
6750
6751       // Convert this build_vector into a pair of horizontal binop followed by
6752       // a concat vector.
6753       bool isUndefLO = NumUndefsLO == Half;
6754       bool isUndefHI = NumUndefsHI == Half;
6755       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6756                                    isUndefLO, isUndefHI);
6757     }
6758   }
6759
6760   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6761        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6762     unsigned X86Opcode;
6763     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6764       X86Opcode = X86ISD::HADD;
6765     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6766       X86Opcode = X86ISD::HSUB;
6767     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6768       X86Opcode = X86ISD::FHADD;
6769     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6770       X86Opcode = X86ISD::FHSUB;
6771     else
6772       return SDValue();
6773
6774     // Don't try to expand this build_vector into a pair of horizontal add/sub
6775     // if we can simply emit a pair of scalar add/sub.
6776     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6777       return SDValue();
6778
6779     // Convert this build_vector into two horizontal add/sub followed by
6780     // a concat vector.
6781     bool isUndefLO = NumUndefsLO == Half;
6782     bool isUndefHI = NumUndefsHI == Half;
6783     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6784                                  isUndefLO, isUndefHI);
6785   }
6786
6787   return SDValue();
6788 }
6789
6790 SDValue
6791 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6792   SDLoc dl(Op);
6793
6794   MVT VT = Op.getSimpleValueType();
6795   MVT ExtVT = VT.getVectorElementType();
6796   unsigned NumElems = Op.getNumOperands();
6797
6798   // Generate vectors for predicate vectors.
6799   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6800     return LowerBUILD_VECTORvXi1(Op, DAG);
6801
6802   // Vectors containing all zeros can be matched by pxor and xorps later
6803   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6804     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6805     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6806     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6807       return Op;
6808
6809     return getZeroVector(VT, Subtarget, DAG, dl);
6810   }
6811
6812   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6813   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6814   // vpcmpeqd on 256-bit vectors.
6815   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6816     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6817       return Op;
6818
6819     if (!VT.is512BitVector())
6820       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6821   }
6822
6823   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6824   if (Broadcast.getNode())
6825     return Broadcast;
6826
6827   unsigned EVTBits = ExtVT.getSizeInBits();
6828
6829   unsigned NumZero  = 0;
6830   unsigned NumNonZero = 0;
6831   unsigned NonZeros = 0;
6832   bool IsAllConstants = true;
6833   SmallSet<SDValue, 8> Values;
6834   for (unsigned i = 0; i < NumElems; ++i) {
6835     SDValue Elt = Op.getOperand(i);
6836     if (Elt.getOpcode() == ISD::UNDEF)
6837       continue;
6838     Values.insert(Elt);
6839     if (Elt.getOpcode() != ISD::Constant &&
6840         Elt.getOpcode() != ISD::ConstantFP)
6841       IsAllConstants = false;
6842     if (X86::isZeroNode(Elt))
6843       NumZero++;
6844     else {
6845       NonZeros |= (1 << i);
6846       NumNonZero++;
6847     }
6848   }
6849
6850   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6851   if (NumNonZero == 0)
6852     return DAG.getUNDEF(VT);
6853
6854   // Special case for single non-zero, non-undef, element.
6855   if (NumNonZero == 1) {
6856     unsigned Idx = countTrailingZeros(NonZeros);
6857     SDValue Item = Op.getOperand(Idx);
6858
6859     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6860     // the value are obviously zero, truncate the value to i32 and do the
6861     // insertion that way.  Only do this if the value is non-constant or if the
6862     // value is a constant being inserted into element 0.  It is cheaper to do
6863     // a constant pool load than it is to do a movd + shuffle.
6864     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6865         (!IsAllConstants || Idx == 0)) {
6866       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6867         // Handle SSE only.
6868         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6869         EVT VecVT = MVT::v4i32;
6870         unsigned VecElts = 4;
6871
6872         // Truncate the value (which may itself be a constant) to i32, and
6873         // convert it to a vector with movd (S2V+shuffle to zero extend).
6874         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6875         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6876
6877         // If using the new shuffle lowering, just directly insert this.
6878         if (ExperimentalVectorShuffleLowering)
6879           return DAG.getNode(
6880               ISD::BITCAST, dl, VT,
6881               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6882
6883         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6884
6885         // Now we have our 32-bit value zero extended in the low element of
6886         // a vector.  If Idx != 0, swizzle it into place.
6887         if (Idx != 0) {
6888           SmallVector<int, 4> Mask;
6889           Mask.push_back(Idx);
6890           for (unsigned i = 1; i != VecElts; ++i)
6891             Mask.push_back(i);
6892           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6893                                       &Mask[0]);
6894         }
6895         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6896       }
6897     }
6898
6899     // If we have a constant or non-constant insertion into the low element of
6900     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6901     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6902     // depending on what the source datatype is.
6903     if (Idx == 0) {
6904       if (NumZero == 0)
6905         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6906
6907       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6908           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6909         if (VT.is256BitVector() || VT.is512BitVector()) {
6910           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6911           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6912                              Item, DAG.getIntPtrConstant(0));
6913         }
6914         assert(VT.is128BitVector() && "Expected an SSE value type!");
6915         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6916         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6917         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6918       }
6919
6920       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6921         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6922         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6923         if (VT.is256BitVector()) {
6924           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6925           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6926         } else {
6927           assert(VT.is128BitVector() && "Expected an SSE value type!");
6928           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6929         }
6930         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6931       }
6932     }
6933
6934     // Is it a vector logical left shift?
6935     if (NumElems == 2 && Idx == 1 &&
6936         X86::isZeroNode(Op.getOperand(0)) &&
6937         !X86::isZeroNode(Op.getOperand(1))) {
6938       unsigned NumBits = VT.getSizeInBits();
6939       return getVShift(true, VT,
6940                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6941                                    VT, Op.getOperand(1)),
6942                        NumBits/2, DAG, *this, dl);
6943     }
6944
6945     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6946       return SDValue();
6947
6948     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6949     // is a non-constant being inserted into an element other than the low one,
6950     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6951     // movd/movss) to move this into the low element, then shuffle it into
6952     // place.
6953     if (EVTBits == 32) {
6954       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6955
6956       // If using the new shuffle lowering, just directly insert this.
6957       if (ExperimentalVectorShuffleLowering)
6958         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6959
6960       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6961       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6962       SmallVector<int, 8> MaskVec;
6963       for (unsigned i = 0; i != NumElems; ++i)
6964         MaskVec.push_back(i == Idx ? 0 : 1);
6965       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6966     }
6967   }
6968
6969   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6970   if (Values.size() == 1) {
6971     if (EVTBits == 32) {
6972       // Instead of a shuffle like this:
6973       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6974       // Check if it's possible to issue this instead.
6975       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6976       unsigned Idx = countTrailingZeros(NonZeros);
6977       SDValue Item = Op.getOperand(Idx);
6978       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6979         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6980     }
6981     return SDValue();
6982   }
6983
6984   // A vector full of immediates; various special cases are already
6985   // handled, so this is best done with a single constant-pool load.
6986   if (IsAllConstants)
6987     return SDValue();
6988
6989   // For AVX-length vectors, build the individual 128-bit pieces and use
6990   // shuffles to put them in place.
6991   if (VT.is256BitVector() || VT.is512BitVector()) {
6992     SmallVector<SDValue, 64> V;
6993     for (unsigned i = 0; i != NumElems; ++i)
6994       V.push_back(Op.getOperand(i));
6995
6996     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6997
6998     // Build both the lower and upper subvector.
6999     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7000                                 makeArrayRef(&V[0], NumElems/2));
7001     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
7002                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
7003
7004     // Recreate the wider vector with the lower and upper part.
7005     if (VT.is256BitVector())
7006       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7007     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
7008   }
7009
7010   // Let legalizer expand 2-wide build_vectors.
7011   if (EVTBits == 64) {
7012     if (NumNonZero == 1) {
7013       // One half is zero or undef.
7014       unsigned Idx = countTrailingZeros(NonZeros);
7015       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
7016                                  Op.getOperand(Idx));
7017       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
7018     }
7019     return SDValue();
7020   }
7021
7022   // If element VT is < 32 bits, convert it to inserts into a zero vector.
7023   if (EVTBits == 8 && NumElems == 16) {
7024     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
7025                                         Subtarget, *this);
7026     if (V.getNode()) return V;
7027   }
7028
7029   if (EVTBits == 16 && NumElems == 8) {
7030     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
7031                                       Subtarget, *this);
7032     if (V.getNode()) return V;
7033   }
7034
7035   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
7036   if (EVTBits == 32 && NumElems == 4) {
7037     SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this);
7038     if (V.getNode())
7039       return V;
7040   }
7041
7042   // If element VT is == 32 bits, turn it into a number of shuffles.
7043   SmallVector<SDValue, 8> V(NumElems);
7044   if (NumElems == 4 && NumZero > 0) {
7045     for (unsigned i = 0; i < 4; ++i) {
7046       bool isZero = !(NonZeros & (1 << i));
7047       if (isZero)
7048         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7049       else
7050         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7051     }
7052
7053     for (unsigned i = 0; i < 2; ++i) {
7054       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7055         default: break;
7056         case 0:
7057           V[i] = V[i*2];  // Must be a zero vector.
7058           break;
7059         case 1:
7060           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7061           break;
7062         case 2:
7063           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7064           break;
7065         case 3:
7066           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7067           break;
7068       }
7069     }
7070
7071     bool Reverse1 = (NonZeros & 0x3) == 2;
7072     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7073     int MaskVec[] = {
7074       Reverse1 ? 1 : 0,
7075       Reverse1 ? 0 : 1,
7076       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7077       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7078     };
7079     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7080   }
7081
7082   if (Values.size() > 1 && VT.is128BitVector()) {
7083     // Check for a build vector of consecutive loads.
7084     for (unsigned i = 0; i < NumElems; ++i)
7085       V[i] = Op.getOperand(i);
7086
7087     // Check for elements which are consecutive loads.
7088     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7089     if (LD.getNode())
7090       return LD;
7091
7092     // Check for a build vector from mostly shuffle plus few inserting.
7093     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7094     if (Sh.getNode())
7095       return Sh;
7096
7097     // For SSE 4.1, use insertps to put the high elements into the low element.
7098     if (getSubtarget()->hasSSE41()) {
7099       SDValue Result;
7100       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7101         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7102       else
7103         Result = DAG.getUNDEF(VT);
7104
7105       for (unsigned i = 1; i < NumElems; ++i) {
7106         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7107         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7108                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7109       }
7110       return Result;
7111     }
7112
7113     // Otherwise, expand into a number of unpckl*, start by extending each of
7114     // our (non-undef) elements to the full vector width with the element in the
7115     // bottom slot of the vector (which generates no code for SSE).
7116     for (unsigned i = 0; i < NumElems; ++i) {
7117       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7118         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7119       else
7120         V[i] = DAG.getUNDEF(VT);
7121     }
7122
7123     // Next, we iteratively mix elements, e.g. for v4f32:
7124     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7125     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7126     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7127     unsigned EltStride = NumElems >> 1;
7128     while (EltStride != 0) {
7129       for (unsigned i = 0; i < EltStride; ++i) {
7130         // If V[i+EltStride] is undef and this is the first round of mixing,
7131         // then it is safe to just drop this shuffle: V[i] is already in the
7132         // right place, the one element (since it's the first round) being
7133         // inserted as undef can be dropped.  This isn't safe for successive
7134         // rounds because they will permute elements within both vectors.
7135         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7136             EltStride == NumElems/2)
7137           continue;
7138
7139         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7140       }
7141       EltStride >>= 1;
7142     }
7143     return V[0];
7144   }
7145   return SDValue();
7146 }
7147
7148 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7149 // to create 256-bit vectors from two other 128-bit ones.
7150 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7151   SDLoc dl(Op);
7152   MVT ResVT = Op.getSimpleValueType();
7153
7154   assert((ResVT.is256BitVector() ||
7155           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7156
7157   SDValue V1 = Op.getOperand(0);
7158   SDValue V2 = Op.getOperand(1);
7159   unsigned NumElems = ResVT.getVectorNumElements();
7160   if(ResVT.is256BitVector())
7161     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7162
7163   if (Op.getNumOperands() == 4) {
7164     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7165                                 ResVT.getVectorNumElements()/2);
7166     SDValue V3 = Op.getOperand(2);
7167     SDValue V4 = Op.getOperand(3);
7168     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7169       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7170   }
7171   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7172 }
7173
7174 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7175   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7176   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7177          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7178           Op.getNumOperands() == 4)));
7179
7180   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7181   // from two other 128-bit ones.
7182
7183   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7184   return LowerAVXCONCAT_VECTORS(Op, DAG);
7185 }
7186
7187
7188 //===----------------------------------------------------------------------===//
7189 // Vector shuffle lowering
7190 //
7191 // This is an experimental code path for lowering vector shuffles on x86. It is
7192 // designed to handle arbitrary vector shuffles and blends, gracefully
7193 // degrading performance as necessary. It works hard to recognize idiomatic
7194 // shuffles and lower them to optimal instruction patterns without leaving
7195 // a framework that allows reasonably efficient handling of all vector shuffle
7196 // patterns.
7197 //===----------------------------------------------------------------------===//
7198
7199 /// \brief Tiny helper function to identify a no-op mask.
7200 ///
7201 /// This is a somewhat boring predicate function. It checks whether the mask
7202 /// array input, which is assumed to be a single-input shuffle mask of the kind
7203 /// used by the X86 shuffle instructions (not a fully general
7204 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7205 /// in-place shuffle are 'no-op's.
7206 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7207   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7208     if (Mask[i] != -1 && Mask[i] != i)
7209       return false;
7210   return true;
7211 }
7212
7213 /// \brief Helper function to classify a mask as a single-input mask.
7214 ///
7215 /// This isn't a generic single-input test because in the vector shuffle
7216 /// lowering we canonicalize single inputs to be the first input operand. This
7217 /// means we can more quickly test for a single input by only checking whether
7218 /// an input from the second operand exists. We also assume that the size of
7219 /// mask corresponds to the size of the input vectors which isn't true in the
7220 /// fully general case.
7221 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7222   for (int M : Mask)
7223     if (M >= (int)Mask.size())
7224       return false;
7225   return true;
7226 }
7227
7228 /// \brief Test whether there are elements crossing 128-bit lanes in this
7229 /// shuffle mask.
7230 ///
7231 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7232 /// and we routinely test for these.
7233 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7234   int LaneSize = 128 / VT.getScalarSizeInBits();
7235   int Size = Mask.size();
7236   for (int i = 0; i < Size; ++i)
7237     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7238       return true;
7239   return false;
7240 }
7241
7242 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
7243 ///
7244 /// This checks a shuffle mask to see if it is performing the same
7245 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
7246 /// that it is also not lane-crossing. It may however involve a blend from the
7247 /// same lane of a second vector.
7248 ///
7249 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7250 /// non-trivial to compute in the face of undef lanes. The representation is
7251 /// *not* suitable for use with existing 128-bit shuffles as it will contain
7252 /// entries from both V1 and V2 inputs to the wider mask.
7253 static bool
7254 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7255                                 SmallVectorImpl<int> &RepeatedMask) {
7256   int LaneSize = 128 / VT.getScalarSizeInBits();
7257   RepeatedMask.resize(LaneSize, -1);
7258   int Size = Mask.size();
7259   for (int i = 0; i < Size; ++i) {
7260     if (Mask[i] < 0)
7261       continue;
7262     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7263       // This entry crosses lanes, so there is no way to model this shuffle.
7264       return false;
7265
7266     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7267     if (RepeatedMask[i % LaneSize] == -1)
7268       // This is the first non-undef entry in this slot of a 128-bit lane.
7269       RepeatedMask[i % LaneSize] =
7270           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
7271     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
7272       // Found a mismatch with the repeated mask.
7273       return false;
7274   }
7275   return true;
7276 }
7277
7278 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7279 // 2013 will allow us to use it as a non-type template parameter.
7280 namespace {
7281
7282 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7283 ///
7284 /// See its documentation for details.
7285 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7286   if (Mask.size() != Args.size())
7287     return false;
7288   for (int i = 0, e = Mask.size(); i < e; ++i) {
7289     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7290     if (Mask[i] != -1 && Mask[i] != *Args[i])
7291       return false;
7292   }
7293   return true;
7294 }
7295
7296 } // namespace
7297
7298 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7299 /// arguments.
7300 ///
7301 /// This is a fast way to test a shuffle mask against a fixed pattern:
7302 ///
7303 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7304 ///
7305 /// It returns true if the mask is exactly as wide as the argument list, and
7306 /// each element of the mask is either -1 (signifying undef) or the value given
7307 /// in the argument.
7308 static const VariadicFunction1<
7309     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7310
7311 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7312 ///
7313 /// This helper function produces an 8-bit shuffle immediate corresponding to
7314 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7315 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7316 /// example.
7317 ///
7318 /// NB: We rely heavily on "undef" masks preserving the input lane.
7319 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7320                                           SelectionDAG &DAG) {
7321   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7322   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7323   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7324   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7325   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7326
7327   unsigned Imm = 0;
7328   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7329   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7330   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7331   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7332   return DAG.getConstant(Imm, MVT::i8);
7333 }
7334
7335 /// \brief Try to emit a blend instruction for a shuffle.
7336 ///
7337 /// This doesn't do any checks for the availability of instructions for blending
7338 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7339 /// be matched in the backend with the type given. What it does check for is
7340 /// that the shuffle mask is in fact a blend.
7341 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7342                                          SDValue V2, ArrayRef<int> Mask,
7343                                          const X86Subtarget *Subtarget,
7344                                          SelectionDAG &DAG) {
7345
7346   unsigned BlendMask = 0;
7347   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7348     if (Mask[i] >= Size) {
7349       if (Mask[i] != i + Size)
7350         return SDValue(); // Shuffled V2 input!
7351       BlendMask |= 1u << i;
7352       continue;
7353     }
7354     if (Mask[i] >= 0 && Mask[i] != i)
7355       return SDValue(); // Shuffled V1 input!
7356   }
7357   switch (VT.SimpleTy) {
7358   case MVT::v2f64:
7359   case MVT::v4f32:
7360   case MVT::v4f64:
7361   case MVT::v8f32:
7362     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7363                        DAG.getConstant(BlendMask, MVT::i8));
7364
7365   case MVT::v4i64:
7366   case MVT::v8i32:
7367     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7368     // FALLTHROUGH
7369   case MVT::v2i64:
7370   case MVT::v4i32:
7371     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7372     // that instruction.
7373     if (Subtarget->hasAVX2()) {
7374       // Scale the blend by the number of 32-bit dwords per element.
7375       int Scale =  VT.getScalarSizeInBits() / 32;
7376       BlendMask = 0;
7377       for (int i = 0, Size = Mask.size(); i < Size; ++i)
7378         if (Mask[i] >= Size)
7379           for (int j = 0; j < Scale; ++j)
7380             BlendMask |= 1u << (i * Scale + j);
7381
7382       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7383       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7384       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7385       return DAG.getNode(ISD::BITCAST, DL, VT,
7386                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7387                                      DAG.getConstant(BlendMask, MVT::i8)));
7388     }
7389     // FALLTHROUGH
7390   case MVT::v8i16: {
7391     // For integer shuffles we need to expand the mask and cast the inputs to
7392     // v8i16s prior to blending.
7393     int Scale = 8 / VT.getVectorNumElements();
7394     BlendMask = 0;
7395     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7396       if (Mask[i] >= Size)
7397         for (int j = 0; j < Scale; ++j)
7398           BlendMask |= 1u << (i * Scale + j);
7399
7400     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7401     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7402     return DAG.getNode(ISD::BITCAST, DL, VT,
7403                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7404                                    DAG.getConstant(BlendMask, MVT::i8)));
7405   }
7406
7407   case MVT::v16i16: {
7408     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7409     SmallVector<int, 8> RepeatedMask;
7410     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7411       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7412       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7413       BlendMask = 0;
7414       for (int i = 0; i < 8; ++i)
7415         if (RepeatedMask[i] >= 16)
7416           BlendMask |= 1u << i;
7417       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7418                          DAG.getConstant(BlendMask, MVT::i8));
7419     }
7420   }
7421     // FALLTHROUGH
7422   case MVT::v32i8: {
7423     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7424     // Scale the blend by the number of bytes per element.
7425     int Scale =  VT.getScalarSizeInBits() / 8;
7426     assert(Mask.size() * Scale == 32 && "Not a 256-bit vector!");
7427
7428     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7429     // mix of LLVM's code generator and the x86 backend. We tell the code
7430     // generator that boolean values in the elements of an x86 vector register
7431     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7432     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7433     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7434     // of the element (the remaining are ignored) and 0 in that high bit would
7435     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7436     // the LLVM model for boolean values in vector elements gets the relevant
7437     // bit set, it is set backwards and over constrained relative to x86's
7438     // actual model.
7439     SDValue VSELECTMask[32];
7440     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7441       for (int j = 0; j < Scale; ++j)
7442         VSELECTMask[Scale * i + j] =
7443             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7444                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8);
7445
7446     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1);
7447     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V2);
7448     return DAG.getNode(
7449         ISD::BITCAST, DL, VT,
7450         DAG.getNode(ISD::VSELECT, DL, MVT::v32i8,
7451                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, VSELECTMask),
7452                     V1, V2));
7453   }
7454
7455   default:
7456     llvm_unreachable("Not a supported integer vector type!");
7457   }
7458 }
7459
7460 /// \brief Generic routine to lower a shuffle and blend as a decomposed set of
7461 /// unblended shuffles followed by an unshuffled blend.
7462 ///
7463 /// This matches the extremely common pattern for handling combined
7464 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7465 /// operations.
7466 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7467                                                           SDValue V1,
7468                                                           SDValue V2,
7469                                                           ArrayRef<int> Mask,
7470                                                           SelectionDAG &DAG) {
7471   // Shuffle the input elements into the desired positions in V1 and V2 and
7472   // blend them together.
7473   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7474   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7475   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7476   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7477     if (Mask[i] >= 0 && Mask[i] < Size) {
7478       V1Mask[i] = Mask[i];
7479       BlendMask[i] = i;
7480     } else if (Mask[i] >= Size) {
7481       V2Mask[i] = Mask[i] - Size;
7482       BlendMask[i] = i + Size;
7483     }
7484
7485   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7486   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7487   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7488 }
7489
7490 /// \brief Try to lower a vector shuffle as a byte rotation.
7491 ///
7492 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7493 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7494 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7495 /// try to generically lower a vector shuffle through such an pattern. It
7496 /// does not check for the profitability of lowering either as PALIGNR or
7497 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7498 /// This matches shuffle vectors that look like:
7499 /// 
7500 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7501 /// 
7502 /// Essentially it concatenates V1 and V2, shifts right by some number of
7503 /// elements, and takes the low elements as the result. Note that while this is
7504 /// specified as a *right shift* because x86 is little-endian, it is a *left
7505 /// rotate* of the vector lanes.
7506 ///
7507 /// Note that this only handles 128-bit vector widths currently.
7508 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7509                                               SDValue V2,
7510                                               ArrayRef<int> Mask,
7511                                               const X86Subtarget *Subtarget,
7512                                               SelectionDAG &DAG) {
7513   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7514
7515   // We need to detect various ways of spelling a rotation:
7516   //   [11, 12, 13, 14, 15,  0,  1,  2]
7517   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7518   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7519   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7520   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7521   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7522   int Rotation = 0;
7523   SDValue Lo, Hi;
7524   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7525     if (Mask[i] == -1)
7526       continue;
7527     assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7528
7529     // Based on the mod-Size value of this mask element determine where
7530     // a rotated vector would have started.
7531     int StartIdx = i - (Mask[i] % Size);
7532     if (StartIdx == 0)
7533       // The identity rotation isn't interesting, stop.
7534       return SDValue();
7535
7536     // If we found the tail of a vector the rotation must be the missing
7537     // front. If we found the head of a vector, it must be how much of the head.
7538     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7539
7540     if (Rotation == 0)
7541       Rotation = CandidateRotation;
7542     else if (Rotation != CandidateRotation)
7543       // The rotations don't match, so we can't match this mask.
7544       return SDValue();
7545
7546     // Compute which value this mask is pointing at.
7547     SDValue MaskV = Mask[i] < Size ? V1 : V2;
7548
7549     // Compute which of the two target values this index should be assigned to.
7550     // This reflects whether the high elements are remaining or the low elements
7551     // are remaining.
7552     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7553
7554     // Either set up this value if we've not encountered it before, or check
7555     // that it remains consistent.
7556     if (!TargetV)
7557       TargetV = MaskV;
7558     else if (TargetV != MaskV)
7559       // This may be a rotation, but it pulls from the inputs in some
7560       // unsupported interleaving.
7561       return SDValue();
7562   }
7563
7564   // Check that we successfully analyzed the mask, and normalize the results.
7565   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7566   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7567   if (!Lo)
7568     Lo = Hi;
7569   else if (!Hi)
7570     Hi = Lo;
7571
7572   assert(VT.getSizeInBits() == 128 &&
7573          "Rotate-based lowering only supports 128-bit lowering!");
7574   assert(Mask.size() <= 16 &&
7575          "Can shuffle at most 16 bytes in a 128-bit vector!");
7576
7577   // The actual rotate instruction rotates bytes, so we need to scale the
7578   // rotation based on how many bytes are in the vector.
7579   int Scale = 16 / Mask.size();
7580
7581   // SSSE3 targets can use the palignr instruction
7582   if (Subtarget->hasSSSE3()) {
7583     // Cast the inputs to v16i8 to match PALIGNR.
7584     Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7585     Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7586
7587     return DAG.getNode(ISD::BITCAST, DL, VT,
7588                        DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7589                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
7590   }
7591
7592   // Default SSE2 implementation
7593   int LoByteShift = 16 - Rotation * Scale;
7594   int HiByteShift = Rotation * Scale;
7595
7596   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7597   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
7598   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
7599
7600   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7601                                 DAG.getConstant(8 * LoByteShift, MVT::i8));
7602   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7603                                 DAG.getConstant(8 * HiByteShift, MVT::i8));
7604   return DAG.getNode(ISD::BITCAST, DL, VT,
7605                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7606 }
7607
7608 /// \brief Compute whether each element of a shuffle is zeroable.
7609 ///
7610 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7611 /// Either it is an undef element in the shuffle mask, the element of the input
7612 /// referenced is undef, or the element of the input referenced is known to be
7613 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7614 /// as many lanes with this technique as possible to simplify the remaining
7615 /// shuffle.
7616 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7617                                                      SDValue V1, SDValue V2) {
7618   SmallBitVector Zeroable(Mask.size(), false);
7619
7620   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7621   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7622
7623   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7624     int M = Mask[i];
7625     // Handle the easy cases.
7626     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7627       Zeroable[i] = true;
7628       continue;
7629     }
7630
7631     // If this is an index into a build_vector node, dig out the input value and
7632     // use it.
7633     SDValue V = M < Size ? V1 : V2;
7634     if (V.getOpcode() != ISD::BUILD_VECTOR)
7635       continue;
7636
7637     SDValue Input = V.getOperand(M % Size);
7638     // The UNDEF opcode check really should be dead code here, but not quite
7639     // worth asserting on (it isn't invalid, just unexpected).
7640     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7641       Zeroable[i] = true;
7642   }
7643
7644   return Zeroable;
7645 }
7646
7647 /// \brief Try to lower a vector shuffle as a byte shift (shifts in zeros).
7648 ///
7649 /// Attempts to match a shuffle mask against the PSRLDQ and PSLLDQ SSE2
7650 /// byte-shift instructions. The mask must consist of a shifted sequential
7651 /// shuffle from one of the input vectors and zeroable elements for the
7652 /// remaining 'shifted in' elements.
7653 ///
7654 /// Note that this only handles 128-bit vector widths currently.
7655 static SDValue lowerVectorShuffleAsByteShift(SDLoc DL, MVT VT, SDValue V1,
7656                                              SDValue V2, ArrayRef<int> Mask,
7657                                              SelectionDAG &DAG) {
7658   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7659
7660   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7661
7662   int Size = Mask.size();
7663   int Scale = 16 / Size;
7664
7665   auto isSequential = [](int Base, int StartIndex, int EndIndex, int MaskOffset,
7666                          ArrayRef<int> Mask) {
7667     for (int i = StartIndex; i < EndIndex; i++) {
7668       if (Mask[i] < 0)
7669         continue;
7670       if (i + Base != Mask[i] - MaskOffset)
7671         return false;
7672     }
7673     return true;
7674   };
7675
7676   for (int Shift = 1; Shift < Size; Shift++) {
7677     int ByteShift = Shift * Scale;
7678
7679     // PSRLDQ : (little-endian) right byte shift
7680     // [ 5,  6,  7, zz, zz, zz, zz, zz]
7681     // [ -1, 5,  6,  7, zz, zz, zz, zz]
7682     // [  1, 2, -1, -1, -1, -1, zz, zz]
7683     bool ZeroableRight = true;
7684     for (int i = Size - Shift; i < Size; i++) {
7685       ZeroableRight &= Zeroable[i];
7686     }
7687
7688     if (ZeroableRight) {
7689       bool ValidShiftRight1 = isSequential(Shift, 0, Size - Shift, 0, Mask);
7690       bool ValidShiftRight2 = isSequential(Shift, 0, Size - Shift, Size, Mask);
7691
7692       if (ValidShiftRight1 || ValidShiftRight2) {
7693         // Cast the inputs to v2i64 to match PSRLDQ.
7694         SDValue &TargetV = ValidShiftRight1 ? V1 : V2;
7695         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7696         SDValue Shifted = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, V,
7697                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7698         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7699       }
7700     }
7701
7702     // PSLLDQ : (little-endian) left byte shift
7703     // [ zz,  0,  1,  2,  3,  4,  5,  6]
7704     // [ zz, zz, -1, -1,  2,  3,  4, -1]
7705     // [ zz, zz, zz, zz, zz, zz, -1,  1]
7706     bool ZeroableLeft = true;
7707     for (int i = 0; i < Shift; i++) {
7708       ZeroableLeft &= Zeroable[i];
7709     }
7710
7711     if (ZeroableLeft) {
7712       bool ValidShiftLeft1 = isSequential(-Shift, Shift, Size, 0, Mask);
7713       bool ValidShiftLeft2 = isSequential(-Shift, Shift, Size, Size, Mask);
7714
7715       if (ValidShiftLeft1 || ValidShiftLeft2) {
7716         // Cast the inputs to v2i64 to match PSLLDQ.
7717         SDValue &TargetV = ValidShiftLeft1 ? V1 : V2;
7718         SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, TargetV);
7719         SDValue Shifted = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, V,
7720                                       DAG.getConstant(ByteShift * 8, MVT::i8));
7721         return DAG.getNode(ISD::BITCAST, DL, VT, Shifted);
7722       }
7723     }
7724   }
7725
7726   return SDValue();
7727 }
7728
7729 /// \brief Lower a vector shuffle as a zero or any extension.
7730 ///
7731 /// Given a specific number of elements, element bit width, and extension
7732 /// stride, produce either a zero or any extension based on the available
7733 /// features of the subtarget.
7734 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7735     SDLoc DL, MVT VT, int NumElements, int Scale, bool AnyExt, SDValue InputV,
7736     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7737   assert(Scale > 1 && "Need a scale to extend.");
7738   int EltBits = VT.getSizeInBits() / NumElements;
7739   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7740          "Only 8, 16, and 32 bit elements can be extended.");
7741   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7742
7743   // Found a valid zext mask! Try various lowering strategies based on the
7744   // input type and available ISA extensions.
7745   if (Subtarget->hasSSE41()) {
7746     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7747     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7748                                  NumElements / Scale);
7749     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7750     return DAG.getNode(ISD::BITCAST, DL, VT,
7751                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7752   }
7753
7754   // For any extends we can cheat for larger element sizes and use shuffle
7755   // instructions that can fold with a load and/or copy.
7756   if (AnyExt && EltBits == 32) {
7757     int PSHUFDMask[4] = {0, -1, 1, -1};
7758     return DAG.getNode(
7759         ISD::BITCAST, DL, VT,
7760         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7761                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7762                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7763   }
7764   if (AnyExt && EltBits == 16 && Scale > 2) {
7765     int PSHUFDMask[4] = {0, -1, 0, -1};
7766     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7767                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7768                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7769     int PSHUFHWMask[4] = {1, -1, -1, -1};
7770     return DAG.getNode(
7771         ISD::BITCAST, DL, VT,
7772         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7773                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
7774                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
7775   }
7776
7777   // If this would require more than 2 unpack instructions to expand, use
7778   // pshufb when available. We can only use more than 2 unpack instructions
7779   // when zero extending i8 elements which also makes it easier to use pshufb.
7780   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7781     assert(NumElements == 16 && "Unexpected byte vector width!");
7782     SDValue PSHUFBMask[16];
7783     for (int i = 0; i < 16; ++i)
7784       PSHUFBMask[i] =
7785           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
7786     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
7787     return DAG.getNode(ISD::BITCAST, DL, VT,
7788                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7789                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
7790                                                MVT::v16i8, PSHUFBMask)));
7791   }
7792
7793   // Otherwise emit a sequence of unpacks.
7794   do {
7795     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7796     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7797                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7798     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7799     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7800     Scale /= 2;
7801     EltBits *= 2;
7802     NumElements /= 2;
7803   } while (Scale > 1);
7804   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
7805 }
7806
7807 /// \brief Try to lower a vector shuffle as a zero extension on any micrarch.
7808 ///
7809 /// This routine will try to do everything in its power to cleverly lower
7810 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7811 /// check for the profitability of this lowering,  it tries to aggressively
7812 /// match this pattern. It will use all of the micro-architectural details it
7813 /// can to emit an efficient lowering. It handles both blends with all-zero
7814 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7815 /// masking out later).
7816 ///
7817 /// The reason we have dedicated lowering for zext-style shuffles is that they
7818 /// are both incredibly common and often quite performance sensitive.
7819 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7820     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7821     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7822   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7823
7824   int Bits = VT.getSizeInBits();
7825   int NumElements = Mask.size();
7826
7827   // Define a helper function to check a particular ext-scale and lower to it if
7828   // valid.
7829   auto Lower = [&](int Scale) -> SDValue {
7830     SDValue InputV;
7831     bool AnyExt = true;
7832     for (int i = 0; i < NumElements; ++i) {
7833       if (Mask[i] == -1)
7834         continue; // Valid anywhere but doesn't tell us anything.
7835       if (i % Scale != 0) {
7836         // Each of the extend elements needs to be zeroable.
7837         if (!Zeroable[i])
7838           return SDValue();
7839
7840         // We no lorger are in the anyext case.
7841         AnyExt = false;
7842         continue;
7843       }
7844
7845       // Each of the base elements needs to be consecutive indices into the
7846       // same input vector.
7847       SDValue V = Mask[i] < NumElements ? V1 : V2;
7848       if (!InputV)
7849         InputV = V;
7850       else if (InputV != V)
7851         return SDValue(); // Flip-flopping inputs.
7852
7853       if (Mask[i] % NumElements != i / Scale)
7854         return SDValue(); // Non-consecutive strided elemenst.
7855     }
7856
7857     // If we fail to find an input, we have a zero-shuffle which should always
7858     // have already been handled.
7859     // FIXME: Maybe handle this here in case during blending we end up with one?
7860     if (!InputV)
7861       return SDValue();
7862
7863     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7864         DL, VT, NumElements, Scale, AnyExt, InputV, Subtarget, DAG);
7865   };
7866
7867   // The widest scale possible for extending is to a 64-bit integer.
7868   assert(Bits % 64 == 0 &&
7869          "The number of bits in a vector must be divisible by 64 on x86!");
7870   int NumExtElements = Bits / 64;
7871
7872   // Each iteration, try extending the elements half as much, but into twice as
7873   // many elements.
7874   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7875     assert(NumElements % NumExtElements == 0 &&
7876            "The input vector size must be divisble by the extended size.");
7877     if (SDValue V = Lower(NumElements / NumExtElements))
7878       return V;
7879   }
7880
7881   // No viable ext lowering found.
7882   return SDValue();
7883 }
7884
7885 /// \brief Try to get a scalar value for a specific element of a vector.
7886 ///
7887 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7888 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7889                                               SelectionDAG &DAG) {
7890   MVT VT = V.getSimpleValueType();
7891   MVT EltVT = VT.getVectorElementType();
7892   while (V.getOpcode() == ISD::BITCAST)
7893     V = V.getOperand(0);
7894   // If the bitcasts shift the element size, we can't extract an equivalent
7895   // element from it.
7896   MVT NewVT = V.getSimpleValueType();
7897   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7898     return SDValue();
7899
7900   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7901       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR))
7902     return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, V.getOperand(Idx));
7903
7904   return SDValue();
7905 }
7906
7907 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7908 ///
7909 /// This is particularly important because the set of instructions varies
7910 /// significantly based on whether the operand is a load or not.
7911 static bool isShuffleFoldableLoad(SDValue V) {
7912   while (V.getOpcode() == ISD::BITCAST)
7913     V = V.getOperand(0);
7914
7915   return ISD::isNON_EXTLoad(V.getNode());
7916 }
7917
7918 /// \brief Try to lower insertion of a single element into a zero vector.
7919 ///
7920 /// This is a common pattern that we have especially efficient patterns to lower
7921 /// across all subtarget feature sets.
7922 static SDValue lowerVectorShuffleAsElementInsertion(
7923     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7924     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7925   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7926   MVT ExtVT = VT;
7927   MVT EltVT = VT.getVectorElementType();
7928
7929   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7930                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7931                 Mask.begin();
7932   bool IsV1Zeroable = true;
7933   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7934     if (i != V2Index && !Zeroable[i]) {
7935       IsV1Zeroable = false;
7936       break;
7937     }
7938
7939   // Check for a single input from a SCALAR_TO_VECTOR node.
7940   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7941   // all the smarts here sunk into that routine. However, the current
7942   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7943   // vector shuffle lowering is dead.
7944   if (SDValue V2S = getScalarValueForVectorElement(
7945           V2, Mask[V2Index] - Mask.size(), DAG)) {
7946     // We need to zext the scalar if it is smaller than an i32.
7947     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7948     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7949       // Using zext to expand a narrow element won't work for non-zero
7950       // insertions.
7951       if (!IsV1Zeroable)
7952         return SDValue();
7953
7954       // Zero-extend directly to i32.
7955       ExtVT = MVT::v4i32;
7956       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7957     }
7958     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7959   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7960              EltVT == MVT::i16) {
7961     // Either not inserting from the low element of the input or the input
7962     // element size is too small to use VZEXT_MOVL to clear the high bits.
7963     return SDValue();
7964   }
7965
7966   if (!IsV1Zeroable) {
7967     // If V1 can't be treated as a zero vector we have fewer options to lower
7968     // this. We can't support integer vectors or non-zero targets cheaply, and
7969     // the V1 elements can't be permuted in any way.
7970     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7971     if (!VT.isFloatingPoint() || V2Index != 0)
7972       return SDValue();
7973     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7974     V1Mask[V2Index] = -1;
7975     if (!isNoopShuffleMask(V1Mask))
7976       return SDValue();
7977     // This is essentially a special case blend operation, but if we have
7978     // general purpose blend operations, they are always faster. Bail and let
7979     // the rest of the lowering handle these as blends.
7980     if (Subtarget->hasSSE41())
7981       return SDValue();
7982
7983     // Otherwise, use MOVSD or MOVSS.
7984     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7985            "Only two types of floating point element types to handle!");
7986     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7987                        ExtVT, V1, V2);
7988   }
7989
7990   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7991   if (ExtVT != VT)
7992     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7993
7994   if (V2Index != 0) {
7995     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7996     // the desired position. Otherwise it is more efficient to do a vector
7997     // shift left. We know that we can do a vector shift left because all
7998     // the inputs are zero.
7999     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8000       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8001       V2Shuffle[V2Index] = 0;
8002       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8003     } else {
8004       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
8005       V2 = DAG.getNode(
8006           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8007           DAG.getConstant(
8008               V2Index * EltVT.getSizeInBits(),
8009               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
8010       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
8011     }
8012   }
8013   return V2;
8014 }
8015
8016 /// \brief Try to lower broadcast of a single element.
8017 ///
8018 /// For convenience, this code also bundles all of the subtarget feature set
8019 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8020 /// a convenient way to factor it out.
8021 static SDValue lowerVectorShuffleAsBroadcast(MVT VT, SDLoc DL, SDValue V,
8022                                              ArrayRef<int> Mask,
8023                                              const X86Subtarget *Subtarget,
8024                                              SelectionDAG &DAG) {
8025   if (!Subtarget->hasAVX())
8026     return SDValue();
8027   if (VT.isInteger() && !Subtarget->hasAVX2())
8028     return SDValue();
8029
8030   // Check that the mask is a broadcast.
8031   int BroadcastIdx = -1;
8032   for (int M : Mask)
8033     if (M >= 0 && BroadcastIdx == -1)
8034       BroadcastIdx = M;
8035     else if (M >= 0 && M != BroadcastIdx)
8036       return SDValue();
8037
8038   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8039                                             "a sorted mask where the broadcast "
8040                                             "comes from V1.");
8041
8042   // Go up the chain of (vector) values to try and find a scalar load that
8043   // we can combine with the broadcast.
8044   for (;;) {
8045     switch (V.getOpcode()) {
8046     case ISD::CONCAT_VECTORS: {
8047       int OperandSize = Mask.size() / V.getNumOperands();
8048       V = V.getOperand(BroadcastIdx / OperandSize);
8049       BroadcastIdx %= OperandSize;
8050       continue;
8051     }
8052
8053     case ISD::INSERT_SUBVECTOR: {
8054       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8055       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8056       if (!ConstantIdx)
8057         break;
8058
8059       int BeginIdx = (int)ConstantIdx->getZExtValue();
8060       int EndIdx =
8061           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
8062       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8063         BroadcastIdx -= BeginIdx;
8064         V = VInner;
8065       } else {
8066         V = VOuter;
8067       }
8068       continue;
8069     }
8070     }
8071     break;
8072   }
8073
8074   // Check if this is a broadcast of a scalar. We special case lowering
8075   // for scalars so that we can more effectively fold with loads.
8076   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8077       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8078     V = V.getOperand(BroadcastIdx);
8079
8080     // If the scalar isn't a load we can't broadcast from it in AVX1, only with
8081     // AVX2.
8082     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8083       return SDValue();
8084   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8085     // We can't broadcast from a vector register w/o AVX2, and we can only
8086     // broadcast from the zero-element of a vector register.
8087     return SDValue();
8088   }
8089
8090   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8091 }
8092
8093 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8094 ///
8095 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8096 /// support for floating point shuffles but not integer shuffles. These
8097 /// instructions will incur a domain crossing penalty on some chips though so
8098 /// it is better to avoid lowering through this for integer vectors where
8099 /// possible.
8100 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8101                                        const X86Subtarget *Subtarget,
8102                                        SelectionDAG &DAG) {
8103   SDLoc DL(Op);
8104   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8105   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8106   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8107   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8108   ArrayRef<int> Mask = SVOp->getMask();
8109   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8110
8111   if (isSingleInputShuffleMask(Mask)) {
8112     // Straight shuffle of a single input vector. Simulate this by using the
8113     // single input as both of the "inputs" to this instruction..
8114     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8115
8116     if (Subtarget->hasAVX()) {
8117       // If we have AVX, we can use VPERMILPS which will allow folding a load
8118       // into the shuffle.
8119       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8120                          DAG.getConstant(SHUFPDMask, MVT::i8));
8121     }
8122
8123     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
8124                        DAG.getConstant(SHUFPDMask, MVT::i8));
8125   }
8126   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8127   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8128
8129   // Use dedicated unpack instructions for masks that match their pattern.
8130   if (isShuffleEquivalent(Mask, 0, 2))
8131     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8132   if (isShuffleEquivalent(Mask, 1, 3))
8133     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8134
8135   // If we have a single input, insert that into V1 if we can do so cheaply.
8136   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8137     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8138             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
8139       return Insertion;
8140     // Try inverting the insertion since for v2 masks it is easy to do and we
8141     // can't reliably sort the mask one way or the other.
8142     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8143                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8144     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8145             MVT::v2f64, DL, V2, V1, InverseMask, Subtarget, DAG))
8146       return Insertion;
8147   }
8148
8149   // Try to use one of the special instruction patterns to handle two common
8150   // blend patterns if a zero-blend above didn't work.
8151   if (isShuffleEquivalent(Mask, 0, 3) || isShuffleEquivalent(Mask, 1, 3))
8152     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8153       // We can either use a special instruction to load over the low double or
8154       // to move just the low double.
8155       return DAG.getNode(
8156           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8157           DL, MVT::v2f64, V2,
8158           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8159
8160   if (Subtarget->hasSSE41())
8161     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8162                                                   Subtarget, DAG))
8163       return Blend;
8164
8165   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8166   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
8167                      DAG.getConstant(SHUFPDMask, MVT::i8));
8168 }
8169
8170 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8171 ///
8172 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8173 /// the integer unit to minimize domain crossing penalties. However, for blends
8174 /// it falls back to the floating point shuffle operation with appropriate bit
8175 /// casting.
8176 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8177                                        const X86Subtarget *Subtarget,
8178                                        SelectionDAG &DAG) {
8179   SDLoc DL(Op);
8180   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8181   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8182   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8183   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8184   ArrayRef<int> Mask = SVOp->getMask();
8185   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8186
8187   if (isSingleInputShuffleMask(Mask)) {
8188     // Check for being able to broadcast a single element.
8189     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v2i64, DL, V1,
8190                                                           Mask, Subtarget, DAG))
8191       return Broadcast;
8192
8193     // Straight shuffle of a single input vector. For everything from SSE2
8194     // onward this has a single fast instruction with no scary immediates.
8195     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8196     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
8197     int WidenedMask[4] = {
8198         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8199         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8200     return DAG.getNode(
8201         ISD::BITCAST, DL, MVT::v2i64,
8202         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
8203                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
8204   }
8205
8206   // Try to use byte shift instructions.
8207   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8208           DL, MVT::v2i64, V1, V2, Mask, DAG))
8209     return Shift;
8210
8211   // If we have a single input from V2 insert that into V1 if we can do so
8212   // cheaply.
8213   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8214     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8215             MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
8216       return Insertion;
8217     // Try inverting the insertion since for v2 masks it is easy to do and we
8218     // can't reliably sort the mask one way or the other.
8219     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8220                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8221     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8222             MVT::v2i64, DL, V2, V1, InverseMask, Subtarget, DAG))
8223       return Insertion;
8224   }
8225
8226   // Use dedicated unpack instructions for masks that match their pattern.
8227   if (isShuffleEquivalent(Mask, 0, 2))
8228     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8229   if (isShuffleEquivalent(Mask, 1, 3))
8230     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8231
8232   if (Subtarget->hasSSE41())
8233     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8234                                                   Subtarget, DAG))
8235       return Blend;
8236
8237   // Try to use byte rotation instructions.
8238   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8239   if (Subtarget->hasSSSE3())
8240     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8241             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8242       return Rotate;
8243
8244   // We implement this with SHUFPD which is pretty lame because it will likely
8245   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8246   // However, all the alternatives are still more cycles and newer chips don't
8247   // have this problem. It would be really nice if x86 had better shuffles here.
8248   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
8249   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
8250   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
8251                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8252 }
8253
8254 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8255 ///
8256 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8257 /// It makes no assumptions about whether this is the *best* lowering, it simply
8258 /// uses it.
8259 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8260                                             ArrayRef<int> Mask, SDValue V1,
8261                                             SDValue V2, SelectionDAG &DAG) {
8262   SDValue LowV = V1, HighV = V2;
8263   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8264
8265   int NumV2Elements =
8266       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8267
8268   if (NumV2Elements == 1) {
8269     int V2Index =
8270         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8271         Mask.begin();
8272
8273     // Compute the index adjacent to V2Index and in the same half by toggling
8274     // the low bit.
8275     int V2AdjIndex = V2Index ^ 1;
8276
8277     if (Mask[V2AdjIndex] == -1) {
8278       // Handles all the cases where we have a single V2 element and an undef.
8279       // This will only ever happen in the high lanes because we commute the
8280       // vector otherwise.
8281       if (V2Index < 2)
8282         std::swap(LowV, HighV);
8283       NewMask[V2Index] -= 4;
8284     } else {
8285       // Handle the case where the V2 element ends up adjacent to a V1 element.
8286       // To make this work, blend them together as the first step.
8287       int V1Index = V2AdjIndex;
8288       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8289       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8290                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8291
8292       // Now proceed to reconstruct the final blend as we have the necessary
8293       // high or low half formed.
8294       if (V2Index < 2) {
8295         LowV = V2;
8296         HighV = V1;
8297       } else {
8298         HighV = V2;
8299       }
8300       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8301       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8302     }
8303   } else if (NumV2Elements == 2) {
8304     if (Mask[0] < 4 && Mask[1] < 4) {
8305       // Handle the easy case where we have V1 in the low lanes and V2 in the
8306       // high lanes.
8307       NewMask[2] -= 4;
8308       NewMask[3] -= 4;
8309     } else if (Mask[2] < 4 && Mask[3] < 4) {
8310       // We also handle the reversed case because this utility may get called
8311       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8312       // arrange things in the right direction.
8313       NewMask[0] -= 4;
8314       NewMask[1] -= 4;
8315       HighV = V1;
8316       LowV = V2;
8317     } else {
8318       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8319       // trying to place elements directly, just blend them and set up the final
8320       // shuffle to place them.
8321
8322       // The first two blend mask elements are for V1, the second two are for
8323       // V2.
8324       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8325                           Mask[2] < 4 ? Mask[2] : Mask[3],
8326                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8327                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8328       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8329                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
8330
8331       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8332       // a blend.
8333       LowV = HighV = V1;
8334       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8335       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8336       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8337       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8338     }
8339   }
8340   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8341                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
8342 }
8343
8344 /// \brief Lower 4-lane 32-bit floating point shuffles.
8345 ///
8346 /// Uses instructions exclusively from the floating point unit to minimize
8347 /// domain crossing penalties, as these are sufficient to implement all v4f32
8348 /// shuffles.
8349 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8350                                        const X86Subtarget *Subtarget,
8351                                        SelectionDAG &DAG) {
8352   SDLoc DL(Op);
8353   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8354   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8355   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8356   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8357   ArrayRef<int> Mask = SVOp->getMask();
8358   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8359
8360   int NumV2Elements =
8361       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8362
8363   if (NumV2Elements == 0) {
8364     // Check for being able to broadcast a single element.
8365     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f32, DL, V1,
8366                                                           Mask, Subtarget, DAG))
8367       return Broadcast;
8368
8369     if (Subtarget->hasAVX()) {
8370       // If we have AVX, we can use VPERMILPS which will allow folding a load
8371       // into the shuffle.
8372       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8373                          getV4X86ShuffleImm8ForMask(Mask, DAG));
8374     }
8375
8376     // Otherwise, use a straight shuffle of a single input vector. We pass the
8377     // input vector to both operands to simulate this with a SHUFPS.
8378     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8379                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8380   }
8381
8382   // Use dedicated unpack instructions for masks that match their pattern.
8383   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8384     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8385   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8386     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8387
8388   // There are special ways we can lower some single-element blends. However, we
8389   // have custom ways we can lower more complex single-element blends below that
8390   // we defer to if both this and BLENDPS fail to match, so restrict this to
8391   // when the V2 input is targeting element 0 of the mask -- that is the fast
8392   // case here.
8393   if (NumV2Elements == 1 && Mask[0] >= 4)
8394     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
8395                                                          Mask, Subtarget, DAG))
8396       return V;
8397
8398   if (Subtarget->hasSSE41())
8399     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8400                                                   Subtarget, DAG))
8401       return Blend;
8402
8403   // Check for whether we can use INSERTPS to perform the blend. We only use
8404   // INSERTPS when the V1 elements are already in the correct locations
8405   // because otherwise we can just always use two SHUFPS instructions which
8406   // are much smaller to encode than a SHUFPS and an INSERTPS.
8407   if (NumV2Elements == 1 && Subtarget->hasSSE41()) {
8408     int V2Index =
8409         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8410         Mask.begin();
8411
8412     // When using INSERTPS we can zero any lane of the destination. Collect
8413     // the zero inputs into a mask and drop them from the lanes of V1 which
8414     // actually need to be present as inputs to the INSERTPS.
8415     SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8416
8417     // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
8418     bool InsertNeedsShuffle = false;
8419     unsigned ZMask = 0;
8420     for (int i = 0; i < 4; ++i)
8421       if (i != V2Index) {
8422         if (Zeroable[i]) {
8423           ZMask |= 1 << i;
8424         } else if (Mask[i] != i) {
8425           InsertNeedsShuffle = true;
8426           break;
8427         }
8428       }
8429
8430     // We don't want to use INSERTPS or other insertion techniques if it will
8431     // require shuffling anyways.
8432     if (!InsertNeedsShuffle) {
8433       // If all of V1 is zeroable, replace it with undef.
8434       if ((ZMask | 1 << V2Index) == 0xF)
8435         V1 = DAG.getUNDEF(MVT::v4f32);
8436
8437       unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
8438       assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8439
8440       // Insert the V2 element into the desired position.
8441       return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8442                          DAG.getConstant(InsertPSMask, MVT::i8));
8443     }
8444   }
8445
8446   // Otherwise fall back to a SHUFPS lowering strategy.
8447   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8448 }
8449
8450 /// \brief Lower 4-lane i32 vector shuffles.
8451 ///
8452 /// We try to handle these with integer-domain shuffles where we can, but for
8453 /// blends we use the floating point domain blend instructions.
8454 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8455                                        const X86Subtarget *Subtarget,
8456                                        SelectionDAG &DAG) {
8457   SDLoc DL(Op);
8458   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8459   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8460   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8461   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8462   ArrayRef<int> Mask = SVOp->getMask();
8463   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8464
8465   // Whenever we can lower this as a zext, that instruction is strictly faster
8466   // than any alternative. It also allows us to fold memory operands into the
8467   // shuffle in many cases.
8468   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8469                                                          Mask, Subtarget, DAG))
8470     return ZExt;
8471
8472   int NumV2Elements =
8473       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8474
8475   if (NumV2Elements == 0) {
8476     // Check for being able to broadcast a single element.
8477     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i32, DL, V1,
8478                                                           Mask, Subtarget, DAG))
8479       return Broadcast;
8480
8481     // Straight shuffle of a single input vector. For everything from SSE2
8482     // onward this has a single fast instruction with no scary immediates.
8483     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8484     // but we aren't actually going to use the UNPCK instruction because doing
8485     // so prevents folding a load into this instruction or making a copy.
8486     const int UnpackLoMask[] = {0, 0, 1, 1};
8487     const int UnpackHiMask[] = {2, 2, 3, 3};
8488     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8489       Mask = UnpackLoMask;
8490     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8491       Mask = UnpackHiMask;
8492
8493     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8494                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8495   }
8496
8497   // Try to use byte shift instructions.
8498   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8499           DL, MVT::v4i32, V1, V2, Mask, DAG))
8500     return Shift;
8501
8502   // There are special ways we can lower some single-element blends.
8503   if (NumV2Elements == 1)
8504     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8505                                                          Mask, Subtarget, DAG))
8506       return V;
8507
8508   // Use dedicated unpack instructions for masks that match their pattern.
8509   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8510     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8511   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8512     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8513
8514   if (Subtarget->hasSSE41())
8515     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8516                                                   Subtarget, DAG))
8517       return Blend;
8518
8519   // Try to use byte rotation instructions.
8520   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8521   if (Subtarget->hasSSSE3())
8522     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8523             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8524       return Rotate;
8525
8526   // We implement this with SHUFPS because it can blend from two vectors.
8527   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8528   // up the inputs, bypassing domain shift penalties that we would encur if we
8529   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8530   // relevant.
8531   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8532                      DAG.getVectorShuffle(
8533                          MVT::v4f32, DL,
8534                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8535                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8536 }
8537
8538 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8539 /// shuffle lowering, and the most complex part.
8540 ///
8541 /// The lowering strategy is to try to form pairs of input lanes which are
8542 /// targeted at the same half of the final vector, and then use a dword shuffle
8543 /// to place them onto the right half, and finally unpack the paired lanes into
8544 /// their final position.
8545 ///
8546 /// The exact breakdown of how to form these dword pairs and align them on the
8547 /// correct sides is really tricky. See the comments within the function for
8548 /// more of the details.
8549 static SDValue lowerV8I16SingleInputVectorShuffle(
8550     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8551     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8552   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8553   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8554   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8555
8556   SmallVector<int, 4> LoInputs;
8557   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8558                [](int M) { return M >= 0; });
8559   std::sort(LoInputs.begin(), LoInputs.end());
8560   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8561   SmallVector<int, 4> HiInputs;
8562   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8563                [](int M) { return M >= 0; });
8564   std::sort(HiInputs.begin(), HiInputs.end());
8565   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8566   int NumLToL =
8567       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8568   int NumHToL = LoInputs.size() - NumLToL;
8569   int NumLToH =
8570       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8571   int NumHToH = HiInputs.size() - NumLToH;
8572   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8573   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8574   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8575   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8576
8577   // Check for being able to broadcast a single element.
8578   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i16, DL, V,
8579                                                         Mask, Subtarget, DAG))
8580     return Broadcast;
8581
8582   // Try to use byte shift instructions.
8583   if (SDValue Shift = lowerVectorShuffleAsByteShift(
8584           DL, MVT::v8i16, V, V, Mask, DAG))
8585     return Shift;
8586
8587   // Use dedicated unpack instructions for masks that match their pattern.
8588   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8589     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8590   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8591     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8592
8593   // Try to use byte rotation instructions.
8594   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8595           DL, MVT::v8i16, V, V, Mask, Subtarget, DAG))
8596     return Rotate;
8597
8598   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8599   // such inputs we can swap two of the dwords across the half mark and end up
8600   // with <=2 inputs to each half in each half. Once there, we can fall through
8601   // to the generic code below. For example:
8602   //
8603   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8604   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8605   //
8606   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8607   // and an existing 2-into-2 on the other half. In this case we may have to
8608   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8609   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8610   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8611   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8612   // half than the one we target for fixing) will be fixed when we re-enter this
8613   // path. We will also combine away any sequence of PSHUFD instructions that
8614   // result into a single instruction. Here is an example of the tricky case:
8615   //
8616   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8617   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8618   //
8619   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8620   //
8621   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8622   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8623   //
8624   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8625   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8626   //
8627   // The result is fine to be handled by the generic logic.
8628   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8629                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8630                           int AOffset, int BOffset) {
8631     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8632            "Must call this with A having 3 or 1 inputs from the A half.");
8633     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8634            "Must call this with B having 1 or 3 inputs from the B half.");
8635     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8636            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8637
8638     // Compute the index of dword with only one word among the three inputs in
8639     // a half by taking the sum of the half with three inputs and subtracting
8640     // the sum of the actual three inputs. The difference is the remaining
8641     // slot.
8642     int ADWord, BDWord;
8643     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8644     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8645     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8646     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8647     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8648     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8649     int TripleNonInputIdx =
8650         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8651     TripleDWord = TripleNonInputIdx / 2;
8652
8653     // We use xor with one to compute the adjacent DWord to whichever one the
8654     // OneInput is in.
8655     OneInputDWord = (OneInput / 2) ^ 1;
8656
8657     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8658     // and BToA inputs. If there is also such a problem with the BToB and AToB
8659     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8660     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8661     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8662     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8663       // Compute how many inputs will be flipped by swapping these DWords. We
8664       // need
8665       // to balance this to ensure we don't form a 3-1 shuffle in the other
8666       // half.
8667       int NumFlippedAToBInputs =
8668           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8669           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8670       int NumFlippedBToBInputs =
8671           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8672           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8673       if ((NumFlippedAToBInputs == 1 &&
8674            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8675           (NumFlippedBToBInputs == 1 &&
8676            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8677         // We choose whether to fix the A half or B half based on whether that
8678         // half has zero flipped inputs. At zero, we may not be able to fix it
8679         // with that half. We also bias towards fixing the B half because that
8680         // will more commonly be the high half, and we have to bias one way.
8681         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8682                                                        ArrayRef<int> Inputs) {
8683           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8684           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8685                                          PinnedIdx ^ 1) != Inputs.end();
8686           // Determine whether the free index is in the flipped dword or the
8687           // unflipped dword based on where the pinned index is. We use this bit
8688           // in an xor to conditionally select the adjacent dword.
8689           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8690           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8691                                              FixFreeIdx) != Inputs.end();
8692           if (IsFixIdxInput == IsFixFreeIdxInput)
8693             FixFreeIdx += 1;
8694           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8695                                         FixFreeIdx) != Inputs.end();
8696           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8697                  "We need to be changing the number of flipped inputs!");
8698           int PSHUFHalfMask[] = {0, 1, 2, 3};
8699           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8700           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8701                           MVT::v8i16, V,
8702                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
8703
8704           for (int &M : Mask)
8705             if (M != -1 && M == FixIdx)
8706               M = FixFreeIdx;
8707             else if (M != -1 && M == FixFreeIdx)
8708               M = FixIdx;
8709         };
8710         if (NumFlippedBToBInputs != 0) {
8711           int BPinnedIdx =
8712               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8713           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8714         } else {
8715           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8716           int APinnedIdx =
8717               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8718           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8719         }
8720       }
8721     }
8722
8723     int PSHUFDMask[] = {0, 1, 2, 3};
8724     PSHUFDMask[ADWord] = BDWord;
8725     PSHUFDMask[BDWord] = ADWord;
8726     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8727                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8728                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8729                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8730
8731     // Adjust the mask to match the new locations of A and B.
8732     for (int &M : Mask)
8733       if (M != -1 && M/2 == ADWord)
8734         M = 2 * BDWord + M % 2;
8735       else if (M != -1 && M/2 == BDWord)
8736         M = 2 * ADWord + M % 2;
8737
8738     // Recurse back into this routine to re-compute state now that this isn't
8739     // a 3 and 1 problem.
8740     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8741                                 Mask);
8742   };
8743   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8744     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8745   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8746     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8747
8748   // At this point there are at most two inputs to the low and high halves from
8749   // each half. That means the inputs can always be grouped into dwords and
8750   // those dwords can then be moved to the correct half with a dword shuffle.
8751   // We use at most one low and one high word shuffle to collect these paired
8752   // inputs into dwords, and finally a dword shuffle to place them.
8753   int PSHUFLMask[4] = {-1, -1, -1, -1};
8754   int PSHUFHMask[4] = {-1, -1, -1, -1};
8755   int PSHUFDMask[4] = {-1, -1, -1, -1};
8756
8757   // First fix the masks for all the inputs that are staying in their
8758   // original halves. This will then dictate the targets of the cross-half
8759   // shuffles.
8760   auto fixInPlaceInputs =
8761       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8762                     MutableArrayRef<int> SourceHalfMask,
8763                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8764     if (InPlaceInputs.empty())
8765       return;
8766     if (InPlaceInputs.size() == 1) {
8767       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8768           InPlaceInputs[0] - HalfOffset;
8769       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8770       return;
8771     }
8772     if (IncomingInputs.empty()) {
8773       // Just fix all of the in place inputs.
8774       for (int Input : InPlaceInputs) {
8775         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8776         PSHUFDMask[Input / 2] = Input / 2;
8777       }
8778       return;
8779     }
8780
8781     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8782     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8783         InPlaceInputs[0] - HalfOffset;
8784     // Put the second input next to the first so that they are packed into
8785     // a dword. We find the adjacent index by toggling the low bit.
8786     int AdjIndex = InPlaceInputs[0] ^ 1;
8787     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8788     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8789     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8790   };
8791   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8792   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8793
8794   // Now gather the cross-half inputs and place them into a free dword of
8795   // their target half.
8796   // FIXME: This operation could almost certainly be simplified dramatically to
8797   // look more like the 3-1 fixing operation.
8798   auto moveInputsToRightHalf = [&PSHUFDMask](
8799       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8800       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8801       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8802       int DestOffset) {
8803     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8804       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8805     };
8806     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8807                                                int Word) {
8808       int LowWord = Word & ~1;
8809       int HighWord = Word | 1;
8810       return isWordClobbered(SourceHalfMask, LowWord) ||
8811              isWordClobbered(SourceHalfMask, HighWord);
8812     };
8813
8814     if (IncomingInputs.empty())
8815       return;
8816
8817     if (ExistingInputs.empty()) {
8818       // Map any dwords with inputs from them into the right half.
8819       for (int Input : IncomingInputs) {
8820         // If the source half mask maps over the inputs, turn those into
8821         // swaps and use the swapped lane.
8822         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8823           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8824             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8825                 Input - SourceOffset;
8826             // We have to swap the uses in our half mask in one sweep.
8827             for (int &M : HalfMask)
8828               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8829                 M = Input;
8830               else if (M == Input)
8831                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8832           } else {
8833             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8834                        Input - SourceOffset &&
8835                    "Previous placement doesn't match!");
8836           }
8837           // Note that this correctly re-maps both when we do a swap and when
8838           // we observe the other side of the swap above. We rely on that to
8839           // avoid swapping the members of the input list directly.
8840           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8841         }
8842
8843         // Map the input's dword into the correct half.
8844         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8845           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8846         else
8847           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8848                      Input / 2 &&
8849                  "Previous placement doesn't match!");
8850       }
8851
8852       // And just directly shift any other-half mask elements to be same-half
8853       // as we will have mirrored the dword containing the element into the
8854       // same position within that half.
8855       for (int &M : HalfMask)
8856         if (M >= SourceOffset && M < SourceOffset + 4) {
8857           M = M - SourceOffset + DestOffset;
8858           assert(M >= 0 && "This should never wrap below zero!");
8859         }
8860       return;
8861     }
8862
8863     // Ensure we have the input in a viable dword of its current half. This
8864     // is particularly tricky because the original position may be clobbered
8865     // by inputs being moved and *staying* in that half.
8866     if (IncomingInputs.size() == 1) {
8867       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8868         int InputFixed = std::find(std::begin(SourceHalfMask),
8869                                    std::end(SourceHalfMask), -1) -
8870                          std::begin(SourceHalfMask) + SourceOffset;
8871         SourceHalfMask[InputFixed - SourceOffset] =
8872             IncomingInputs[0] - SourceOffset;
8873         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8874                      InputFixed);
8875         IncomingInputs[0] = InputFixed;
8876       }
8877     } else if (IncomingInputs.size() == 2) {
8878       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8879           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8880         // We have two non-adjacent or clobbered inputs we need to extract from
8881         // the source half. To do this, we need to map them into some adjacent
8882         // dword slot in the source mask.
8883         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8884                               IncomingInputs[1] - SourceOffset};
8885
8886         // If there is a free slot in the source half mask adjacent to one of
8887         // the inputs, place the other input in it. We use (Index XOR 1) to
8888         // compute an adjacent index.
8889         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8890             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8891           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8892           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8893           InputsFixed[1] = InputsFixed[0] ^ 1;
8894         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8895                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8896           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8897           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8898           InputsFixed[0] = InputsFixed[1] ^ 1;
8899         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8900                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8901           // The two inputs are in the same DWord but it is clobbered and the
8902           // adjacent DWord isn't used at all. Move both inputs to the free
8903           // slot.
8904           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8905           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8906           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8907           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8908         } else {
8909           // The only way we hit this point is if there is no clobbering
8910           // (because there are no off-half inputs to this half) and there is no
8911           // free slot adjacent to one of the inputs. In this case, we have to
8912           // swap an input with a non-input.
8913           for (int i = 0; i < 4; ++i)
8914             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8915                    "We can't handle any clobbers here!");
8916           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8917                  "Cannot have adjacent inputs here!");
8918
8919           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8920           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8921
8922           // We also have to update the final source mask in this case because
8923           // it may need to undo the above swap.
8924           for (int &M : FinalSourceHalfMask)
8925             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8926               M = InputsFixed[1] + SourceOffset;
8927             else if (M == InputsFixed[1] + SourceOffset)
8928               M = (InputsFixed[0] ^ 1) + SourceOffset;
8929
8930           InputsFixed[1] = InputsFixed[0] ^ 1;
8931         }
8932
8933         // Point everything at the fixed inputs.
8934         for (int &M : HalfMask)
8935           if (M == IncomingInputs[0])
8936             M = InputsFixed[0] + SourceOffset;
8937           else if (M == IncomingInputs[1])
8938             M = InputsFixed[1] + SourceOffset;
8939
8940         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8941         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8942       }
8943     } else {
8944       llvm_unreachable("Unhandled input size!");
8945     }
8946
8947     // Now hoist the DWord down to the right half.
8948     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8949     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8950     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8951     for (int &M : HalfMask)
8952       for (int Input : IncomingInputs)
8953         if (M == Input)
8954           M = FreeDWord * 2 + Input % 2;
8955   };
8956   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8957                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8958   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8959                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8960
8961   // Now enact all the shuffles we've computed to move the inputs into their
8962   // target half.
8963   if (!isNoopShuffleMask(PSHUFLMask))
8964     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8965                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8966   if (!isNoopShuffleMask(PSHUFHMask))
8967     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8968                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8969   if (!isNoopShuffleMask(PSHUFDMask))
8970     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8971                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8972                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8973                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8974
8975   // At this point, each half should contain all its inputs, and we can then
8976   // just shuffle them into their final position.
8977   assert(std::count_if(LoMask.begin(), LoMask.end(),
8978                        [](int M) { return M >= 4; }) == 0 &&
8979          "Failed to lift all the high half inputs to the low mask!");
8980   assert(std::count_if(HiMask.begin(), HiMask.end(),
8981                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8982          "Failed to lift all the low half inputs to the high mask!");
8983
8984   // Do a half shuffle for the low mask.
8985   if (!isNoopShuffleMask(LoMask))
8986     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8987                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8988
8989   // Do a half shuffle with the high mask after shifting its values down.
8990   for (int &M : HiMask)
8991     if (M >= 0)
8992       M -= 4;
8993   if (!isNoopShuffleMask(HiMask))
8994     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8995                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8996
8997   return V;
8998 }
8999
9000 /// \brief Detect whether the mask pattern should be lowered through
9001 /// interleaving.
9002 ///
9003 /// This essentially tests whether viewing the mask as an interleaving of two
9004 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
9005 /// lowering it through interleaving is a significantly better strategy.
9006 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
9007   int NumEvenInputs[2] = {0, 0};
9008   int NumOddInputs[2] = {0, 0};
9009   int NumLoInputs[2] = {0, 0};
9010   int NumHiInputs[2] = {0, 0};
9011   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9012     if (Mask[i] < 0)
9013       continue;
9014
9015     int InputIdx = Mask[i] >= Size;
9016
9017     if (i < Size / 2)
9018       ++NumLoInputs[InputIdx];
9019     else
9020       ++NumHiInputs[InputIdx];
9021
9022     if ((i % 2) == 0)
9023       ++NumEvenInputs[InputIdx];
9024     else
9025       ++NumOddInputs[InputIdx];
9026   }
9027
9028   // The minimum number of cross-input results for both the interleaved and
9029   // split cases. If interleaving results in fewer cross-input results, return
9030   // true.
9031   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
9032                                     NumEvenInputs[0] + NumOddInputs[1]);
9033   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
9034                               NumLoInputs[0] + NumHiInputs[1]);
9035   return InterleavedCrosses < SplitCrosses;
9036 }
9037
9038 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
9039 ///
9040 /// This strategy only works when the inputs from each vector fit into a single
9041 /// half of that vector, and generally there are not so many inputs as to leave
9042 /// the in-place shuffles required highly constrained (and thus expensive). It
9043 /// shifts all the inputs into a single side of both input vectors and then
9044 /// uses an unpack to interleave these inputs in a single vector. At that
9045 /// point, we will fall back on the generic single input shuffle lowering.
9046 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
9047                                                  SDValue V2,
9048                                                  MutableArrayRef<int> Mask,
9049                                                  const X86Subtarget *Subtarget,
9050                                                  SelectionDAG &DAG) {
9051   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9052   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
9053   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
9054   for (int i = 0; i < 8; ++i)
9055     if (Mask[i] >= 0 && Mask[i] < 4)
9056       LoV1Inputs.push_back(i);
9057     else if (Mask[i] >= 4 && Mask[i] < 8)
9058       HiV1Inputs.push_back(i);
9059     else if (Mask[i] >= 8 && Mask[i] < 12)
9060       LoV2Inputs.push_back(i);
9061     else if (Mask[i] >= 12)
9062       HiV2Inputs.push_back(i);
9063
9064   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
9065   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
9066   (void)NumV1Inputs;
9067   (void)NumV2Inputs;
9068   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
9069   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
9070   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
9071
9072   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
9073                      HiV1Inputs.size() + HiV2Inputs.size();
9074
9075   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
9076                               ArrayRef<int> HiInputs, bool MoveToLo,
9077                               int MaskOffset) {
9078     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
9079     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
9080     if (BadInputs.empty())
9081       return V;
9082
9083     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9084     int MoveOffset = MoveToLo ? 0 : 4;
9085
9086     if (GoodInputs.empty()) {
9087       for (int BadInput : BadInputs) {
9088         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
9089         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
9090       }
9091     } else {
9092       if (GoodInputs.size() == 2) {
9093         // If the low inputs are spread across two dwords, pack them into
9094         // a single dword.
9095         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
9096         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
9097         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
9098         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
9099       } else {
9100         // Otherwise pin the good inputs.
9101         for (int GoodInput : GoodInputs)
9102           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
9103       }
9104
9105       if (BadInputs.size() == 2) {
9106         // If we have two bad inputs then there may be either one or two good
9107         // inputs fixed in place. Find a fixed input, and then find the *other*
9108         // two adjacent indices by using modular arithmetic.
9109         int GoodMaskIdx =
9110             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
9111                          [](int M) { return M >= 0; }) -
9112             std::begin(MoveMask);
9113         int MoveMaskIdx =
9114             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
9115         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
9116         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
9117         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9118         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
9119         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9120         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
9121       } else {
9122         assert(BadInputs.size() == 1 && "All sizes handled");
9123         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
9124                                     std::end(MoveMask), -1) -
9125                           std::begin(MoveMask);
9126         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
9127         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
9128       }
9129     }
9130
9131     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
9132                                 MoveMask);
9133   };
9134   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
9135                         /*MaskOffset*/ 0);
9136   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
9137                         /*MaskOffset*/ 8);
9138
9139   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
9140   // cross-half traffic in the final shuffle.
9141
9142   // Munge the mask to be a single-input mask after the unpack merges the
9143   // results.
9144   for (int &M : Mask)
9145     if (M != -1)
9146       M = 2 * (M % 4) + (M / 8);
9147
9148   return DAG.getVectorShuffle(
9149       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
9150                                   DL, MVT::v8i16, V1, V2),
9151       DAG.getUNDEF(MVT::v8i16), Mask);
9152 }
9153
9154 /// \brief Generic lowering of 8-lane i16 shuffles.
9155 ///
9156 /// This handles both single-input shuffles and combined shuffle/blends with
9157 /// two inputs. The single input shuffles are immediately delegated to
9158 /// a dedicated lowering routine.
9159 ///
9160 /// The blends are lowered in one of three fundamental ways. If there are few
9161 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9162 /// of the input is significantly cheaper when lowered as an interleaving of
9163 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9164 /// halves of the inputs separately (making them have relatively few inputs)
9165 /// and then concatenate them.
9166 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9167                                        const X86Subtarget *Subtarget,
9168                                        SelectionDAG &DAG) {
9169   SDLoc DL(Op);
9170   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9171   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9172   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9173   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9174   ArrayRef<int> OrigMask = SVOp->getMask();
9175   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9176                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9177   MutableArrayRef<int> Mask(MaskStorage);
9178
9179   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9180
9181   // Whenever we can lower this as a zext, that instruction is strictly faster
9182   // than any alternative.
9183   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9184           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9185     return ZExt;
9186
9187   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9188   auto isV2 = [](int M) { return M >= 8; };
9189
9190   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
9191   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9192
9193   if (NumV2Inputs == 0)
9194     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
9195
9196   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
9197                             "to be V1-input shuffles.");
9198
9199   // Try to use byte shift instructions.
9200   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9201           DL, MVT::v8i16, V1, V2, Mask, DAG))
9202     return Shift;
9203
9204   // There are special ways we can lower some single-element blends.
9205   if (NumV2Inputs == 1)
9206     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
9207                                                          Mask, Subtarget, DAG))
9208       return V;
9209
9210   // Use dedicated unpack instructions for masks that match their pattern.
9211   if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 2, 10, 3, 11))
9212     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9213   if (isShuffleEquivalent(Mask, 4, 12, 5, 13, 6, 14, 7, 15))
9214     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9215
9216   if (Subtarget->hasSSE41())
9217     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9218                                                   Subtarget, DAG))
9219       return Blend;
9220
9221   // Try to use byte rotation instructions.
9222   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9223           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9224     return Rotate;
9225
9226   if (NumV1Inputs + NumV2Inputs <= 4)
9227     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
9228
9229   // Check whether an interleaving lowering is likely to be more efficient.
9230   // This isn't perfect but it is a strong heuristic that tends to work well on
9231   // the kinds of shuffles that show up in practice.
9232   //
9233   // FIXME: Handle 1x, 2x, and 4x interleaving.
9234   if (shouldLowerAsInterleaving(Mask)) {
9235     // FIXME: Figure out whether we should pack these into the low or high
9236     // halves.
9237
9238     int EMask[8], OMask[8];
9239     for (int i = 0; i < 4; ++i) {
9240       EMask[i] = Mask[2*i];
9241       OMask[i] = Mask[2*i + 1];
9242       EMask[i + 4] = -1;
9243       OMask[i + 4] = -1;
9244     }
9245
9246     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
9247     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
9248
9249     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
9250   }
9251
9252   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9253   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9254
9255   for (int i = 0; i < 4; ++i) {
9256     LoBlendMask[i] = Mask[i];
9257     HiBlendMask[i] = Mask[i + 4];
9258   }
9259
9260   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9261   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9262   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
9263   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
9264
9265   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9266                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
9267 }
9268
9269 /// \brief Check whether a compaction lowering can be done by dropping even
9270 /// elements and compute how many times even elements must be dropped.
9271 ///
9272 /// This handles shuffles which take every Nth element where N is a power of
9273 /// two. Example shuffle masks:
9274 ///
9275 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9276 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9277 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9278 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9279 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9280 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9281 ///
9282 /// Any of these lanes can of course be undef.
9283 ///
9284 /// This routine only supports N <= 3.
9285 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9286 /// for larger N.
9287 ///
9288 /// \returns N above, or the number of times even elements must be dropped if
9289 /// there is such a number. Otherwise returns zero.
9290 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9291   // Figure out whether we're looping over two inputs or just one.
9292   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9293
9294   // The modulus for the shuffle vector entries is based on whether this is
9295   // a single input or not.
9296   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9297   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9298          "We should only be called with masks with a power-of-2 size!");
9299
9300   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9301
9302   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9303   // and 2^3 simultaneously. This is because we may have ambiguity with
9304   // partially undef inputs.
9305   bool ViableForN[3] = {true, true, true};
9306
9307   for (int i = 0, e = Mask.size(); i < e; ++i) {
9308     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9309     // want.
9310     if (Mask[i] == -1)
9311       continue;
9312
9313     bool IsAnyViable = false;
9314     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9315       if (ViableForN[j]) {
9316         uint64_t N = j + 1;
9317
9318         // The shuffle mask must be equal to (i * 2^N) % M.
9319         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9320           IsAnyViable = true;
9321         else
9322           ViableForN[j] = false;
9323       }
9324     // Early exit if we exhaust the possible powers of two.
9325     if (!IsAnyViable)
9326       break;
9327   }
9328
9329   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9330     if (ViableForN[j])
9331       return j + 1;
9332
9333   // Return 0 as there is no viable power of two.
9334   return 0;
9335 }
9336
9337 /// \brief Generic lowering of v16i8 shuffles.
9338 ///
9339 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9340 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9341 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9342 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9343 /// back together.
9344 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9345                                        const X86Subtarget *Subtarget,
9346                                        SelectionDAG &DAG) {
9347   SDLoc DL(Op);
9348   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9349   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9350   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9351   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9352   ArrayRef<int> OrigMask = SVOp->getMask();
9353   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9354
9355   // Try to use byte shift instructions.
9356   if (SDValue Shift = lowerVectorShuffleAsByteShift(
9357           DL, MVT::v16i8, V1, V2, OrigMask, DAG))
9358     return Shift;
9359
9360   // Try to use byte rotation instructions.
9361   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9362           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9363     return Rotate;
9364
9365   // Try to use a zext lowering.
9366   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9367           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
9368     return ZExt;
9369
9370   int MaskStorage[16] = {
9371       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
9372       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
9373       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
9374       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
9375   MutableArrayRef<int> Mask(MaskStorage);
9376   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
9377   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
9378
9379   int NumV2Elements =
9380       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9381
9382   // For single-input shuffles, there are some nicer lowering tricks we can use.
9383   if (NumV2Elements == 0) {
9384     // Check for being able to broadcast a single element.
9385     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i8, DL, V1,
9386                                                           Mask, Subtarget, DAG))
9387       return Broadcast;
9388
9389     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9390     // Notably, this handles splat and partial-splat shuffles more efficiently.
9391     // However, it only makes sense if the pre-duplication shuffle simplifies
9392     // things significantly. Currently, this means we need to be able to
9393     // express the pre-duplication shuffle as an i16 shuffle.
9394     //
9395     // FIXME: We should check for other patterns which can be widened into an
9396     // i16 shuffle as well.
9397     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9398       for (int i = 0; i < 16; i += 2)
9399         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9400           return false;
9401
9402       return true;
9403     };
9404     auto tryToWidenViaDuplication = [&]() -> SDValue {
9405       if (!canWidenViaDuplication(Mask))
9406         return SDValue();
9407       SmallVector<int, 4> LoInputs;
9408       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9409                    [](int M) { return M >= 0 && M < 8; });
9410       std::sort(LoInputs.begin(), LoInputs.end());
9411       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9412                      LoInputs.end());
9413       SmallVector<int, 4> HiInputs;
9414       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9415                    [](int M) { return M >= 8; });
9416       std::sort(HiInputs.begin(), HiInputs.end());
9417       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9418                      HiInputs.end());
9419
9420       bool TargetLo = LoInputs.size() >= HiInputs.size();
9421       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9422       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9423
9424       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9425       SmallDenseMap<int, int, 8> LaneMap;
9426       for (int I : InPlaceInputs) {
9427         PreDupI16Shuffle[I/2] = I/2;
9428         LaneMap[I] = I;
9429       }
9430       int j = TargetLo ? 0 : 4, je = j + 4;
9431       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9432         // Check if j is already a shuffle of this input. This happens when
9433         // there are two adjacent bytes after we move the low one.
9434         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9435           // If we haven't yet mapped the input, search for a slot into which
9436           // we can map it.
9437           while (j < je && PreDupI16Shuffle[j] != -1)
9438             ++j;
9439
9440           if (j == je)
9441             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9442             return SDValue();
9443
9444           // Map this input with the i16 shuffle.
9445           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9446         }
9447
9448         // Update the lane map based on the mapping we ended up with.
9449         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9450       }
9451       V1 = DAG.getNode(
9452           ISD::BITCAST, DL, MVT::v16i8,
9453           DAG.getVectorShuffle(MVT::v8i16, DL,
9454                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9455                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9456
9457       // Unpack the bytes to form the i16s that will be shuffled into place.
9458       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9459                        MVT::v16i8, V1, V1);
9460
9461       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9462       for (int i = 0; i < 16; ++i)
9463         if (Mask[i] != -1) {
9464           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9465           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9466           if (PostDupI16Shuffle[i / 2] == -1)
9467             PostDupI16Shuffle[i / 2] = MappedMask;
9468           else
9469             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9470                    "Conflicting entrties in the original shuffle!");
9471         }
9472       return DAG.getNode(
9473           ISD::BITCAST, DL, MVT::v16i8,
9474           DAG.getVectorShuffle(MVT::v8i16, DL,
9475                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
9476                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9477     };
9478     if (SDValue V = tryToWidenViaDuplication())
9479       return V;
9480   }
9481
9482   // Check whether an interleaving lowering is likely to be more efficient.
9483   // This isn't perfect but it is a strong heuristic that tends to work well on
9484   // the kinds of shuffles that show up in practice.
9485   //
9486   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
9487   if (shouldLowerAsInterleaving(Mask)) {
9488     int NumLoHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9489       return (M >= 0 && M < 8) || (M >= 16 && M < 24);
9490     });
9491     int NumHiHalf = std::count_if(Mask.begin(), Mask.end(), [](int M) {
9492       return (M >= 8 && M < 16) || M >= 24;
9493     });
9494     int EMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9495                      -1, -1, -1, -1, -1, -1, -1, -1};
9496     int OMask[16] = {-1, -1, -1, -1, -1, -1, -1, -1,
9497                      -1, -1, -1, -1, -1, -1, -1, -1};
9498     bool UnpackLo = NumLoHalf >= NumHiHalf;
9499     MutableArrayRef<int> TargetEMask(UnpackLo ? EMask : EMask + 8, 8);
9500     MutableArrayRef<int> TargetOMask(UnpackLo ? OMask : OMask + 8, 8);
9501     for (int i = 0; i < 8; ++i) {
9502       TargetEMask[i] = Mask[2 * i];
9503       TargetOMask[i] = Mask[2 * i + 1];
9504     }
9505
9506     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9507     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9508
9509     return DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9510                        MVT::v16i8, Evens, Odds);
9511   }
9512
9513   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9514   // with PSHUFB. It is important to do this before we attempt to generate any
9515   // blends but after all of the single-input lowerings. If the single input
9516   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9517   // want to preserve that and we can DAG combine any longer sequences into
9518   // a PSHUFB in the end. But once we start blending from multiple inputs,
9519   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9520   // and there are *very* few patterns that would actually be faster than the
9521   // PSHUFB approach because of its ability to zero lanes.
9522   //
9523   // FIXME: The only exceptions to the above are blends which are exact
9524   // interleavings with direct instructions supporting them. We currently don't
9525   // handle those well here.
9526   if (Subtarget->hasSSSE3()) {
9527     SDValue V1Mask[16];
9528     SDValue V2Mask[16];
9529     for (int i = 0; i < 16; ++i)
9530       if (Mask[i] == -1) {
9531         V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9532       } else {
9533         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
9534         V2Mask[i] =
9535             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
9536       }
9537     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9538                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9539     if (isSingleInputShuffleMask(Mask))
9540       return V1; // Single inputs are easy.
9541
9542     // Otherwise, blend the two.
9543     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9544                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9545     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9546   }
9547
9548   // There are special ways we can lower some single-element blends.
9549   if (NumV2Elements == 1)
9550     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9551                                                          Mask, Subtarget, DAG))
9552       return V;
9553
9554   // Check whether a compaction lowering can be done. This handles shuffles
9555   // which take every Nth element for some even N. See the helper function for
9556   // details.
9557   //
9558   // We special case these as they can be particularly efficiently handled with
9559   // the PACKUSB instruction on x86 and they show up in common patterns of
9560   // rearranging bytes to truncate wide elements.
9561   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9562     // NumEvenDrops is the power of two stride of the elements. Another way of
9563     // thinking about it is that we need to drop the even elements this many
9564     // times to get the original input.
9565     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9566
9567     // First we need to zero all the dropped bytes.
9568     assert(NumEvenDrops <= 3 &&
9569            "No support for dropping even elements more than 3 times.");
9570     // We use the mask type to pick which bytes are preserved based on how many
9571     // elements are dropped.
9572     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9573     SDValue ByteClearMask =
9574         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9575                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9576     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9577     if (!IsSingleInput)
9578       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9579
9580     // Now pack things back together.
9581     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9582     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9583     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9584     for (int i = 1; i < NumEvenDrops; ++i) {
9585       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9586       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9587     }
9588
9589     return Result;
9590   }
9591
9592   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9593   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9594   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9595   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9596
9597   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9598                             MutableArrayRef<int> V1HalfBlendMask,
9599                             MutableArrayRef<int> V2HalfBlendMask) {
9600     for (int i = 0; i < 8; ++i)
9601       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9602         V1HalfBlendMask[i] = HalfMask[i];
9603         HalfMask[i] = i;
9604       } else if (HalfMask[i] >= 16) {
9605         V2HalfBlendMask[i] = HalfMask[i] - 16;
9606         HalfMask[i] = i + 8;
9607       }
9608   };
9609   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9610   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9611
9612   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9613
9614   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9615                              MutableArrayRef<int> HiBlendMask) {
9616     SDValue V1, V2;
9617     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9618     // them out and avoid using UNPCK{L,H} to extract the elements of V as
9619     // i16s.
9620     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9621                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
9622         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
9623                      [](int M) { return M >= 0 && M % 2 == 1; })) {
9624       // Use a mask to drop the high bytes.
9625       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
9626       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
9627                        DAG.getConstant(0x00FF, MVT::v8i16));
9628
9629       // This will be a single vector shuffle instead of a blend so nuke V2.
9630       V2 = DAG.getUNDEF(MVT::v8i16);
9631
9632       // Squash the masks to point directly into V1.
9633       for (int &M : LoBlendMask)
9634         if (M >= 0)
9635           M /= 2;
9636       for (int &M : HiBlendMask)
9637         if (M >= 0)
9638           M /= 2;
9639     } else {
9640       // Otherwise just unpack the low half of V into V1 and the high half into
9641       // V2 so that we can blend them as i16s.
9642       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9643                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9644       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9645                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9646     }
9647
9648     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9649     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9650     return std::make_pair(BlendedLo, BlendedHi);
9651   };
9652   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
9653   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
9654   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
9655
9656   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
9657   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
9658
9659   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9660 }
9661
9662 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9663 ///
9664 /// This routine breaks down the specific type of 128-bit shuffle and
9665 /// dispatches to the lowering routines accordingly.
9666 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9667                                         MVT VT, const X86Subtarget *Subtarget,
9668                                         SelectionDAG &DAG) {
9669   switch (VT.SimpleTy) {
9670   case MVT::v2i64:
9671     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9672   case MVT::v2f64:
9673     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9674   case MVT::v4i32:
9675     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9676   case MVT::v4f32:
9677     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9678   case MVT::v8i16:
9679     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9680   case MVT::v16i8:
9681     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9682
9683   default:
9684     llvm_unreachable("Unimplemented!");
9685   }
9686 }
9687
9688 /// \brief Helper function to test whether a shuffle mask could be
9689 /// simplified by widening the elements being shuffled.
9690 ///
9691 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9692 /// leaves it in an unspecified state.
9693 ///
9694 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9695 /// shuffle masks. The latter have the special property of a '-2' representing
9696 /// a zero-ed lane of a vector.
9697 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9698                                     SmallVectorImpl<int> &WidenedMask) {
9699   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9700     // If both elements are undef, its trivial.
9701     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9702       WidenedMask.push_back(SM_SentinelUndef);
9703       continue;
9704     }
9705
9706     // Check for an undef mask and a mask value properly aligned to fit with
9707     // a pair of values. If we find such a case, use the non-undef mask's value.
9708     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9709       WidenedMask.push_back(Mask[i + 1] / 2);
9710       continue;
9711     }
9712     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9713       WidenedMask.push_back(Mask[i] / 2);
9714       continue;
9715     }
9716
9717     // When zeroing, we need to spread the zeroing across both lanes to widen.
9718     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9719       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9720           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9721         WidenedMask.push_back(SM_SentinelZero);
9722         continue;
9723       }
9724       return false;
9725     }
9726
9727     // Finally check if the two mask values are adjacent and aligned with
9728     // a pair.
9729     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9730       WidenedMask.push_back(Mask[i] / 2);
9731       continue;
9732     }
9733
9734     // Otherwise we can't safely widen the elements used in this shuffle.
9735     return false;
9736   }
9737   assert(WidenedMask.size() == Mask.size() / 2 &&
9738          "Incorrect size of mask after widening the elements!");
9739
9740   return true;
9741 }
9742
9743 /// \brief Generic routine to split ector shuffle into half-sized shuffles.
9744 ///
9745 /// This routine just extracts two subvectors, shuffles them independently, and
9746 /// then concatenates them back together. This should work effectively with all
9747 /// AVX vector shuffle types.
9748 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9749                                           SDValue V2, ArrayRef<int> Mask,
9750                                           SelectionDAG &DAG) {
9751   assert(VT.getSizeInBits() >= 256 &&
9752          "Only for 256-bit or wider vector shuffles!");
9753   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9754   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9755
9756   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9757   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9758
9759   int NumElements = VT.getVectorNumElements();
9760   int SplitNumElements = NumElements / 2;
9761   MVT ScalarVT = VT.getScalarType();
9762   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9763
9764   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9765                              DAG.getIntPtrConstant(0));
9766   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9767                              DAG.getIntPtrConstant(SplitNumElements));
9768   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9769                              DAG.getIntPtrConstant(0));
9770   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9771                              DAG.getIntPtrConstant(SplitNumElements));
9772
9773   // Now create two 4-way blends of these half-width vectors.
9774   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9775     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9776     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9777     for (int i = 0; i < SplitNumElements; ++i) {
9778       int M = HalfMask[i];
9779       if (M >= NumElements) {
9780         if (M >= NumElements + SplitNumElements)
9781           UseHiV2 = true;
9782         else
9783           UseLoV2 = true;
9784         V2BlendMask.push_back(M - NumElements);
9785         V1BlendMask.push_back(-1);
9786         BlendMask.push_back(SplitNumElements + i);
9787       } else if (M >= 0) {
9788         if (M >= SplitNumElements)
9789           UseHiV1 = true;
9790         else
9791           UseLoV1 = true;
9792         V2BlendMask.push_back(-1);
9793         V1BlendMask.push_back(M);
9794         BlendMask.push_back(i);
9795       } else {
9796         V2BlendMask.push_back(-1);
9797         V1BlendMask.push_back(-1);
9798         BlendMask.push_back(-1);
9799       }
9800     }
9801
9802     // Because the lowering happens after all combining takes place, we need to
9803     // manually combine these blend masks as much as possible so that we create
9804     // a minimal number of high-level vector shuffle nodes.
9805
9806     // First try just blending the halves of V1 or V2.
9807     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9808       return DAG.getUNDEF(SplitVT);
9809     if (!UseLoV2 && !UseHiV2)
9810       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9811     if (!UseLoV1 && !UseHiV1)
9812       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9813
9814     SDValue V1Blend, V2Blend;
9815     if (UseLoV1 && UseHiV1) {
9816       V1Blend =
9817         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9818     } else {
9819       // We only use half of V1 so map the usage down into the final blend mask.
9820       V1Blend = UseLoV1 ? LoV1 : HiV1;
9821       for (int i = 0; i < SplitNumElements; ++i)
9822         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9823           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9824     }
9825     if (UseLoV2 && UseHiV2) {
9826       V2Blend =
9827         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9828     } else {
9829       // We only use half of V2 so map the usage down into the final blend mask.
9830       V2Blend = UseLoV2 ? LoV2 : HiV2;
9831       for (int i = 0; i < SplitNumElements; ++i)
9832         if (BlendMask[i] >= SplitNumElements)
9833           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9834     }
9835     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9836   };
9837   SDValue Lo = HalfBlend(LoMask);
9838   SDValue Hi = HalfBlend(HiMask);
9839   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9840 }
9841
9842 /// \brief Either split a vector in halves or decompose the shuffles and the
9843 /// blend.
9844 ///
9845 /// This is provided as a good fallback for many lowerings of non-single-input
9846 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9847 /// between splitting the shuffle into 128-bit components and stitching those
9848 /// back together vs. extracting the single-input shuffles and blending those
9849 /// results.
9850 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9851                                                 SDValue V2, ArrayRef<int> Mask,
9852                                                 SelectionDAG &DAG) {
9853   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9854                                             "lower single-input shuffles as it "
9855                                             "could then recurse on itself.");
9856   int Size = Mask.size();
9857
9858   // If this can be modeled as a broadcast of two elements followed by a blend,
9859   // prefer that lowering. This is especially important because broadcasts can
9860   // often fold with memory operands.
9861   auto DoBothBroadcast = [&] {
9862     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9863     for (int M : Mask)
9864       if (M >= Size) {
9865         if (V2BroadcastIdx == -1)
9866           V2BroadcastIdx = M - Size;
9867         else if (M - Size != V2BroadcastIdx)
9868           return false;
9869       } else if (M >= 0) {
9870         if (V1BroadcastIdx == -1)
9871           V1BroadcastIdx = M;
9872         else if (M != V1BroadcastIdx)
9873           return false;
9874       }
9875     return true;
9876   };
9877   if (DoBothBroadcast())
9878     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9879                                                       DAG);
9880
9881   // If the inputs all stem from a single 128-bit lane of each input, then we
9882   // split them rather than blending because the split will decompose to
9883   // unusually few instructions.
9884   int LaneCount = VT.getSizeInBits() / 128;
9885   int LaneSize = Size / LaneCount;
9886   SmallBitVector LaneInputs[2];
9887   LaneInputs[0].resize(LaneCount, false);
9888   LaneInputs[1].resize(LaneCount, false);
9889   for (int i = 0; i < Size; ++i)
9890     if (Mask[i] >= 0)
9891       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9892   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9893     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9894
9895   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9896   // that the decomposed single-input shuffles don't end up here.
9897   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9898 }
9899
9900 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9901 /// a permutation and blend of those lanes.
9902 ///
9903 /// This essentially blends the out-of-lane inputs to each lane into the lane
9904 /// from a permuted copy of the vector. This lowering strategy results in four
9905 /// instructions in the worst case for a single-input cross lane shuffle which
9906 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9907 /// of. Special cases for each particular shuffle pattern should be handled
9908 /// prior to trying this lowering.
9909 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9910                                                        SDValue V1, SDValue V2,
9911                                                        ArrayRef<int> Mask,
9912                                                        SelectionDAG &DAG) {
9913   // FIXME: This should probably be generalized for 512-bit vectors as well.
9914   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9915   int LaneSize = Mask.size() / 2;
9916
9917   // If there are only inputs from one 128-bit lane, splitting will in fact be
9918   // less expensive. The flags track wether the given lane contains an element
9919   // that crosses to another lane.
9920   bool LaneCrossing[2] = {false, false};
9921   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9922     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9923       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9924   if (!LaneCrossing[0] || !LaneCrossing[1])
9925     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9926
9927   if (isSingleInputShuffleMask(Mask)) {
9928     SmallVector<int, 32> FlippedBlendMask;
9929     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9930       FlippedBlendMask.push_back(
9931           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9932                                   ? Mask[i]
9933                                   : Mask[i] % LaneSize +
9934                                         (i / LaneSize) * LaneSize + Size));
9935
9936     // Flip the vector, and blend the results which should now be in-lane. The
9937     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9938     // 5 for the high source. The value 3 selects the high half of source 2 and
9939     // the value 2 selects the low half of source 2. We only use source 2 to
9940     // allow folding it into a memory operand.
9941     unsigned PERMMask = 3 | 2 << 4;
9942     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9943                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9944     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9945   }
9946
9947   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9948   // will be handled by the above logic and a blend of the results, much like
9949   // other patterns in AVX.
9950   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9951 }
9952
9953 /// \brief Handle lowering 2-lane 128-bit shuffles.
9954 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9955                                         SDValue V2, ArrayRef<int> Mask,
9956                                         const X86Subtarget *Subtarget,
9957                                         SelectionDAG &DAG) {
9958   // Blends are faster and handle all the non-lane-crossing cases.
9959   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9960                                                 Subtarget, DAG))
9961     return Blend;
9962
9963   MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9964                                VT.getVectorNumElements() / 2);
9965   // Check for patterns which can be matched with a single insert of a 128-bit
9966   // subvector.
9967   if (isShuffleEquivalent(Mask, 0, 1, 0, 1) ||
9968       isShuffleEquivalent(Mask, 0, 1, 4, 5)) {
9969     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9970                               DAG.getIntPtrConstant(0));
9971     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9972                               Mask[2] < 4 ? V1 : V2, DAG.getIntPtrConstant(0));
9973     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9974   }
9975   if (isShuffleEquivalent(Mask, 0, 1, 6, 7)) {
9976     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9977                               DAG.getIntPtrConstant(0));
9978     SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
9979                               DAG.getIntPtrConstant(2));
9980     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9981   }
9982
9983   // Otherwise form a 128-bit permutation.
9984   // FIXME: Detect zero-vector inputs and use the VPERM2X128 to zero that half.
9985   unsigned PermMask = Mask[0] / 2 | (Mask[2] / 2) << 4;
9986   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9987                      DAG.getConstant(PermMask, MVT::i8));
9988 }
9989
9990 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9991 /// shuffling each lane.
9992 ///
9993 /// This will only succeed when the result of fixing the 128-bit lanes results
9994 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9995 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9996 /// the lane crosses early and then use simpler shuffles within each lane.
9997 ///
9998 /// FIXME: It might be worthwhile at some point to support this without
9999 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10000 /// in x86 only floating point has interesting non-repeating shuffles, and even
10001 /// those are still *marginally* more expensive.
10002 static SDValue lowerVectorShuffleByMerging128BitLanes(
10003     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10004     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10005   assert(!isSingleInputShuffleMask(Mask) &&
10006          "This is only useful with multiple inputs.");
10007
10008   int Size = Mask.size();
10009   int LaneSize = 128 / VT.getScalarSizeInBits();
10010   int NumLanes = Size / LaneSize;
10011   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10012
10013   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10014   // check whether the in-128-bit lane shuffles share a repeating pattern.
10015   SmallVector<int, 4> Lanes;
10016   Lanes.resize(NumLanes, -1);
10017   SmallVector<int, 4> InLaneMask;
10018   InLaneMask.resize(LaneSize, -1);
10019   for (int i = 0; i < Size; ++i) {
10020     if (Mask[i] < 0)
10021       continue;
10022
10023     int j = i / LaneSize;
10024
10025     if (Lanes[j] < 0) {
10026       // First entry we've seen for this lane.
10027       Lanes[j] = Mask[i] / LaneSize;
10028     } else if (Lanes[j] != Mask[i] / LaneSize) {
10029       // This doesn't match the lane selected previously!
10030       return SDValue();
10031     }
10032
10033     // Check that within each lane we have a consistent shuffle mask.
10034     int k = i % LaneSize;
10035     if (InLaneMask[k] < 0) {
10036       InLaneMask[k] = Mask[i] % LaneSize;
10037     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10038       // This doesn't fit a repeating in-lane mask.
10039       return SDValue();
10040     }
10041   }
10042
10043   // First shuffle the lanes into place.
10044   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10045                                 VT.getSizeInBits() / 64);
10046   SmallVector<int, 8> LaneMask;
10047   LaneMask.resize(NumLanes * 2, -1);
10048   for (int i = 0; i < NumLanes; ++i)
10049     if (Lanes[i] >= 0) {
10050       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10051       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10052     }
10053
10054   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
10055   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
10056   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10057
10058   // Cast it back to the type we actually want.
10059   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
10060
10061   // Now do a simple shuffle that isn't lane crossing.
10062   SmallVector<int, 8> NewMask;
10063   NewMask.resize(Size, -1);
10064   for (int i = 0; i < Size; ++i)
10065     if (Mask[i] >= 0)
10066       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10067   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10068          "Must not introduce lane crosses at this point!");
10069
10070   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10071 }
10072
10073 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10074 /// given mask.
10075 ///
10076 /// This returns true if the elements from a particular input are already in the
10077 /// slot required by the given mask and require no permutation.
10078 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10079   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10080   int Size = Mask.size();
10081   for (int i = 0; i < Size; ++i)
10082     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10083       return false;
10084
10085   return true;
10086 }
10087
10088 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10089 ///
10090 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10091 /// isn't available.
10092 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10093                                        const X86Subtarget *Subtarget,
10094                                        SelectionDAG &DAG) {
10095   SDLoc DL(Op);
10096   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10097   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10098   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10099   ArrayRef<int> Mask = SVOp->getMask();
10100   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10101
10102   SmallVector<int, 4> WidenedMask;
10103   if (canWidenShuffleElements(Mask, WidenedMask))
10104     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10105                                     DAG);
10106
10107   if (isSingleInputShuffleMask(Mask)) {
10108     // Check for being able to broadcast a single element.
10109     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4f64, DL, V1,
10110                                                           Mask, Subtarget, DAG))
10111       return Broadcast;
10112
10113     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10114       // Non-half-crossing single input shuffles can be lowerid with an
10115       // interleaved permutation.
10116       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10117                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10118       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10119                          DAG.getConstant(VPERMILPMask, MVT::i8));
10120     }
10121
10122     // With AVX2 we have direct support for this permutation.
10123     if (Subtarget->hasAVX2())
10124       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10125                          getV4X86ShuffleImm8ForMask(Mask, DAG));
10126
10127     // Otherwise, fall back.
10128     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10129                                                    DAG);
10130   }
10131
10132   // X86 has dedicated unpack instructions that can handle specific blend
10133   // operations: UNPCKH and UNPCKL.
10134   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10135     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10136   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10137     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10138
10139   // If we have a single input to the zero element, insert that into V1 if we
10140   // can do so cheaply.
10141   int NumV2Elements =
10142       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
10143   if (NumV2Elements == 1 && Mask[0] >= 4)
10144     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10145             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
10146       return Insertion;
10147
10148   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10149                                                 Subtarget, DAG))
10150     return Blend;
10151
10152   // Check if the blend happens to exactly fit that of SHUFPD.
10153   if ((Mask[0] == -1 || Mask[0] < 2) &&
10154       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
10155       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
10156       (Mask[3] == -1 || Mask[3] >= 6)) {
10157     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
10158                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
10159     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
10160                        DAG.getConstant(SHUFPDMask, MVT::i8));
10161   }
10162   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
10163       (Mask[1] == -1 || Mask[1] < 2) &&
10164       (Mask[2] == -1 || Mask[2] >= 6) &&
10165       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
10166     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
10167                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
10168     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
10169                        DAG.getConstant(SHUFPDMask, MVT::i8));
10170   }
10171
10172   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10173   // shuffle. However, if we have AVX2 and either inputs are already in place,
10174   // we will be able to shuffle even across lanes the other input in a single
10175   // instruction so skip this pattern.
10176   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10177                                  isShuffleMaskInputInPlace(1, Mask))))
10178     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10179             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10180       return Result;
10181
10182   // If we have AVX2 then we always want to lower with a blend because an v4 we
10183   // can fully permute the elements.
10184   if (Subtarget->hasAVX2())
10185     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10186                                                       Mask, DAG);
10187
10188   // Otherwise fall back on generic lowering.
10189   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10190 }
10191
10192 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10193 ///
10194 /// This routine is only called when we have AVX2 and thus a reasonable
10195 /// instruction set for v4i64 shuffling..
10196 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10197                                        const X86Subtarget *Subtarget,
10198                                        SelectionDAG &DAG) {
10199   SDLoc DL(Op);
10200   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10201   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10202   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10203   ArrayRef<int> Mask = SVOp->getMask();
10204   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10205   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10206
10207   SmallVector<int, 4> WidenedMask;
10208   if (canWidenShuffleElements(Mask, WidenedMask))
10209     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10210                                     DAG);
10211
10212   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10213                                                 Subtarget, DAG))
10214     return Blend;
10215
10216   // Check for being able to broadcast a single element.
10217   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v4i64, DL, V1,
10218                                                         Mask, Subtarget, DAG))
10219     return Broadcast;
10220
10221   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10222   // use lower latency instructions that will operate on both 128-bit lanes.
10223   SmallVector<int, 2> RepeatedMask;
10224   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10225     if (isSingleInputShuffleMask(Mask)) {
10226       int PSHUFDMask[] = {-1, -1, -1, -1};
10227       for (int i = 0; i < 2; ++i)
10228         if (RepeatedMask[i] >= 0) {
10229           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10230           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10231         }
10232       return DAG.getNode(
10233           ISD::BITCAST, DL, MVT::v4i64,
10234           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10235                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
10236                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
10237     }
10238
10239     // Use dedicated unpack instructions for masks that match their pattern.
10240     if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
10241       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10242     if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
10243       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10244   }
10245
10246   // AVX2 provides a direct instruction for permuting a single input across
10247   // lanes.
10248   if (isSingleInputShuffleMask(Mask))
10249     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10250                        getV4X86ShuffleImm8ForMask(Mask, DAG));
10251
10252   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10253   // shuffle. However, if we have AVX2 and either inputs are already in place,
10254   // we will be able to shuffle even across lanes the other input in a single
10255   // instruction so skip this pattern.
10256   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10257                                  isShuffleMaskInputInPlace(1, Mask))))
10258     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10259             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10260       return Result;
10261
10262   // Otherwise fall back on generic blend lowering.
10263   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10264                                                     Mask, DAG);
10265 }
10266
10267 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10268 ///
10269 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10270 /// isn't available.
10271 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10272                                        const X86Subtarget *Subtarget,
10273                                        SelectionDAG &DAG) {
10274   SDLoc DL(Op);
10275   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10276   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10277   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10278   ArrayRef<int> Mask = SVOp->getMask();
10279   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10280
10281   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10282                                                 Subtarget, DAG))
10283     return Blend;
10284
10285   // Check for being able to broadcast a single element.
10286   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8f32, DL, V1,
10287                                                         Mask, Subtarget, DAG))
10288     return Broadcast;
10289
10290   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10291   // options to efficiently lower the shuffle.
10292   SmallVector<int, 4> RepeatedMask;
10293   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10294     assert(RepeatedMask.size() == 4 &&
10295            "Repeated masks must be half the mask width!");
10296     if (isSingleInputShuffleMask(Mask))
10297       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10298                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10299
10300     // Use dedicated unpack instructions for masks that match their pattern.
10301     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10302       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10303     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10304       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10305
10306     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10307     // have already handled any direct blends. We also need to squash the
10308     // repeated mask into a simulated v4f32 mask.
10309     for (int i = 0; i < 4; ++i)
10310       if (RepeatedMask[i] >= 8)
10311         RepeatedMask[i] -= 4;
10312     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10313   }
10314
10315   // If we have a single input shuffle with different shuffle patterns in the
10316   // two 128-bit lanes use the variable mask to VPERMILPS.
10317   if (isSingleInputShuffleMask(Mask)) {
10318     SDValue VPermMask[8];
10319     for (int i = 0; i < 8; ++i)
10320       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10321                                  : DAG.getConstant(Mask[i], MVT::i32);
10322     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10323       return DAG.getNode(
10324           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10325           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10326
10327     if (Subtarget->hasAVX2())
10328       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
10329                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
10330                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
10331                                                  MVT::v8i32, VPermMask)),
10332                          V1);
10333
10334     // Otherwise, fall back.
10335     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10336                                                    DAG);
10337   }
10338
10339   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10340   // shuffle.
10341   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10342           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10343     return Result;
10344
10345   // If we have AVX2 then we always want to lower with a blend because at v8 we
10346   // can fully permute the elements.
10347   if (Subtarget->hasAVX2())
10348     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10349                                                       Mask, DAG);
10350
10351   // Otherwise fall back on generic lowering.
10352   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10353 }
10354
10355 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10356 ///
10357 /// This routine is only called when we have AVX2 and thus a reasonable
10358 /// instruction set for v8i32 shuffling..
10359 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10360                                        const X86Subtarget *Subtarget,
10361                                        SelectionDAG &DAG) {
10362   SDLoc DL(Op);
10363   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10364   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10365   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10366   ArrayRef<int> Mask = SVOp->getMask();
10367   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10368   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10369
10370   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10371                                                 Subtarget, DAG))
10372     return Blend;
10373
10374   // Check for being able to broadcast a single element.
10375   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v8i32, DL, V1,
10376                                                         Mask, Subtarget, DAG))
10377     return Broadcast;
10378
10379   // If the shuffle mask is repeated in each 128-bit lane we can use more
10380   // efficient instructions that mirror the shuffles across the two 128-bit
10381   // lanes.
10382   SmallVector<int, 4> RepeatedMask;
10383   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10384     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10385     if (isSingleInputShuffleMask(Mask))
10386       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10387                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
10388
10389     // Use dedicated unpack instructions for masks that match their pattern.
10390     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
10391       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10392     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
10393       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10394   }
10395
10396   // If the shuffle patterns aren't repeated but it is a single input, directly
10397   // generate a cross-lane VPERMD instruction.
10398   if (isSingleInputShuffleMask(Mask)) {
10399     SDValue VPermMask[8];
10400     for (int i = 0; i < 8; ++i)
10401       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10402                                  : DAG.getConstant(Mask[i], MVT::i32);
10403     return DAG.getNode(
10404         X86ISD::VPERMV, DL, MVT::v8i32,
10405         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10406   }
10407
10408   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10409   // shuffle.
10410   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10411           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10412     return Result;
10413
10414   // Otherwise fall back on generic blend lowering.
10415   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10416                                                     Mask, DAG);
10417 }
10418
10419 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10420 ///
10421 /// This routine is only called when we have AVX2 and thus a reasonable
10422 /// instruction set for v16i16 shuffling..
10423 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10424                                         const X86Subtarget *Subtarget,
10425                                         SelectionDAG &DAG) {
10426   SDLoc DL(Op);
10427   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10428   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10429   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10430   ArrayRef<int> Mask = SVOp->getMask();
10431   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10432   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10433
10434   // Check for being able to broadcast a single element.
10435   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v16i16, DL, V1,
10436                                                         Mask, Subtarget, DAG))
10437     return Broadcast;
10438
10439   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10440                                                 Subtarget, DAG))
10441     return Blend;
10442
10443   // Use dedicated unpack instructions for masks that match their pattern.
10444   if (isShuffleEquivalent(Mask,
10445                           // First 128-bit lane:
10446                           0, 16, 1, 17, 2, 18, 3, 19,
10447                           // Second 128-bit lane:
10448                           8, 24, 9, 25, 10, 26, 11, 27))
10449     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10450   if (isShuffleEquivalent(Mask,
10451                           // First 128-bit lane:
10452                           4, 20, 5, 21, 6, 22, 7, 23,
10453                           // Second 128-bit lane:
10454                           12, 28, 13, 29, 14, 30, 15, 31))
10455     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10456
10457   if (isSingleInputShuffleMask(Mask)) {
10458     // There are no generalized cross-lane shuffle operations available on i16
10459     // element types.
10460     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10461       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10462                                                      Mask, DAG);
10463
10464     SDValue PSHUFBMask[32];
10465     for (int i = 0; i < 16; ++i) {
10466       if (Mask[i] == -1) {
10467         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10468         continue;
10469       }
10470
10471       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10472       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10473       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
10474       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
10475     }
10476     return DAG.getNode(
10477         ISD::BITCAST, DL, MVT::v16i16,
10478         DAG.getNode(
10479             X86ISD::PSHUFB, DL, MVT::v32i8,
10480             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
10481             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
10482   }
10483
10484   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10485   // shuffle.
10486   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10487           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10488     return Result;
10489
10490   // Otherwise fall back on generic lowering.
10491   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10492 }
10493
10494 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10495 ///
10496 /// This routine is only called when we have AVX2 and thus a reasonable
10497 /// instruction set for v32i8 shuffling..
10498 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10499                                        const X86Subtarget *Subtarget,
10500                                        SelectionDAG &DAG) {
10501   SDLoc DL(Op);
10502   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10503   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10504   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10505   ArrayRef<int> Mask = SVOp->getMask();
10506   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10507   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10508
10509   // Check for being able to broadcast a single element.
10510   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(MVT::v32i8, DL, V1,
10511                                                         Mask, Subtarget, DAG))
10512     return Broadcast;
10513
10514   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10515                                                 Subtarget, DAG))
10516     return Blend;
10517
10518   // Use dedicated unpack instructions for masks that match their pattern.
10519   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10520   // 256-bit lanes.
10521   if (isShuffleEquivalent(
10522           Mask,
10523           // First 128-bit lane:
10524           0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10525           // Second 128-bit lane:
10526           16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55))
10527     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10528   if (isShuffleEquivalent(
10529           Mask,
10530           // First 128-bit lane:
10531           8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10532           // Second 128-bit lane:
10533           24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63))
10534     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10535
10536   if (isSingleInputShuffleMask(Mask)) {
10537     // There are no generalized cross-lane shuffle operations available on i8
10538     // element types.
10539     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10540       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10541                                                      Mask, DAG);
10542
10543     SDValue PSHUFBMask[32];
10544     for (int i = 0; i < 32; ++i)
10545       PSHUFBMask[i] =
10546           Mask[i] < 0
10547               ? DAG.getUNDEF(MVT::i8)
10548               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
10549
10550     return DAG.getNode(
10551         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10552         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10553   }
10554
10555   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10556   // shuffle.
10557   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10558           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10559     return Result;
10560
10561   // Otherwise fall back on generic lowering.
10562   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10563 }
10564
10565 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10566 ///
10567 /// This routine either breaks down the specific type of a 256-bit x86 vector
10568 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10569 /// together based on the available instructions.
10570 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10571                                         MVT VT, const X86Subtarget *Subtarget,
10572                                         SelectionDAG &DAG) {
10573   SDLoc DL(Op);
10574   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10575   ArrayRef<int> Mask = SVOp->getMask();
10576
10577   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10578   // check for those subtargets here and avoid much of the subtarget querying in
10579   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10580   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10581   // floating point types there eventually, just immediately cast everything to
10582   // a float and operate entirely in that domain.
10583   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10584     int ElementBits = VT.getScalarSizeInBits();
10585     if (ElementBits < 32)
10586       // No floating point type available, decompose into 128-bit vectors.
10587       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10588
10589     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10590                                 VT.getVectorNumElements());
10591     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10592     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10593     return DAG.getNode(ISD::BITCAST, DL, VT,
10594                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10595   }
10596
10597   switch (VT.SimpleTy) {
10598   case MVT::v4f64:
10599     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10600   case MVT::v4i64:
10601     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10602   case MVT::v8f32:
10603     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10604   case MVT::v8i32:
10605     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10606   case MVT::v16i16:
10607     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10608   case MVT::v32i8:
10609     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10610
10611   default:
10612     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10613   }
10614 }
10615
10616 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10617 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10618                                        const X86Subtarget *Subtarget,
10619                                        SelectionDAG &DAG) {
10620   SDLoc DL(Op);
10621   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10622   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10623   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10624   ArrayRef<int> Mask = SVOp->getMask();
10625   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10626
10627   // FIXME: Implement direct support for this type!
10628   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10629 }
10630
10631 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10632 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10633                                        const X86Subtarget *Subtarget,
10634                                        SelectionDAG &DAG) {
10635   SDLoc DL(Op);
10636   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10637   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10638   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10639   ArrayRef<int> Mask = SVOp->getMask();
10640   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10641
10642   // FIXME: Implement direct support for this type!
10643   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10644 }
10645
10646 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10647 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10648                                        const X86Subtarget *Subtarget,
10649                                        SelectionDAG &DAG) {
10650   SDLoc DL(Op);
10651   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10652   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10653   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10654   ArrayRef<int> Mask = SVOp->getMask();
10655   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10656
10657   // FIXME: Implement direct support for this type!
10658   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10659 }
10660
10661 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10662 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10663                                        const X86Subtarget *Subtarget,
10664                                        SelectionDAG &DAG) {
10665   SDLoc DL(Op);
10666   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10667   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10668   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10669   ArrayRef<int> Mask = SVOp->getMask();
10670   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10671
10672   // FIXME: Implement direct support for this type!
10673   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10674 }
10675
10676 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10677 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10678                                         const X86Subtarget *Subtarget,
10679                                         SelectionDAG &DAG) {
10680   SDLoc DL(Op);
10681   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10682   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10683   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10684   ArrayRef<int> Mask = SVOp->getMask();
10685   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10686   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10687
10688   // FIXME: Implement direct support for this type!
10689   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10690 }
10691
10692 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10693 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10694                                        const X86Subtarget *Subtarget,
10695                                        SelectionDAG &DAG) {
10696   SDLoc DL(Op);
10697   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10698   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10699   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10700   ArrayRef<int> Mask = SVOp->getMask();
10701   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10702   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10703
10704   // FIXME: Implement direct support for this type!
10705   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10706 }
10707
10708 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10709 ///
10710 /// This routine either breaks down the specific type of a 512-bit x86 vector
10711 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10712 /// together based on the available instructions.
10713 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10714                                         MVT VT, const X86Subtarget *Subtarget,
10715                                         SelectionDAG &DAG) {
10716   SDLoc DL(Op);
10717   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10718   ArrayRef<int> Mask = SVOp->getMask();
10719   assert(Subtarget->hasAVX512() &&
10720          "Cannot lower 512-bit vectors w/ basic ISA!");
10721
10722   // Check for being able to broadcast a single element.
10723   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(VT.SimpleTy, DL, V1,
10724                                                         Mask, Subtarget, DAG))
10725     return Broadcast;
10726
10727   // Dispatch to each element type for lowering. If we don't have supprot for
10728   // specific element type shuffles at 512 bits, immediately split them and
10729   // lower them. Each lowering routine of a given type is allowed to assume that
10730   // the requisite ISA extensions for that element type are available.
10731   switch (VT.SimpleTy) {
10732   case MVT::v8f64:
10733     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10734   case MVT::v16f32:
10735     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10736   case MVT::v8i64:
10737     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10738   case MVT::v16i32:
10739     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10740   case MVT::v32i16:
10741     if (Subtarget->hasBWI())
10742       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10743     break;
10744   case MVT::v64i8:
10745     if (Subtarget->hasBWI())
10746       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10747     break;
10748
10749   default:
10750     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10751   }
10752
10753   // Otherwise fall back on splitting.
10754   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10755 }
10756
10757 /// \brief Top-level lowering for x86 vector shuffles.
10758 ///
10759 /// This handles decomposition, canonicalization, and lowering of all x86
10760 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10761 /// above in helper routines. The canonicalization attempts to widen shuffles
10762 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10763 /// s.t. only one of the two inputs needs to be tested, etc.
10764 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10765                                   SelectionDAG &DAG) {
10766   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10767   ArrayRef<int> Mask = SVOp->getMask();
10768   SDValue V1 = Op.getOperand(0);
10769   SDValue V2 = Op.getOperand(1);
10770   MVT VT = Op.getSimpleValueType();
10771   int NumElements = VT.getVectorNumElements();
10772   SDLoc dl(Op);
10773
10774   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10775
10776   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10777   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10778   if (V1IsUndef && V2IsUndef)
10779     return DAG.getUNDEF(VT);
10780
10781   // When we create a shuffle node we put the UNDEF node to second operand,
10782   // but in some cases the first operand may be transformed to UNDEF.
10783   // In this case we should just commute the node.
10784   if (V1IsUndef)
10785     return DAG.getCommutedVectorShuffle(*SVOp);
10786
10787   // Check for non-undef masks pointing at an undef vector and make the masks
10788   // undef as well. This makes it easier to match the shuffle based solely on
10789   // the mask.
10790   if (V2IsUndef)
10791     for (int M : Mask)
10792       if (M >= NumElements) {
10793         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10794         for (int &M : NewMask)
10795           if (M >= NumElements)
10796             M = -1;
10797         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10798       }
10799
10800   // Try to collapse shuffles into using a vector type with fewer elements but
10801   // wider element types. We cap this to not form integers or floating point
10802   // elements wider than 64 bits, but it might be interesting to form i128
10803   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10804   SmallVector<int, 16> WidenedMask;
10805   if (VT.getScalarSizeInBits() < 64 &&
10806       canWidenShuffleElements(Mask, WidenedMask)) {
10807     MVT NewEltVT = VT.isFloatingPoint()
10808                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10809                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10810     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10811     // Make sure that the new vector type is legal. For example, v2f64 isn't
10812     // legal on SSE1.
10813     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10814       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10815       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10816       return DAG.getNode(ISD::BITCAST, dl, VT,
10817                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10818     }
10819   }
10820
10821   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10822   for (int M : SVOp->getMask())
10823     if (M < 0)
10824       ++NumUndefElements;
10825     else if (M < NumElements)
10826       ++NumV1Elements;
10827     else
10828       ++NumV2Elements;
10829
10830   // Commute the shuffle as needed such that more elements come from V1 than
10831   // V2. This allows us to match the shuffle pattern strictly on how many
10832   // elements come from V1 without handling the symmetric cases.
10833   if (NumV2Elements > NumV1Elements)
10834     return DAG.getCommutedVectorShuffle(*SVOp);
10835
10836   // When the number of V1 and V2 elements are the same, try to minimize the
10837   // number of uses of V2 in the low half of the vector. When that is tied,
10838   // ensure that the sum of indices for V1 is equal to or lower than the sum
10839   // indices for V2. When those are equal, try to ensure that the number of odd
10840   // indices for V1 is lower than the number of odd indices for V2.
10841   if (NumV1Elements == NumV2Elements) {
10842     int LowV1Elements = 0, LowV2Elements = 0;
10843     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10844       if (M >= NumElements)
10845         ++LowV2Elements;
10846       else if (M >= 0)
10847         ++LowV1Elements;
10848     if (LowV2Elements > LowV1Elements) {
10849       return DAG.getCommutedVectorShuffle(*SVOp);
10850     } else if (LowV2Elements == LowV1Elements) {
10851       int SumV1Indices = 0, SumV2Indices = 0;
10852       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10853         if (SVOp->getMask()[i] >= NumElements)
10854           SumV2Indices += i;
10855         else if (SVOp->getMask()[i] >= 0)
10856           SumV1Indices += i;
10857       if (SumV2Indices < SumV1Indices) {
10858         return DAG.getCommutedVectorShuffle(*SVOp);
10859       } else if (SumV2Indices == SumV1Indices) {
10860         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10861         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10862           if (SVOp->getMask()[i] >= NumElements)
10863             NumV2OddIndices += i % 2;
10864           else if (SVOp->getMask()[i] >= 0)
10865             NumV1OddIndices += i % 2;
10866         if (NumV2OddIndices < NumV1OddIndices)
10867           return DAG.getCommutedVectorShuffle(*SVOp);
10868       }
10869     }
10870   }
10871
10872   // For each vector width, delegate to a specialized lowering routine.
10873   if (VT.getSizeInBits() == 128)
10874     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10875
10876   if (VT.getSizeInBits() == 256)
10877     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10878
10879   // Force AVX-512 vectors to be scalarized for now.
10880   // FIXME: Implement AVX-512 support!
10881   if (VT.getSizeInBits() == 512)
10882     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10883
10884   llvm_unreachable("Unimplemented!");
10885 }
10886
10887
10888 //===----------------------------------------------------------------------===//
10889 // Legacy vector shuffle lowering
10890 //
10891 // This code is the legacy code handling vector shuffles until the above
10892 // replaces its functionality and performance.
10893 //===----------------------------------------------------------------------===//
10894
10895 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
10896                         bool hasInt256, unsigned *MaskOut = nullptr) {
10897   MVT EltVT = VT.getVectorElementType();
10898
10899   // There is no blend with immediate in AVX-512.
10900   if (VT.is512BitVector())
10901     return false;
10902
10903   if (!hasSSE41 || EltVT == MVT::i8)
10904     return false;
10905   if (!hasInt256 && VT == MVT::v16i16)
10906     return false;
10907
10908   unsigned MaskValue = 0;
10909   unsigned NumElems = VT.getVectorNumElements();
10910   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10911   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10912   unsigned NumElemsInLane = NumElems / NumLanes;
10913
10914   // Blend for v16i16 should be symetric for the both lanes.
10915   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10916
10917     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
10918     int EltIdx = MaskVals[i];
10919
10920     if ((EltIdx < 0 || EltIdx == (int)i) &&
10921         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
10922       continue;
10923
10924     if (((unsigned)EltIdx == (i + NumElems)) &&
10925         (SndLaneEltIdx < 0 ||
10926          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
10927       MaskValue |= (1 << i);
10928     else
10929       return false;
10930   }
10931
10932   if (MaskOut)
10933     *MaskOut = MaskValue;
10934   return true;
10935 }
10936
10937 // Try to lower a shuffle node into a simple blend instruction.
10938 // This function assumes isBlendMask returns true for this
10939 // SuffleVectorSDNode
10940 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
10941                                           unsigned MaskValue,
10942                                           const X86Subtarget *Subtarget,
10943                                           SelectionDAG &DAG) {
10944   MVT VT = SVOp->getSimpleValueType(0);
10945   MVT EltVT = VT.getVectorElementType();
10946   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
10947                      Subtarget->hasInt256() && "Trying to lower a "
10948                                                "VECTOR_SHUFFLE to a Blend but "
10949                                                "with the wrong mask"));
10950   SDValue V1 = SVOp->getOperand(0);
10951   SDValue V2 = SVOp->getOperand(1);
10952   SDLoc dl(SVOp);
10953   unsigned NumElems = VT.getVectorNumElements();
10954
10955   // Convert i32 vectors to floating point if it is not AVX2.
10956   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10957   MVT BlendVT = VT;
10958   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10959     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10960                                NumElems);
10961     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
10962     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
10963   }
10964
10965   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
10966                             DAG.getConstant(MaskValue, MVT::i32));
10967   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10968 }
10969
10970 /// In vector type \p VT, return true if the element at index \p InputIdx
10971 /// falls on a different 128-bit lane than \p OutputIdx.
10972 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
10973                                      unsigned OutputIdx) {
10974   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
10975   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
10976 }
10977
10978 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
10979 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
10980 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
10981 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
10982 /// zero.
10983 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
10984                          SelectionDAG &DAG) {
10985   MVT VT = V1.getSimpleValueType();
10986   assert(VT.is128BitVector() || VT.is256BitVector());
10987
10988   MVT EltVT = VT.getVectorElementType();
10989   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
10990   unsigned NumElts = VT.getVectorNumElements();
10991
10992   SmallVector<SDValue, 32> PshufbMask;
10993   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
10994     int InputIdx = MaskVals[OutputIdx];
10995     unsigned InputByteIdx;
10996
10997     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
10998       InputByteIdx = 0x80;
10999     else {
11000       // Cross lane is not allowed.
11001       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
11002         return SDValue();
11003       InputByteIdx = InputIdx * EltSizeInBytes;
11004       // Index is an byte offset within the 128-bit lane.
11005       InputByteIdx &= 0xf;
11006     }
11007
11008     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
11009       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
11010       if (InputByteIdx != 0x80)
11011         ++InputByteIdx;
11012     }
11013   }
11014
11015   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
11016   if (ShufVT != VT)
11017     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
11018   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
11019                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
11020 }
11021
11022 // v8i16 shuffles - Prefer shuffles in the following order:
11023 // 1. [all]   pshuflw, pshufhw, optional move
11024 // 2. [ssse3] 1 x pshufb
11025 // 3. [ssse3] 2 x pshufb + 1 x por
11026 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
11027 static SDValue
11028 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
11029                          SelectionDAG &DAG) {
11030   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11031   SDValue V1 = SVOp->getOperand(0);
11032   SDValue V2 = SVOp->getOperand(1);
11033   SDLoc dl(SVOp);
11034   SmallVector<int, 8> MaskVals;
11035
11036   // Determine if more than 1 of the words in each of the low and high quadwords
11037   // of the result come from the same quadword of one of the two inputs.  Undef
11038   // mask values count as coming from any quadword, for better codegen.
11039   //
11040   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
11041   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
11042   unsigned LoQuad[] = { 0, 0, 0, 0 };
11043   unsigned HiQuad[] = { 0, 0, 0, 0 };
11044   // Indices of quads used.
11045   std::bitset<4> InputQuads;
11046   for (unsigned i = 0; i < 8; ++i) {
11047     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
11048     int EltIdx = SVOp->getMaskElt(i);
11049     MaskVals.push_back(EltIdx);
11050     if (EltIdx < 0) {
11051       ++Quad[0];
11052       ++Quad[1];
11053       ++Quad[2];
11054       ++Quad[3];
11055       continue;
11056     }
11057     ++Quad[EltIdx / 4];
11058     InputQuads.set(EltIdx / 4);
11059   }
11060
11061   int BestLoQuad = -1;
11062   unsigned MaxQuad = 1;
11063   for (unsigned i = 0; i < 4; ++i) {
11064     if (LoQuad[i] > MaxQuad) {
11065       BestLoQuad = i;
11066       MaxQuad = LoQuad[i];
11067     }
11068   }
11069
11070   int BestHiQuad = -1;
11071   MaxQuad = 1;
11072   for (unsigned i = 0; i < 4; ++i) {
11073     if (HiQuad[i] > MaxQuad) {
11074       BestHiQuad = i;
11075       MaxQuad = HiQuad[i];
11076     }
11077   }
11078
11079   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
11080   // of the two input vectors, shuffle them into one input vector so only a
11081   // single pshufb instruction is necessary. If there are more than 2 input
11082   // quads, disable the next transformation since it does not help SSSE3.
11083   bool V1Used = InputQuads[0] || InputQuads[1];
11084   bool V2Used = InputQuads[2] || InputQuads[3];
11085   if (Subtarget->hasSSSE3()) {
11086     if (InputQuads.count() == 2 && V1Used && V2Used) {
11087       BestLoQuad = InputQuads[0] ? 0 : 1;
11088       BestHiQuad = InputQuads[2] ? 2 : 3;
11089     }
11090     if (InputQuads.count() > 2) {
11091       BestLoQuad = -1;
11092       BestHiQuad = -1;
11093     }
11094   }
11095
11096   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
11097   // the shuffle mask.  If a quad is scored as -1, that means that it contains
11098   // words from all 4 input quadwords.
11099   SDValue NewV;
11100   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
11101     int MaskV[] = {
11102       BestLoQuad < 0 ? 0 : BestLoQuad,
11103       BestHiQuad < 0 ? 1 : BestHiQuad
11104     };
11105     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
11106                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
11107                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
11108     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
11109
11110     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
11111     // source words for the shuffle, to aid later transformations.
11112     bool AllWordsInNewV = true;
11113     bool InOrder[2] = { true, true };
11114     for (unsigned i = 0; i != 8; ++i) {
11115       int idx = MaskVals[i];
11116       if (idx != (int)i)
11117         InOrder[i/4] = false;
11118       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
11119         continue;
11120       AllWordsInNewV = false;
11121       break;
11122     }
11123
11124     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
11125     if (AllWordsInNewV) {
11126       for (int i = 0; i != 8; ++i) {
11127         int idx = MaskVals[i];
11128         if (idx < 0)
11129           continue;
11130         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
11131         if ((idx != i) && idx < 4)
11132           pshufhw = false;
11133         if ((idx != i) && idx > 3)
11134           pshuflw = false;
11135       }
11136       V1 = NewV;
11137       V2Used = false;
11138       BestLoQuad = 0;
11139       BestHiQuad = 1;
11140     }
11141
11142     // If we've eliminated the use of V2, and the new mask is a pshuflw or
11143     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
11144     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
11145       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
11146       unsigned TargetMask = 0;
11147       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
11148                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
11149       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11150       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
11151                              getShufflePSHUFLWImmediate(SVOp);
11152       V1 = NewV.getOperand(0);
11153       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
11154     }
11155   }
11156
11157   // Promote splats to a larger type which usually leads to more efficient code.
11158   // FIXME: Is this true if pshufb is available?
11159   if (SVOp->isSplat())
11160     return PromoteSplat(SVOp, DAG);
11161
11162   // If we have SSSE3, and all words of the result are from 1 input vector,
11163   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
11164   // is present, fall back to case 4.
11165   if (Subtarget->hasSSSE3()) {
11166     SmallVector<SDValue,16> pshufbMask;
11167
11168     // If we have elements from both input vectors, set the high bit of the
11169     // shuffle mask element to zero out elements that come from V2 in the V1
11170     // mask, and elements that come from V1 in the V2 mask, so that the two
11171     // results can be OR'd together.
11172     bool TwoInputs = V1Used && V2Used;
11173     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
11174     if (!TwoInputs)
11175       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11176
11177     // Calculate the shuffle mask for the second input, shuffle it, and
11178     // OR it with the first shuffled input.
11179     CommuteVectorShuffleMask(MaskVals, 8);
11180     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
11181     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11182     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11183   }
11184
11185   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
11186   // and update MaskVals with new element order.
11187   std::bitset<8> InOrder;
11188   if (BestLoQuad >= 0) {
11189     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
11190     for (int i = 0; i != 4; ++i) {
11191       int idx = MaskVals[i];
11192       if (idx < 0) {
11193         InOrder.set(i);
11194       } else if ((idx / 4) == BestLoQuad) {
11195         MaskV[i] = idx & 3;
11196         InOrder.set(i);
11197       }
11198     }
11199     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11200                                 &MaskV[0]);
11201
11202     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11203       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11204       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
11205                                   NewV.getOperand(0),
11206                                   getShufflePSHUFLWImmediate(SVOp), DAG);
11207     }
11208   }
11209
11210   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
11211   // and update MaskVals with the new element order.
11212   if (BestHiQuad >= 0) {
11213     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
11214     for (unsigned i = 4; i != 8; ++i) {
11215       int idx = MaskVals[i];
11216       if (idx < 0) {
11217         InOrder.set(i);
11218       } else if ((idx / 4) == BestHiQuad) {
11219         MaskV[i] = (idx & 3) + 4;
11220         InOrder.set(i);
11221       }
11222     }
11223     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
11224                                 &MaskV[0]);
11225
11226     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
11227       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
11228       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
11229                                   NewV.getOperand(0),
11230                                   getShufflePSHUFHWImmediate(SVOp), DAG);
11231     }
11232   }
11233
11234   // In case BestHi & BestLo were both -1, which means each quadword has a word
11235   // from each of the four input quadwords, calculate the InOrder bitvector now
11236   // before falling through to the insert/extract cleanup.
11237   if (BestLoQuad == -1 && BestHiQuad == -1) {
11238     NewV = V1;
11239     for (int i = 0; i != 8; ++i)
11240       if (MaskVals[i] < 0 || MaskVals[i] == i)
11241         InOrder.set(i);
11242   }
11243
11244   // The other elements are put in the right place using pextrw and pinsrw.
11245   for (unsigned i = 0; i != 8; ++i) {
11246     if (InOrder[i])
11247       continue;
11248     int EltIdx = MaskVals[i];
11249     if (EltIdx < 0)
11250       continue;
11251     SDValue ExtOp = (EltIdx < 8) ?
11252       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
11253                   DAG.getIntPtrConstant(EltIdx)) :
11254       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
11255                   DAG.getIntPtrConstant(EltIdx - 8));
11256     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
11257                        DAG.getIntPtrConstant(i));
11258   }
11259   return NewV;
11260 }
11261
11262 /// \brief v16i16 shuffles
11263 ///
11264 /// FIXME: We only support generation of a single pshufb currently.  We can
11265 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
11266 /// well (e.g 2 x pshufb + 1 x por).
11267 static SDValue
11268 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
11269   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11270   SDValue V1 = SVOp->getOperand(0);
11271   SDValue V2 = SVOp->getOperand(1);
11272   SDLoc dl(SVOp);
11273
11274   if (V2.getOpcode() != ISD::UNDEF)
11275     return SDValue();
11276
11277   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11278   return getPSHUFB(MaskVals, V1, dl, DAG);
11279 }
11280
11281 // v16i8 shuffles - Prefer shuffles in the following order:
11282 // 1. [ssse3] 1 x pshufb
11283 // 2. [ssse3] 2 x pshufb + 1 x por
11284 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
11285 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
11286                                         const X86Subtarget* Subtarget,
11287                                         SelectionDAG &DAG) {
11288   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11289   SDValue V1 = SVOp->getOperand(0);
11290   SDValue V2 = SVOp->getOperand(1);
11291   SDLoc dl(SVOp);
11292   ArrayRef<int> MaskVals = SVOp->getMask();
11293
11294   // Promote splats to a larger type which usually leads to more efficient code.
11295   // FIXME: Is this true if pshufb is available?
11296   if (SVOp->isSplat())
11297     return PromoteSplat(SVOp, DAG);
11298
11299   // If we have SSSE3, case 1 is generated when all result bytes come from
11300   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
11301   // present, fall back to case 3.
11302
11303   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
11304   if (Subtarget->hasSSSE3()) {
11305     SmallVector<SDValue,16> pshufbMask;
11306
11307     // If all result elements are from one input vector, then only translate
11308     // undef mask values to 0x80 (zero out result) in the pshufb mask.
11309     //
11310     // Otherwise, we have elements from both input vectors, and must zero out
11311     // elements that come from V2 in the first mask, and V1 in the second mask
11312     // so that we can OR them together.
11313     for (unsigned i = 0; i != 16; ++i) {
11314       int EltIdx = MaskVals[i];
11315       if (EltIdx < 0 || EltIdx >= 16)
11316         EltIdx = 0x80;
11317       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11318     }
11319     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
11320                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11321                                  MVT::v16i8, pshufbMask));
11322
11323     // As PSHUFB will zero elements with negative indices, it's safe to ignore
11324     // the 2nd operand if it's undefined or zero.
11325     if (V2.getOpcode() == ISD::UNDEF ||
11326         ISD::isBuildVectorAllZeros(V2.getNode()))
11327       return V1;
11328
11329     // Calculate the shuffle mask for the second input, shuffle it, and
11330     // OR it with the first shuffled input.
11331     pshufbMask.clear();
11332     for (unsigned i = 0; i != 16; ++i) {
11333       int EltIdx = MaskVals[i];
11334       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
11335       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
11336     }
11337     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
11338                      DAG.getNode(ISD::BUILD_VECTOR, dl,
11339                                  MVT::v16i8, pshufbMask));
11340     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
11341   }
11342
11343   // No SSSE3 - Calculate in place words and then fix all out of place words
11344   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
11345   // the 16 different words that comprise the two doublequadword input vectors.
11346   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
11347   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
11348   SDValue NewV = V1;
11349   for (int i = 0; i != 8; ++i) {
11350     int Elt0 = MaskVals[i*2];
11351     int Elt1 = MaskVals[i*2+1];
11352
11353     // This word of the result is all undef, skip it.
11354     if (Elt0 < 0 && Elt1 < 0)
11355       continue;
11356
11357     // This word of the result is already in the correct place, skip it.
11358     if ((Elt0 == i*2) && (Elt1 == i*2+1))
11359       continue;
11360
11361     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
11362     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
11363     SDValue InsElt;
11364
11365     // If Elt0 and Elt1 are defined, are consecutive, and can be load
11366     // using a single extract together, load it and store it.
11367     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
11368       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11369                            DAG.getIntPtrConstant(Elt1 / 2));
11370       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11371                         DAG.getIntPtrConstant(i));
11372       continue;
11373     }
11374
11375     // If Elt1 is defined, extract it from the appropriate source.  If the
11376     // source byte is not also odd, shift the extracted word left 8 bits
11377     // otherwise clear the bottom 8 bits if we need to do an or.
11378     if (Elt1 >= 0) {
11379       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
11380                            DAG.getIntPtrConstant(Elt1 / 2));
11381       if ((Elt1 & 1) == 0)
11382         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
11383                              DAG.getConstant(8,
11384                                   TLI.getShiftAmountTy(InsElt.getValueType())));
11385       else if (Elt0 >= 0)
11386         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
11387                              DAG.getConstant(0xFF00, MVT::i16));
11388     }
11389     // If Elt0 is defined, extract it from the appropriate source.  If the
11390     // source byte is not also even, shift the extracted word right 8 bits. If
11391     // Elt1 was also defined, OR the extracted values together before
11392     // inserting them in the result.
11393     if (Elt0 >= 0) {
11394       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
11395                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
11396       if ((Elt0 & 1) != 0)
11397         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
11398                               DAG.getConstant(8,
11399                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
11400       else if (Elt1 >= 0)
11401         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
11402                              DAG.getConstant(0x00FF, MVT::i16));
11403       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
11404                          : InsElt0;
11405     }
11406     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
11407                        DAG.getIntPtrConstant(i));
11408   }
11409   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
11410 }
11411
11412 // v32i8 shuffles - Translate to VPSHUFB if possible.
11413 static
11414 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
11415                                  const X86Subtarget *Subtarget,
11416                                  SelectionDAG &DAG) {
11417   MVT VT = SVOp->getSimpleValueType(0);
11418   SDValue V1 = SVOp->getOperand(0);
11419   SDValue V2 = SVOp->getOperand(1);
11420   SDLoc dl(SVOp);
11421   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
11422
11423   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11424   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
11425   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
11426
11427   // VPSHUFB may be generated if
11428   // (1) one of input vector is undefined or zeroinitializer.
11429   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
11430   // And (2) the mask indexes don't cross the 128-bit lane.
11431   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
11432       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
11433     return SDValue();
11434
11435   if (V1IsAllZero && !V2IsAllZero) {
11436     CommuteVectorShuffleMask(MaskVals, 32);
11437     V1 = V2;
11438   }
11439   return getPSHUFB(MaskVals, V1, dl, DAG);
11440 }
11441
11442 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
11443 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
11444 /// done when every pair / quad of shuffle mask elements point to elements in
11445 /// the right sequence. e.g.
11446 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
11447 static
11448 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
11449                                  SelectionDAG &DAG) {
11450   MVT VT = SVOp->getSimpleValueType(0);
11451   SDLoc dl(SVOp);
11452   unsigned NumElems = VT.getVectorNumElements();
11453   MVT NewVT;
11454   unsigned Scale;
11455   switch (VT.SimpleTy) {
11456   default: llvm_unreachable("Unexpected!");
11457   case MVT::v2i64:
11458   case MVT::v2f64:
11459            return SDValue(SVOp, 0);
11460   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
11461   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
11462   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
11463   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
11464   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
11465   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
11466   }
11467
11468   SmallVector<int, 8> MaskVec;
11469   for (unsigned i = 0; i != NumElems; i += Scale) {
11470     int StartIdx = -1;
11471     for (unsigned j = 0; j != Scale; ++j) {
11472       int EltIdx = SVOp->getMaskElt(i+j);
11473       if (EltIdx < 0)
11474         continue;
11475       if (StartIdx < 0)
11476         StartIdx = (EltIdx / Scale);
11477       if (EltIdx != (int)(StartIdx*Scale + j))
11478         return SDValue();
11479     }
11480     MaskVec.push_back(StartIdx);
11481   }
11482
11483   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
11484   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
11485   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
11486 }
11487
11488 /// getVZextMovL - Return a zero-extending vector move low node.
11489 ///
11490 static SDValue getVZextMovL(MVT VT, MVT OpVT,
11491                             SDValue SrcOp, SelectionDAG &DAG,
11492                             const X86Subtarget *Subtarget, SDLoc dl) {
11493   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
11494     LoadSDNode *LD = nullptr;
11495     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
11496       LD = dyn_cast<LoadSDNode>(SrcOp);
11497     if (!LD) {
11498       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
11499       // instead.
11500       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
11501       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
11502           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11503           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
11504           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
11505         // PR2108
11506         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
11507         return DAG.getNode(ISD::BITCAST, dl, VT,
11508                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11509                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11510                                                    OpVT,
11511                                                    SrcOp.getOperand(0)
11512                                                           .getOperand(0))));
11513       }
11514     }
11515   }
11516
11517   return DAG.getNode(ISD::BITCAST, dl, VT,
11518                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
11519                                  DAG.getNode(ISD::BITCAST, dl,
11520                                              OpVT, SrcOp)));
11521 }
11522
11523 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
11524 /// which could not be matched by any known target speficic shuffle
11525 static SDValue
11526 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11527
11528   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
11529   if (NewOp.getNode())
11530     return NewOp;
11531
11532   MVT VT = SVOp->getSimpleValueType(0);
11533
11534   unsigned NumElems = VT.getVectorNumElements();
11535   unsigned NumLaneElems = NumElems / 2;
11536
11537   SDLoc dl(SVOp);
11538   MVT EltVT = VT.getVectorElementType();
11539   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
11540   SDValue Output[2];
11541
11542   SmallVector<int, 16> Mask;
11543   for (unsigned l = 0; l < 2; ++l) {
11544     // Build a shuffle mask for the output, discovering on the fly which
11545     // input vectors to use as shuffle operands (recorded in InputUsed).
11546     // If building a suitable shuffle vector proves too hard, then bail
11547     // out with UseBuildVector set.
11548     bool UseBuildVector = false;
11549     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
11550     unsigned LaneStart = l * NumLaneElems;
11551     for (unsigned i = 0; i != NumLaneElems; ++i) {
11552       // The mask element.  This indexes into the input.
11553       int Idx = SVOp->getMaskElt(i+LaneStart);
11554       if (Idx < 0) {
11555         // the mask element does not index into any input vector.
11556         Mask.push_back(-1);
11557         continue;
11558       }
11559
11560       // The input vector this mask element indexes into.
11561       int Input = Idx / NumLaneElems;
11562
11563       // Turn the index into an offset from the start of the input vector.
11564       Idx -= Input * NumLaneElems;
11565
11566       // Find or create a shuffle vector operand to hold this input.
11567       unsigned OpNo;
11568       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
11569         if (InputUsed[OpNo] == Input)
11570           // This input vector is already an operand.
11571           break;
11572         if (InputUsed[OpNo] < 0) {
11573           // Create a new operand for this input vector.
11574           InputUsed[OpNo] = Input;
11575           break;
11576         }
11577       }
11578
11579       if (OpNo >= array_lengthof(InputUsed)) {
11580         // More than two input vectors used!  Give up on trying to create a
11581         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
11582         UseBuildVector = true;
11583         break;
11584       }
11585
11586       // Add the mask index for the new shuffle vector.
11587       Mask.push_back(Idx + OpNo * NumLaneElems);
11588     }
11589
11590     if (UseBuildVector) {
11591       SmallVector<SDValue, 16> SVOps;
11592       for (unsigned i = 0; i != NumLaneElems; ++i) {
11593         // The mask element.  This indexes into the input.
11594         int Idx = SVOp->getMaskElt(i+LaneStart);
11595         if (Idx < 0) {
11596           SVOps.push_back(DAG.getUNDEF(EltVT));
11597           continue;
11598         }
11599
11600         // The input vector this mask element indexes into.
11601         int Input = Idx / NumElems;
11602
11603         // Turn the index into an offset from the start of the input vector.
11604         Idx -= Input * NumElems;
11605
11606         // Extract the vector element by hand.
11607         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
11608                                     SVOp->getOperand(Input),
11609                                     DAG.getIntPtrConstant(Idx)));
11610       }
11611
11612       // Construct the output using a BUILD_VECTOR.
11613       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
11614     } else if (InputUsed[0] < 0) {
11615       // No input vectors were used! The result is undefined.
11616       Output[l] = DAG.getUNDEF(NVT);
11617     } else {
11618       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
11619                                         (InputUsed[0] % 2) * NumLaneElems,
11620                                         DAG, dl);
11621       // If only one input was used, use an undefined vector for the other.
11622       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
11623         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
11624                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
11625       // At least one input vector was used. Create a new shuffle vector.
11626       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
11627     }
11628
11629     Mask.clear();
11630   }
11631
11632   // Concatenate the result back
11633   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
11634 }
11635
11636 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
11637 /// 4 elements, and match them with several different shuffle types.
11638 static SDValue
11639 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
11640   SDValue V1 = SVOp->getOperand(0);
11641   SDValue V2 = SVOp->getOperand(1);
11642   SDLoc dl(SVOp);
11643   MVT VT = SVOp->getSimpleValueType(0);
11644
11645   assert(VT.is128BitVector() && "Unsupported vector size");
11646
11647   std::pair<int, int> Locs[4];
11648   int Mask1[] = { -1, -1, -1, -1 };
11649   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
11650
11651   unsigned NumHi = 0;
11652   unsigned NumLo = 0;
11653   for (unsigned i = 0; i != 4; ++i) {
11654     int Idx = PermMask[i];
11655     if (Idx < 0) {
11656       Locs[i] = std::make_pair(-1, -1);
11657     } else {
11658       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
11659       if (Idx < 4) {
11660         Locs[i] = std::make_pair(0, NumLo);
11661         Mask1[NumLo] = Idx;
11662         NumLo++;
11663       } else {
11664         Locs[i] = std::make_pair(1, NumHi);
11665         if (2+NumHi < 4)
11666           Mask1[2+NumHi] = Idx;
11667         NumHi++;
11668       }
11669     }
11670   }
11671
11672   if (NumLo <= 2 && NumHi <= 2) {
11673     // If no more than two elements come from either vector. This can be
11674     // implemented with two shuffles. First shuffle gather the elements.
11675     // The second shuffle, which takes the first shuffle as both of its
11676     // vector operands, put the elements into the right order.
11677     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11678
11679     int Mask2[] = { -1, -1, -1, -1 };
11680
11681     for (unsigned i = 0; i != 4; ++i)
11682       if (Locs[i].first != -1) {
11683         unsigned Idx = (i < 2) ? 0 : 4;
11684         Idx += Locs[i].first * 2 + Locs[i].second;
11685         Mask2[i] = Idx;
11686       }
11687
11688     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
11689   }
11690
11691   if (NumLo == 3 || NumHi == 3) {
11692     // Otherwise, we must have three elements from one vector, call it X, and
11693     // one element from the other, call it Y.  First, use a shufps to build an
11694     // intermediate vector with the one element from Y and the element from X
11695     // that will be in the same half in the final destination (the indexes don't
11696     // matter). Then, use a shufps to build the final vector, taking the half
11697     // containing the element from Y from the intermediate, and the other half
11698     // from X.
11699     if (NumHi == 3) {
11700       // Normalize it so the 3 elements come from V1.
11701       CommuteVectorShuffleMask(PermMask, 4);
11702       std::swap(V1, V2);
11703     }
11704
11705     // Find the element from V2.
11706     unsigned HiIndex;
11707     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
11708       int Val = PermMask[HiIndex];
11709       if (Val < 0)
11710         continue;
11711       if (Val >= 4)
11712         break;
11713     }
11714
11715     Mask1[0] = PermMask[HiIndex];
11716     Mask1[1] = -1;
11717     Mask1[2] = PermMask[HiIndex^1];
11718     Mask1[3] = -1;
11719     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11720
11721     if (HiIndex >= 2) {
11722       Mask1[0] = PermMask[0];
11723       Mask1[1] = PermMask[1];
11724       Mask1[2] = HiIndex & 1 ? 6 : 4;
11725       Mask1[3] = HiIndex & 1 ? 4 : 6;
11726       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
11727     }
11728
11729     Mask1[0] = HiIndex & 1 ? 2 : 0;
11730     Mask1[1] = HiIndex & 1 ? 0 : 2;
11731     Mask1[2] = PermMask[2];
11732     Mask1[3] = PermMask[3];
11733     if (Mask1[2] >= 0)
11734       Mask1[2] += 4;
11735     if (Mask1[3] >= 0)
11736       Mask1[3] += 4;
11737     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
11738   }
11739
11740   // Break it into (shuffle shuffle_hi, shuffle_lo).
11741   int LoMask[] = { -1, -1, -1, -1 };
11742   int HiMask[] = { -1, -1, -1, -1 };
11743
11744   int *MaskPtr = LoMask;
11745   unsigned MaskIdx = 0;
11746   unsigned LoIdx = 0;
11747   unsigned HiIdx = 2;
11748   for (unsigned i = 0; i != 4; ++i) {
11749     if (i == 2) {
11750       MaskPtr = HiMask;
11751       MaskIdx = 1;
11752       LoIdx = 0;
11753       HiIdx = 2;
11754     }
11755     int Idx = PermMask[i];
11756     if (Idx < 0) {
11757       Locs[i] = std::make_pair(-1, -1);
11758     } else if (Idx < 4) {
11759       Locs[i] = std::make_pair(MaskIdx, LoIdx);
11760       MaskPtr[LoIdx] = Idx;
11761       LoIdx++;
11762     } else {
11763       Locs[i] = std::make_pair(MaskIdx, HiIdx);
11764       MaskPtr[HiIdx] = Idx;
11765       HiIdx++;
11766     }
11767   }
11768
11769   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
11770   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
11771   int MaskOps[] = { -1, -1, -1, -1 };
11772   for (unsigned i = 0; i != 4; ++i)
11773     if (Locs[i].first != -1)
11774       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
11775   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
11776 }
11777
11778 static bool MayFoldVectorLoad(SDValue V) {
11779   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
11780     V = V.getOperand(0);
11781
11782   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
11783     V = V.getOperand(0);
11784   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
11785       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
11786     // BUILD_VECTOR (load), undef
11787     V = V.getOperand(0);
11788
11789   return MayFoldLoad(V);
11790 }
11791
11792 static
11793 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
11794   MVT VT = Op.getSimpleValueType();
11795
11796   // Canonizalize to v2f64.
11797   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
11798   return DAG.getNode(ISD::BITCAST, dl, VT,
11799                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
11800                                           V1, DAG));
11801 }
11802
11803 static
11804 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
11805                         bool HasSSE2) {
11806   SDValue V1 = Op.getOperand(0);
11807   SDValue V2 = Op.getOperand(1);
11808   MVT VT = Op.getSimpleValueType();
11809
11810   assert(VT != MVT::v2i64 && "unsupported shuffle type");
11811
11812   if (HasSSE2 && VT == MVT::v2f64)
11813     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
11814
11815   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
11816   return DAG.getNode(ISD::BITCAST, dl, VT,
11817                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
11818                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
11819                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
11820 }
11821
11822 static
11823 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
11824   SDValue V1 = Op.getOperand(0);
11825   SDValue V2 = Op.getOperand(1);
11826   MVT VT = Op.getSimpleValueType();
11827
11828   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
11829          "unsupported shuffle type");
11830
11831   if (V2.getOpcode() == ISD::UNDEF)
11832     V2 = V1;
11833
11834   // v4i32 or v4f32
11835   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
11836 }
11837
11838 static
11839 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
11840   SDValue V1 = Op.getOperand(0);
11841   SDValue V2 = Op.getOperand(1);
11842   MVT VT = Op.getSimpleValueType();
11843   unsigned NumElems = VT.getVectorNumElements();
11844
11845   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
11846   // operand of these instructions is only memory, so check if there's a
11847   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
11848   // same masks.
11849   bool CanFoldLoad = false;
11850
11851   // Trivial case, when V2 comes from a load.
11852   if (MayFoldVectorLoad(V2))
11853     CanFoldLoad = true;
11854
11855   // When V1 is a load, it can be folded later into a store in isel, example:
11856   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
11857   //    turns into:
11858   //  (MOVLPSmr addr:$src1, VR128:$src2)
11859   // So, recognize this potential and also use MOVLPS or MOVLPD
11860   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
11861     CanFoldLoad = true;
11862
11863   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11864   if (CanFoldLoad) {
11865     if (HasSSE2 && NumElems == 2)
11866       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
11867
11868     if (NumElems == 4)
11869       // If we don't care about the second element, proceed to use movss.
11870       if (SVOp->getMaskElt(1) != -1)
11871         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
11872   }
11873
11874   // movl and movlp will both match v2i64, but v2i64 is never matched by
11875   // movl earlier because we make it strict to avoid messing with the movlp load
11876   // folding logic (see the code above getMOVLP call). Match it here then,
11877   // this is horrible, but will stay like this until we move all shuffle
11878   // matching to x86 specific nodes. Note that for the 1st condition all
11879   // types are matched with movsd.
11880   if (HasSSE2) {
11881     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
11882     // as to remove this logic from here, as much as possible
11883     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
11884       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11885     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11886   }
11887
11888   assert(VT != MVT::v4i32 && "unsupported shuffle type");
11889
11890   // Invert the operand order and use SHUFPS to match it.
11891   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
11892                               getShuffleSHUFImmediate(SVOp), DAG);
11893 }
11894
11895 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
11896                                          SelectionDAG &DAG) {
11897   SDLoc dl(Load);
11898   MVT VT = Load->getSimpleValueType(0);
11899   MVT EVT = VT.getVectorElementType();
11900   SDValue Addr = Load->getOperand(1);
11901   SDValue NewAddr = DAG.getNode(
11902       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
11903       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
11904
11905   SDValue NewLoad =
11906       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
11907                   DAG.getMachineFunction().getMachineMemOperand(
11908                       Load->getMemOperand(), 0, EVT.getStoreSize()));
11909   return NewLoad;
11910 }
11911
11912 // It is only safe to call this function if isINSERTPSMask is true for
11913 // this shufflevector mask.
11914 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
11915                            SelectionDAG &DAG) {
11916   // Generate an insertps instruction when inserting an f32 from memory onto a
11917   // v4f32 or when copying a member from one v4f32 to another.
11918   // We also use it for transferring i32 from one register to another,
11919   // since it simply copies the same bits.
11920   // If we're transferring an i32 from memory to a specific element in a
11921   // register, we output a generic DAG that will match the PINSRD
11922   // instruction.
11923   MVT VT = SVOp->getSimpleValueType(0);
11924   MVT EVT = VT.getVectorElementType();
11925   SDValue V1 = SVOp->getOperand(0);
11926   SDValue V2 = SVOp->getOperand(1);
11927   auto Mask = SVOp->getMask();
11928   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
11929          "unsupported vector type for insertps/pinsrd");
11930
11931   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
11932   auto FromV2Predicate = [](const int &i) { return i >= 4; };
11933   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
11934
11935   SDValue From;
11936   SDValue To;
11937   unsigned DestIndex;
11938   if (FromV1 == 1) {
11939     From = V1;
11940     To = V2;
11941     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
11942                 Mask.begin();
11943
11944     // If we have 1 element from each vector, we have to check if we're
11945     // changing V1's element's place. If so, we're done. Otherwise, we
11946     // should assume we're changing V2's element's place and behave
11947     // accordingly.
11948     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
11949     assert(DestIndex <= INT32_MAX && "truncated destination index");
11950     if (FromV1 == FromV2 &&
11951         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
11952       From = V2;
11953       To = V1;
11954       DestIndex =
11955           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11956     }
11957   } else {
11958     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
11959            "More than one element from V1 and from V2, or no elements from one "
11960            "of the vectors. This case should not have returned true from "
11961            "isINSERTPSMask");
11962     From = V2;
11963     To = V1;
11964     DestIndex =
11965         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
11966   }
11967
11968   // Get an index into the source vector in the range [0,4) (the mask is
11969   // in the range [0,8) because it can address V1 and V2)
11970   unsigned SrcIndex = Mask[DestIndex] % 4;
11971   if (MayFoldLoad(From)) {
11972     // Trivial case, when From comes from a load and is only used by the
11973     // shuffle. Make it use insertps from the vector that we need from that
11974     // load.
11975     SDValue NewLoad =
11976         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
11977     if (!NewLoad.getNode())
11978       return SDValue();
11979
11980     if (EVT == MVT::f32) {
11981       // Create this as a scalar to vector to match the instruction pattern.
11982       SDValue LoadScalarToVector =
11983           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
11984       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
11985       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
11986                          InsertpsMask);
11987     } else { // EVT == MVT::i32
11988       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
11989       // instruction, to match the PINSRD instruction, which loads an i32 to a
11990       // certain vector element.
11991       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
11992                          DAG.getConstant(DestIndex, MVT::i32));
11993     }
11994   }
11995
11996   // Vector-element-to-vector
11997   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
11998   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
11999 }
12000
12001 // Reduce a vector shuffle to zext.
12002 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
12003                                     SelectionDAG &DAG) {
12004   // PMOVZX is only available from SSE41.
12005   if (!Subtarget->hasSSE41())
12006     return SDValue();
12007
12008   MVT VT = Op.getSimpleValueType();
12009
12010   // Only AVX2 support 256-bit vector integer extending.
12011   if (!Subtarget->hasInt256() && VT.is256BitVector())
12012     return SDValue();
12013
12014   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12015   SDLoc DL(Op);
12016   SDValue V1 = Op.getOperand(0);
12017   SDValue V2 = Op.getOperand(1);
12018   unsigned NumElems = VT.getVectorNumElements();
12019
12020   // Extending is an unary operation and the element type of the source vector
12021   // won't be equal to or larger than i64.
12022   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
12023       VT.getVectorElementType() == MVT::i64)
12024     return SDValue();
12025
12026   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
12027   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
12028   while ((1U << Shift) < NumElems) {
12029     if (SVOp->getMaskElt(1U << Shift) == 1)
12030       break;
12031     Shift += 1;
12032     // The maximal ratio is 8, i.e. from i8 to i64.
12033     if (Shift > 3)
12034       return SDValue();
12035   }
12036
12037   // Check the shuffle mask.
12038   unsigned Mask = (1U << Shift) - 1;
12039   for (unsigned i = 0; i != NumElems; ++i) {
12040     int EltIdx = SVOp->getMaskElt(i);
12041     if ((i & Mask) != 0 && EltIdx != -1)
12042       return SDValue();
12043     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
12044       return SDValue();
12045   }
12046
12047   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
12048   MVT NeVT = MVT::getIntegerVT(NBits);
12049   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
12050
12051   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
12052     return SDValue();
12053
12054   return DAG.getNode(ISD::BITCAST, DL, VT,
12055                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
12056 }
12057
12058 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
12059                                       SelectionDAG &DAG) {
12060   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12061   MVT VT = Op.getSimpleValueType();
12062   SDLoc dl(Op);
12063   SDValue V1 = Op.getOperand(0);
12064   SDValue V2 = Op.getOperand(1);
12065
12066   if (isZeroShuffle(SVOp))
12067     return getZeroVector(VT, Subtarget, DAG, dl);
12068
12069   // Handle splat operations
12070   if (SVOp->isSplat()) {
12071     // Use vbroadcast whenever the splat comes from a foldable load
12072     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
12073     if (Broadcast.getNode())
12074       return Broadcast;
12075   }
12076
12077   // Check integer expanding shuffles.
12078   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
12079   if (NewOp.getNode())
12080     return NewOp;
12081
12082   // If the shuffle can be profitably rewritten as a narrower shuffle, then
12083   // do it!
12084   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
12085       VT == MVT::v32i8) {
12086     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12087     if (NewOp.getNode())
12088       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
12089   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
12090     // FIXME: Figure out a cleaner way to do this.
12091     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
12092       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12093       if (NewOp.getNode()) {
12094         MVT NewVT = NewOp.getSimpleValueType();
12095         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
12096                                NewVT, true, false))
12097           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
12098                               dl);
12099       }
12100     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
12101       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
12102       if (NewOp.getNode()) {
12103         MVT NewVT = NewOp.getSimpleValueType();
12104         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
12105           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
12106                               dl);
12107       }
12108     }
12109   }
12110   return SDValue();
12111 }
12112
12113 SDValue
12114 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
12115   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12116   SDValue V1 = Op.getOperand(0);
12117   SDValue V2 = Op.getOperand(1);
12118   MVT VT = Op.getSimpleValueType();
12119   SDLoc dl(Op);
12120   unsigned NumElems = VT.getVectorNumElements();
12121   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
12122   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
12123   bool V1IsSplat = false;
12124   bool V2IsSplat = false;
12125   bool HasSSE2 = Subtarget->hasSSE2();
12126   bool HasFp256    = Subtarget->hasFp256();
12127   bool HasInt256   = Subtarget->hasInt256();
12128   MachineFunction &MF = DAG.getMachineFunction();
12129   bool OptForSize = MF.getFunction()->getAttributes().
12130     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
12131
12132   // Check if we should use the experimental vector shuffle lowering. If so,
12133   // delegate completely to that code path.
12134   if (ExperimentalVectorShuffleLowering)
12135     return lowerVectorShuffle(Op, Subtarget, DAG);
12136
12137   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
12138
12139   if (V1IsUndef && V2IsUndef)
12140     return DAG.getUNDEF(VT);
12141
12142   // When we create a shuffle node we put the UNDEF node to second operand,
12143   // but in some cases the first operand may be transformed to UNDEF.
12144   // In this case we should just commute the node.
12145   if (V1IsUndef)
12146     return DAG.getCommutedVectorShuffle(*SVOp);
12147
12148   // Vector shuffle lowering takes 3 steps:
12149   //
12150   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
12151   //    narrowing and commutation of operands should be handled.
12152   // 2) Matching of shuffles with known shuffle masks to x86 target specific
12153   //    shuffle nodes.
12154   // 3) Rewriting of unmatched masks into new generic shuffle operations,
12155   //    so the shuffle can be broken into other shuffles and the legalizer can
12156   //    try the lowering again.
12157   //
12158   // The general idea is that no vector_shuffle operation should be left to
12159   // be matched during isel, all of them must be converted to a target specific
12160   // node here.
12161
12162   // Normalize the input vectors. Here splats, zeroed vectors, profitable
12163   // narrowing and commutation of operands should be handled. The actual code
12164   // doesn't include all of those, work in progress...
12165   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
12166   if (NewOp.getNode())
12167     return NewOp;
12168
12169   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
12170
12171   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
12172   // unpckh_undef). Only use pshufd if speed is more important than size.
12173   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12174     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12175   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12176     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12177
12178   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
12179       V2IsUndef && MayFoldVectorLoad(V1))
12180     return getMOVDDup(Op, dl, V1, DAG);
12181
12182   if (isMOVHLPS_v_undef_Mask(M, VT))
12183     return getMOVHighToLow(Op, dl, DAG);
12184
12185   // Use to match splats
12186   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
12187       (VT == MVT::v2f64 || VT == MVT::v2i64))
12188     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12189
12190   if (isPSHUFDMask(M, VT)) {
12191     // The actual implementation will match the mask in the if above and then
12192     // during isel it can match several different instructions, not only pshufd
12193     // as its name says, sad but true, emulate the behavior for now...
12194     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
12195       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
12196
12197     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
12198
12199     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
12200       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
12201
12202     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
12203       return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
12204                                   DAG);
12205
12206     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
12207                                 TargetMask, DAG);
12208   }
12209
12210   if (isPALIGNRMask(M, VT, Subtarget))
12211     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
12212                                 getShufflePALIGNRImmediate(SVOp),
12213                                 DAG);
12214
12215   if (isVALIGNMask(M, VT, Subtarget))
12216     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
12217                                 getShuffleVALIGNImmediate(SVOp),
12218                                 DAG);
12219
12220   // Check if this can be converted into a logical shift.
12221   bool isLeft = false;
12222   unsigned ShAmt = 0;
12223   SDValue ShVal;
12224   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
12225   if (isShift && ShVal.hasOneUse()) {
12226     // If the shifted value has multiple uses, it may be cheaper to use
12227     // v_set0 + movlhps or movhlps, etc.
12228     MVT EltVT = VT.getVectorElementType();
12229     ShAmt *= EltVT.getSizeInBits();
12230     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12231   }
12232
12233   if (isMOVLMask(M, VT)) {
12234     if (ISD::isBuildVectorAllZeros(V1.getNode()))
12235       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
12236     if (!isMOVLPMask(M, VT)) {
12237       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
12238         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
12239
12240       if (VT == MVT::v4i32 || VT == MVT::v4f32)
12241         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
12242     }
12243   }
12244
12245   // FIXME: fold these into legal mask.
12246   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
12247     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
12248
12249   if (isMOVHLPSMask(M, VT))
12250     return getMOVHighToLow(Op, dl, DAG);
12251
12252   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
12253     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
12254
12255   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
12256     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
12257
12258   if (isMOVLPMask(M, VT))
12259     return getMOVLP(Op, dl, DAG, HasSSE2);
12260
12261   if (ShouldXformToMOVHLPS(M, VT) ||
12262       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
12263     return DAG.getCommutedVectorShuffle(*SVOp);
12264
12265   if (isShift) {
12266     // No better options. Use a vshldq / vsrldq.
12267     MVT EltVT = VT.getVectorElementType();
12268     ShAmt *= EltVT.getSizeInBits();
12269     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
12270   }
12271
12272   bool Commuted = false;
12273   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
12274   // 1,1,1,1 -> v8i16 though.
12275   BitVector UndefElements;
12276   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
12277     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12278       V1IsSplat = true;
12279   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
12280     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
12281       V2IsSplat = true;
12282
12283   // Canonicalize the splat or undef, if present, to be on the RHS.
12284   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
12285     CommuteVectorShuffleMask(M, NumElems);
12286     std::swap(V1, V2);
12287     std::swap(V1IsSplat, V2IsSplat);
12288     Commuted = true;
12289   }
12290
12291   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
12292     // Shuffling low element of v1 into undef, just return v1.
12293     if (V2IsUndef)
12294       return V1;
12295     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
12296     // the instruction selector will not match, so get a canonical MOVL with
12297     // swapped operands to undo the commute.
12298     return getMOVL(DAG, dl, VT, V2, V1);
12299   }
12300
12301   if (isUNPCKLMask(M, VT, HasInt256))
12302     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12303
12304   if (isUNPCKHMask(M, VT, HasInt256))
12305     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12306
12307   if (V2IsSplat) {
12308     // Normalize mask so all entries that point to V2 points to its first
12309     // element then try to match unpck{h|l} again. If match, return a
12310     // new vector_shuffle with the corrected mask.p
12311     SmallVector<int, 8> NewMask(M.begin(), M.end());
12312     NormalizeMask(NewMask, NumElems);
12313     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
12314       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12315     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
12316       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12317   }
12318
12319   if (Commuted) {
12320     // Commute is back and try unpck* again.
12321     // FIXME: this seems wrong.
12322     CommuteVectorShuffleMask(M, NumElems);
12323     std::swap(V1, V2);
12324     std::swap(V1IsSplat, V2IsSplat);
12325
12326     if (isUNPCKLMask(M, VT, HasInt256))
12327       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
12328
12329     if (isUNPCKHMask(M, VT, HasInt256))
12330       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
12331   }
12332
12333   // Normalize the node to match x86 shuffle ops if needed
12334   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
12335     return DAG.getCommutedVectorShuffle(*SVOp);
12336
12337   // The checks below are all present in isShuffleMaskLegal, but they are
12338   // inlined here right now to enable us to directly emit target specific
12339   // nodes, and remove one by one until they don't return Op anymore.
12340
12341   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
12342       SVOp->getSplatIndex() == 0 && V2IsUndef) {
12343     if (VT == MVT::v2f64 || VT == MVT::v2i64)
12344       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12345   }
12346
12347   if (isPSHUFHWMask(M, VT, HasInt256))
12348     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
12349                                 getShufflePSHUFHWImmediate(SVOp),
12350                                 DAG);
12351
12352   if (isPSHUFLWMask(M, VT, HasInt256))
12353     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
12354                                 getShufflePSHUFLWImmediate(SVOp),
12355                                 DAG);
12356
12357   unsigned MaskValue;
12358   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
12359                   &MaskValue))
12360     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
12361
12362   if (isSHUFPMask(M, VT))
12363     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
12364                                 getShuffleSHUFImmediate(SVOp), DAG);
12365
12366   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
12367     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
12368   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
12369     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
12370
12371   //===--------------------------------------------------------------------===//
12372   // Generate target specific nodes for 128 or 256-bit shuffles only
12373   // supported in the AVX instruction set.
12374   //
12375
12376   // Handle VMOVDDUPY permutations
12377   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
12378     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
12379
12380   // Handle VPERMILPS/D* permutations
12381   if (isVPERMILPMask(M, VT)) {
12382     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
12383       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
12384                                   getShuffleSHUFImmediate(SVOp), DAG);
12385     return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
12386                                 getShuffleSHUFImmediate(SVOp), DAG);
12387   }
12388
12389   unsigned Idx;
12390   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
12391     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
12392                               Idx*(NumElems/2), DAG, dl);
12393
12394   // Handle VPERM2F128/VPERM2I128 permutations
12395   if (isVPERM2X128Mask(M, VT, HasFp256))
12396     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
12397                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
12398
12399   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
12400     return getINSERTPS(SVOp, dl, DAG);
12401
12402   unsigned Imm8;
12403   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
12404     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
12405
12406   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
12407       VT.is512BitVector()) {
12408     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
12409     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
12410     SmallVector<SDValue, 16> permclMask;
12411     for (unsigned i = 0; i != NumElems; ++i) {
12412       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
12413     }
12414
12415     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
12416     if (V2IsUndef)
12417       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
12418       return DAG.getNode(X86ISD::VPERMV, dl, VT,
12419                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
12420     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
12421                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
12422   }
12423
12424   //===--------------------------------------------------------------------===//
12425   // Since no target specific shuffle was selected for this generic one,
12426   // lower it into other known shuffles. FIXME: this isn't true yet, but
12427   // this is the plan.
12428   //
12429
12430   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
12431   if (VT == MVT::v8i16) {
12432     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
12433     if (NewOp.getNode())
12434       return NewOp;
12435   }
12436
12437   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
12438     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
12439     if (NewOp.getNode())
12440       return NewOp;
12441   }
12442
12443   if (VT == MVT::v16i8) {
12444     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
12445     if (NewOp.getNode())
12446       return NewOp;
12447   }
12448
12449   if (VT == MVT::v32i8) {
12450     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
12451     if (NewOp.getNode())
12452       return NewOp;
12453   }
12454
12455   // Handle all 128-bit wide vectors with 4 elements, and match them with
12456   // several different shuffle types.
12457   if (NumElems == 4 && VT.is128BitVector())
12458     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
12459
12460   // Handle general 256-bit shuffles
12461   if (VT.is256BitVector())
12462     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
12463
12464   return SDValue();
12465 }
12466
12467 // This function assumes its argument is a BUILD_VECTOR of constants or
12468 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
12469 // true.
12470 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
12471                                     unsigned &MaskValue) {
12472   MaskValue = 0;
12473   unsigned NumElems = BuildVector->getNumOperands();
12474   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
12475   unsigned NumLanes = (NumElems - 1) / 8 + 1;
12476   unsigned NumElemsInLane = NumElems / NumLanes;
12477
12478   // Blend for v16i16 should be symetric for the both lanes.
12479   for (unsigned i = 0; i < NumElemsInLane; ++i) {
12480     SDValue EltCond = BuildVector->getOperand(i);
12481     SDValue SndLaneEltCond =
12482         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
12483
12484     int Lane1Cond = -1, Lane2Cond = -1;
12485     if (isa<ConstantSDNode>(EltCond))
12486       Lane1Cond = !isZero(EltCond);
12487     if (isa<ConstantSDNode>(SndLaneEltCond))
12488       Lane2Cond = !isZero(SndLaneEltCond);
12489
12490     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
12491       // Lane1Cond != 0, means we want the first argument.
12492       // Lane1Cond == 0, means we want the second argument.
12493       // The encoding of this argument is 0 for the first argument, 1
12494       // for the second. Therefore, invert the condition.
12495       MaskValue |= !Lane1Cond << i;
12496     else if (Lane1Cond < 0)
12497       MaskValue |= !Lane2Cond << i;
12498     else
12499       return false;
12500   }
12501   return true;
12502 }
12503
12504 /// \brief Try to lower a VSELECT instruction to an immediate-controlled blend
12505 /// instruction.
12506 static SDValue lowerVSELECTtoBLENDI(SDValue Op, const X86Subtarget *Subtarget,
12507                                     SelectionDAG &DAG) {
12508   SDValue Cond = Op.getOperand(0);
12509   SDValue LHS = Op.getOperand(1);
12510   SDValue RHS = Op.getOperand(2);
12511   SDLoc dl(Op);
12512   MVT VT = Op.getSimpleValueType();
12513   MVT EltVT = VT.getVectorElementType();
12514   unsigned NumElems = VT.getVectorNumElements();
12515
12516   // There is no blend with immediate in AVX-512.
12517   if (VT.is512BitVector())
12518     return SDValue();
12519
12520   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
12521     return SDValue();
12522   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
12523     return SDValue();
12524
12525   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
12526     return SDValue();
12527
12528   // Check the mask for BLEND and build the value.
12529   unsigned MaskValue = 0;
12530   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
12531     return SDValue();
12532
12533   // Convert i32 vectors to floating point if it is not AVX2.
12534   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
12535   MVT BlendVT = VT;
12536   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
12537     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
12538                                NumElems);
12539     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
12540     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
12541   }
12542
12543   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
12544                             DAG.getConstant(MaskValue, MVT::i32));
12545   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
12546 }
12547
12548 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
12549   // A vselect where all conditions and data are constants can be optimized into
12550   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
12551   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
12552       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
12553       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
12554     return SDValue();
12555
12556   SDValue BlendOp = lowerVSELECTtoBLENDI(Op, Subtarget, DAG);
12557   if (BlendOp.getNode())
12558     return BlendOp;
12559
12560   // Some types for vselect were previously set to Expand, not Legal or
12561   // Custom. Return an empty SDValue so we fall-through to Expand, after
12562   // the Custom lowering phase.
12563   MVT VT = Op.getSimpleValueType();
12564   switch (VT.SimpleTy) {
12565   default:
12566     break;
12567   case MVT::v8i16:
12568   case MVT::v16i16:
12569     if (Subtarget->hasBWI() && Subtarget->hasVLX())
12570       break;
12571     return SDValue();
12572   }
12573
12574   // We couldn't create a "Blend with immediate" node.
12575   // This node should still be legal, but we'll have to emit a blendv*
12576   // instruction.
12577   return Op;
12578 }
12579
12580 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
12581   MVT VT = Op.getSimpleValueType();
12582   SDLoc dl(Op);
12583
12584   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
12585     return SDValue();
12586
12587   if (VT.getSizeInBits() == 8) {
12588     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
12589                                   Op.getOperand(0), Op.getOperand(1));
12590     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12591                                   DAG.getValueType(VT));
12592     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12593   }
12594
12595   if (VT.getSizeInBits() == 16) {
12596     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12597     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
12598     if (Idx == 0)
12599       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12600                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12601                                      DAG.getNode(ISD::BITCAST, dl,
12602                                                  MVT::v4i32,
12603                                                  Op.getOperand(0)),
12604                                      Op.getOperand(1)));
12605     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
12606                                   Op.getOperand(0), Op.getOperand(1));
12607     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12608                                   DAG.getValueType(VT));
12609     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12610   }
12611
12612   if (VT == MVT::f32) {
12613     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
12614     // the result back to FR32 register. It's only worth matching if the
12615     // result has a single use which is a store or a bitcast to i32.  And in
12616     // the case of a store, it's not worth it if the index is a constant 0,
12617     // because a MOVSSmr can be used instead, which is smaller and faster.
12618     if (!Op.hasOneUse())
12619       return SDValue();
12620     SDNode *User = *Op.getNode()->use_begin();
12621     if ((User->getOpcode() != ISD::STORE ||
12622          (isa<ConstantSDNode>(Op.getOperand(1)) &&
12623           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
12624         (User->getOpcode() != ISD::BITCAST ||
12625          User->getValueType(0) != MVT::i32))
12626       return SDValue();
12627     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12628                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
12629                                               Op.getOperand(0)),
12630                                               Op.getOperand(1));
12631     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
12632   }
12633
12634   if (VT == MVT::i32 || VT == MVT::i64) {
12635     // ExtractPS/pextrq works with constant index.
12636     if (isa<ConstantSDNode>(Op.getOperand(1)))
12637       return Op;
12638   }
12639   return SDValue();
12640 }
12641
12642 /// Extract one bit from mask vector, like v16i1 or v8i1.
12643 /// AVX-512 feature.
12644 SDValue
12645 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
12646   SDValue Vec = Op.getOperand(0);
12647   SDLoc dl(Vec);
12648   MVT VecVT = Vec.getSimpleValueType();
12649   SDValue Idx = Op.getOperand(1);
12650   MVT EltVT = Op.getSimpleValueType();
12651
12652   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
12653
12654   // variable index can't be handled in mask registers,
12655   // extend vector to VR512
12656   if (!isa<ConstantSDNode>(Idx)) {
12657     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12658     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
12659     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
12660                               ExtVT.getVectorElementType(), Ext, Idx);
12661     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
12662   }
12663
12664   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12665   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12666   unsigned MaxSift = rc->getSize()*8 - 1;
12667   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
12668                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12669   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
12670                     DAG.getConstant(MaxSift, MVT::i8));
12671   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
12672                        DAG.getIntPtrConstant(0));
12673 }
12674
12675 SDValue
12676 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12677                                            SelectionDAG &DAG) const {
12678   SDLoc dl(Op);
12679   SDValue Vec = Op.getOperand(0);
12680   MVT VecVT = Vec.getSimpleValueType();
12681   SDValue Idx = Op.getOperand(1);
12682
12683   if (Op.getSimpleValueType() == MVT::i1)
12684     return ExtractBitFromMaskVector(Op, DAG);
12685
12686   if (!isa<ConstantSDNode>(Idx)) {
12687     if (VecVT.is512BitVector() ||
12688         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
12689          VecVT.getVectorElementType().getSizeInBits() == 32)) {
12690
12691       MVT MaskEltVT =
12692         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
12693       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
12694                                     MaskEltVT.getSizeInBits());
12695
12696       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
12697       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
12698                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
12699                                 Idx, DAG.getConstant(0, getPointerTy()));
12700       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
12701       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
12702                         Perm, DAG.getConstant(0, getPointerTy()));
12703     }
12704     return SDValue();
12705   }
12706
12707   // If this is a 256-bit vector result, first extract the 128-bit vector and
12708   // then extract the element from the 128-bit vector.
12709   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
12710
12711     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12712     // Get the 128-bit vector.
12713     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
12714     MVT EltVT = VecVT.getVectorElementType();
12715
12716     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
12717
12718     //if (IdxVal >= NumElems/2)
12719     //  IdxVal -= NumElems/2;
12720     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
12721     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
12722                        DAG.getConstant(IdxVal, MVT::i32));
12723   }
12724
12725   assert(VecVT.is128BitVector() && "Unexpected vector length");
12726
12727   if (Subtarget->hasSSE41()) {
12728     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
12729     if (Res.getNode())
12730       return Res;
12731   }
12732
12733   MVT VT = Op.getSimpleValueType();
12734   // TODO: handle v16i8.
12735   if (VT.getSizeInBits() == 16) {
12736     SDValue Vec = Op.getOperand(0);
12737     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12738     if (Idx == 0)
12739       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12740                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12741                                      DAG.getNode(ISD::BITCAST, dl,
12742                                                  MVT::v4i32, Vec),
12743                                      Op.getOperand(1)));
12744     // Transform it so it match pextrw which produces a 32-bit result.
12745     MVT EltVT = MVT::i32;
12746     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
12747                                   Op.getOperand(0), Op.getOperand(1));
12748     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
12749                                   DAG.getValueType(VT));
12750     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12751   }
12752
12753   if (VT.getSizeInBits() == 32) {
12754     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12755     if (Idx == 0)
12756       return Op;
12757
12758     // SHUFPS the element to the lowest double word, then movss.
12759     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
12760     MVT VVT = Op.getOperand(0).getSimpleValueType();
12761     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12762                                        DAG.getUNDEF(VVT), Mask);
12763     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12764                        DAG.getIntPtrConstant(0));
12765   }
12766
12767   if (VT.getSizeInBits() == 64) {
12768     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
12769     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
12770     //        to match extract_elt for f64.
12771     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12772     if (Idx == 0)
12773       return Op;
12774
12775     // UNPCKHPD the element to the lowest double word, then movsd.
12776     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
12777     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
12778     int Mask[2] = { 1, -1 };
12779     MVT VVT = Op.getOperand(0).getSimpleValueType();
12780     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
12781                                        DAG.getUNDEF(VVT), Mask);
12782     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12783                        DAG.getIntPtrConstant(0));
12784   }
12785
12786   return SDValue();
12787 }
12788
12789 /// Insert one bit to mask vector, like v16i1 or v8i1.
12790 /// AVX-512 feature.
12791 SDValue 
12792 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
12793   SDLoc dl(Op);
12794   SDValue Vec = Op.getOperand(0);
12795   SDValue Elt = Op.getOperand(1);
12796   SDValue Idx = Op.getOperand(2);
12797   MVT VecVT = Vec.getSimpleValueType();
12798
12799   if (!isa<ConstantSDNode>(Idx)) {
12800     // Non constant index. Extend source and destination,
12801     // insert element and then truncate the result.
12802     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
12803     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
12804     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
12805       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
12806       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
12807     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
12808   }
12809
12810   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12811   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
12812   if (Vec.getOpcode() == ISD::UNDEF)
12813     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12814                        DAG.getConstant(IdxVal, MVT::i8));
12815   const TargetRegisterClass* rc = getRegClassFor(VecVT);
12816   unsigned MaxSift = rc->getSize()*8 - 1;
12817   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12818                     DAG.getConstant(MaxSift, MVT::i8));
12819   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
12820                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
12821   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
12822 }
12823
12824 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12825                                                   SelectionDAG &DAG) const {
12826   MVT VT = Op.getSimpleValueType();
12827   MVT EltVT = VT.getVectorElementType();
12828
12829   if (EltVT == MVT::i1)
12830     return InsertBitToMaskVector(Op, DAG);
12831
12832   SDLoc dl(Op);
12833   SDValue N0 = Op.getOperand(0);
12834   SDValue N1 = Op.getOperand(1);
12835   SDValue N2 = Op.getOperand(2);
12836   if (!isa<ConstantSDNode>(N2))
12837     return SDValue();
12838   auto *N2C = cast<ConstantSDNode>(N2);
12839   unsigned IdxVal = N2C->getZExtValue();
12840
12841   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
12842   // into that, and then insert the subvector back into the result.
12843   if (VT.is256BitVector() || VT.is512BitVector()) {
12844     // Get the desired 128-bit vector half.
12845     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
12846
12847     // Insert the element into the desired half.
12848     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
12849     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
12850
12851     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
12852                     DAG.getConstant(IdxIn128, MVT::i32));
12853
12854     // Insert the changed part back to the 256-bit vector
12855     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
12856   }
12857   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
12858
12859   if (Subtarget->hasSSE41()) {
12860     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
12861       unsigned Opc;
12862       if (VT == MVT::v8i16) {
12863         Opc = X86ISD::PINSRW;
12864       } else {
12865         assert(VT == MVT::v16i8);
12866         Opc = X86ISD::PINSRB;
12867       }
12868
12869       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
12870       // argument.
12871       if (N1.getValueType() != MVT::i32)
12872         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12873       if (N2.getValueType() != MVT::i32)
12874         N2 = DAG.getIntPtrConstant(IdxVal);
12875       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
12876     }
12877
12878     if (EltVT == MVT::f32) {
12879       // Bits [7:6] of the constant are the source select.  This will always be
12880       //  zero here.  The DAG Combiner may combine an extract_elt index into
12881       //  these
12882       //  bits.  For example (insert (extract, 3), 2) could be matched by
12883       //  putting
12884       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
12885       // Bits [5:4] of the constant are the destination select.  This is the
12886       //  value of the incoming immediate.
12887       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
12888       //   combine either bitwise AND or insert of float 0.0 to set these bits.
12889       N2 = DAG.getIntPtrConstant(IdxVal << 4);
12890       // Create this as a scalar to vector..
12891       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12892       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
12893     }
12894
12895     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
12896       // PINSR* works with constant index.
12897       return Op;
12898     }
12899   }
12900
12901   if (EltVT == MVT::i8)
12902     return SDValue();
12903
12904   if (EltVT.getSizeInBits() == 16) {
12905     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12906     // as its second argument.
12907     if (N1.getValueType() != MVT::i32)
12908       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12909     if (N2.getValueType() != MVT::i32)
12910       N2 = DAG.getIntPtrConstant(IdxVal);
12911     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12912   }
12913   return SDValue();
12914 }
12915
12916 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12917   SDLoc dl(Op);
12918   MVT OpVT = Op.getSimpleValueType();
12919
12920   // If this is a 256-bit vector result, first insert into a 128-bit
12921   // vector and then insert into the 256-bit vector.
12922   if (!OpVT.is128BitVector()) {
12923     // Insert into a 128-bit vector.
12924     unsigned SizeFactor = OpVT.getSizeInBits()/128;
12925     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12926                                  OpVT.getVectorNumElements() / SizeFactor);
12927
12928     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12929
12930     // Insert the 128-bit vector.
12931     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12932   }
12933
12934   if (OpVT == MVT::v1i64 &&
12935       Op.getOperand(0).getValueType() == MVT::i64)
12936     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12937
12938   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12939   assert(OpVT.is128BitVector() && "Expected an SSE type!");
12940   return DAG.getNode(ISD::BITCAST, dl, OpVT,
12941                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
12942 }
12943
12944 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
12945 // a simple subregister reference or explicit instructions to grab
12946 // upper bits of a vector.
12947 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12948                                       SelectionDAG &DAG) {
12949   SDLoc dl(Op);
12950   SDValue In =  Op.getOperand(0);
12951   SDValue Idx = Op.getOperand(1);
12952   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12953   MVT ResVT   = Op.getSimpleValueType();
12954   MVT InVT    = In.getSimpleValueType();
12955
12956   if (Subtarget->hasFp256()) {
12957     if (ResVT.is128BitVector() &&
12958         (InVT.is256BitVector() || InVT.is512BitVector()) &&
12959         isa<ConstantSDNode>(Idx)) {
12960       return Extract128BitVector(In, IdxVal, DAG, dl);
12961     }
12962     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12963         isa<ConstantSDNode>(Idx)) {
12964       return Extract256BitVector(In, IdxVal, DAG, dl);
12965     }
12966   }
12967   return SDValue();
12968 }
12969
12970 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
12971 // simple superregister reference or explicit instructions to insert
12972 // the upper bits of a vector.
12973 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12974                                      SelectionDAG &DAG) {
12975   if (Subtarget->hasFp256()) {
12976     SDLoc dl(Op.getNode());
12977     SDValue Vec = Op.getNode()->getOperand(0);
12978     SDValue SubVec = Op.getNode()->getOperand(1);
12979     SDValue Idx = Op.getNode()->getOperand(2);
12980
12981     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
12982          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
12983         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
12984         isa<ConstantSDNode>(Idx)) {
12985       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12986       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12987     }
12988
12989     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
12990         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
12991         isa<ConstantSDNode>(Idx)) {
12992       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12993       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12994     }
12995   }
12996   return SDValue();
12997 }
12998
12999 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
13000 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
13001 // one of the above mentioned nodes. It has to be wrapped because otherwise
13002 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
13003 // be used to form addressing mode. These wrapped nodes will be selected
13004 // into MOV32ri.
13005 SDValue
13006 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
13007   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
13008
13009   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13010   // global base reg.
13011   unsigned char OpFlag = 0;
13012   unsigned WrapperKind = X86ISD::Wrapper;
13013   CodeModel::Model M = DAG.getTarget().getCodeModel();
13014
13015   if (Subtarget->isPICStyleRIPRel() &&
13016       (M == CodeModel::Small || M == CodeModel::Kernel))
13017     WrapperKind = X86ISD::WrapperRIP;
13018   else if (Subtarget->isPICStyleGOT())
13019     OpFlag = X86II::MO_GOTOFF;
13020   else if (Subtarget->isPICStyleStubPIC())
13021     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13022
13023   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
13024                                              CP->getAlignment(),
13025                                              CP->getOffset(), OpFlag);
13026   SDLoc DL(CP);
13027   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13028   // With PIC, the address is actually $g + Offset.
13029   if (OpFlag) {
13030     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13031                          DAG.getNode(X86ISD::GlobalBaseReg,
13032                                      SDLoc(), getPointerTy()),
13033                          Result);
13034   }
13035
13036   return Result;
13037 }
13038
13039 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
13040   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
13041
13042   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13043   // global base reg.
13044   unsigned char OpFlag = 0;
13045   unsigned WrapperKind = X86ISD::Wrapper;
13046   CodeModel::Model M = DAG.getTarget().getCodeModel();
13047
13048   if (Subtarget->isPICStyleRIPRel() &&
13049       (M == CodeModel::Small || M == CodeModel::Kernel))
13050     WrapperKind = X86ISD::WrapperRIP;
13051   else if (Subtarget->isPICStyleGOT())
13052     OpFlag = X86II::MO_GOTOFF;
13053   else if (Subtarget->isPICStyleStubPIC())
13054     OpFlag = X86II::MO_PIC_BASE_OFFSET;
13055
13056   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
13057                                           OpFlag);
13058   SDLoc DL(JT);
13059   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13060
13061   // With PIC, the address is actually $g + Offset.
13062   if (OpFlag)
13063     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13064                          DAG.getNode(X86ISD::GlobalBaseReg,
13065                                      SDLoc(), getPointerTy()),
13066                          Result);
13067
13068   return Result;
13069 }
13070
13071 SDValue
13072 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
13073   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13074
13075   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13076   // global base reg.
13077   unsigned char OpFlag = 0;
13078   unsigned WrapperKind = X86ISD::Wrapper;
13079   CodeModel::Model M = DAG.getTarget().getCodeModel();
13080
13081   if (Subtarget->isPICStyleRIPRel() &&
13082       (M == CodeModel::Small || M == CodeModel::Kernel)) {
13083     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
13084       OpFlag = X86II::MO_GOTPCREL;
13085     WrapperKind = X86ISD::WrapperRIP;
13086   } else if (Subtarget->isPICStyleGOT()) {
13087     OpFlag = X86II::MO_GOT;
13088   } else if (Subtarget->isPICStyleStubPIC()) {
13089     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
13090   } else if (Subtarget->isPICStyleStubNoDynamic()) {
13091     OpFlag = X86II::MO_DARWIN_NONLAZY;
13092   }
13093
13094   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
13095
13096   SDLoc DL(Op);
13097   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13098
13099   // With PIC, the address is actually $g + Offset.
13100   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
13101       !Subtarget->is64Bit()) {
13102     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13103                          DAG.getNode(X86ISD::GlobalBaseReg,
13104                                      SDLoc(), getPointerTy()),
13105                          Result);
13106   }
13107
13108   // For symbols that require a load from a stub to get the address, emit the
13109   // load.
13110   if (isGlobalStubReference(OpFlag))
13111     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
13112                          MachinePointerInfo::getGOT(), false, false, false, 0);
13113
13114   return Result;
13115 }
13116
13117 SDValue
13118 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
13119   // Create the TargetBlockAddressAddress node.
13120   unsigned char OpFlags =
13121     Subtarget->ClassifyBlockAddressReference();
13122   CodeModel::Model M = DAG.getTarget().getCodeModel();
13123   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
13124   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
13125   SDLoc dl(Op);
13126   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
13127                                              OpFlags);
13128
13129   if (Subtarget->isPICStyleRIPRel() &&
13130       (M == CodeModel::Small || M == CodeModel::Kernel))
13131     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13132   else
13133     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13134
13135   // With PIC, the address is actually $g + Offset.
13136   if (isGlobalRelativeToPICBase(OpFlags)) {
13137     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13138                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13139                          Result);
13140   }
13141
13142   return Result;
13143 }
13144
13145 SDValue
13146 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
13147                                       int64_t Offset, SelectionDAG &DAG) const {
13148   // Create the TargetGlobalAddress node, folding in the constant
13149   // offset if it is legal.
13150   unsigned char OpFlags =
13151       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
13152   CodeModel::Model M = DAG.getTarget().getCodeModel();
13153   SDValue Result;
13154   if (OpFlags == X86II::MO_NO_FLAG &&
13155       X86::isOffsetSuitableForCodeModel(Offset, M)) {
13156     // A direct static reference to a global.
13157     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
13158     Offset = 0;
13159   } else {
13160     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
13161   }
13162
13163   if (Subtarget->isPICStyleRIPRel() &&
13164       (M == CodeModel::Small || M == CodeModel::Kernel))
13165     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
13166   else
13167     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
13168
13169   // With PIC, the address is actually $g + Offset.
13170   if (isGlobalRelativeToPICBase(OpFlags)) {
13171     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
13172                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
13173                          Result);
13174   }
13175
13176   // For globals that require a load from a stub to get the address, emit the
13177   // load.
13178   if (isGlobalStubReference(OpFlags))
13179     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
13180                          MachinePointerInfo::getGOT(), false, false, false, 0);
13181
13182   // If there was a non-zero offset that we didn't fold, create an explicit
13183   // addition for it.
13184   if (Offset != 0)
13185     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
13186                          DAG.getConstant(Offset, getPointerTy()));
13187
13188   return Result;
13189 }
13190
13191 SDValue
13192 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
13193   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
13194   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
13195   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
13196 }
13197
13198 static SDValue
13199 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
13200            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
13201            unsigned char OperandFlags, bool LocalDynamic = false) {
13202   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13203   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13204   SDLoc dl(GA);
13205   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13206                                            GA->getValueType(0),
13207                                            GA->getOffset(),
13208                                            OperandFlags);
13209
13210   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
13211                                            : X86ISD::TLSADDR;
13212
13213   if (InFlag) {
13214     SDValue Ops[] = { Chain,  TGA, *InFlag };
13215     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13216   } else {
13217     SDValue Ops[]  = { Chain, TGA };
13218     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13219   }
13220
13221   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
13222   MFI->setAdjustsStack(true);
13223   MFI->setHasCalls(true);
13224
13225   SDValue Flag = Chain.getValue(1);
13226   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
13227 }
13228
13229 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
13230 static SDValue
13231 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13232                                 const EVT PtrVT) {
13233   SDValue InFlag;
13234   SDLoc dl(GA);  // ? function entry point might be better
13235   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13236                                    DAG.getNode(X86ISD::GlobalBaseReg,
13237                                                SDLoc(), PtrVT), InFlag);
13238   InFlag = Chain.getValue(1);
13239
13240   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
13241 }
13242
13243 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
13244 static SDValue
13245 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13246                                 const EVT PtrVT) {
13247   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
13248                     X86::RAX, X86II::MO_TLSGD);
13249 }
13250
13251 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
13252                                            SelectionDAG &DAG,
13253                                            const EVT PtrVT,
13254                                            bool is64Bit) {
13255   SDLoc dl(GA);
13256
13257   // Get the start address of the TLS block for this module.
13258   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
13259       .getInfo<X86MachineFunctionInfo>();
13260   MFI->incNumLocalDynamicTLSAccesses();
13261
13262   SDValue Base;
13263   if (is64Bit) {
13264     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
13265                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
13266   } else {
13267     SDValue InFlag;
13268     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13269         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
13270     InFlag = Chain.getValue(1);
13271     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
13272                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
13273   }
13274
13275   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
13276   // of Base.
13277
13278   // Build x@dtpoff.
13279   unsigned char OperandFlags = X86II::MO_DTPOFF;
13280   unsigned WrapperKind = X86ISD::Wrapper;
13281   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13282                                            GA->getValueType(0),
13283                                            GA->getOffset(), OperandFlags);
13284   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13285
13286   // Add x@dtpoff with the base.
13287   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
13288 }
13289
13290 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
13291 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13292                                    const EVT PtrVT, TLSModel::Model model,
13293                                    bool is64Bit, bool isPIC) {
13294   SDLoc dl(GA);
13295
13296   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
13297   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
13298                                                          is64Bit ? 257 : 256));
13299
13300   SDValue ThreadPointer =
13301       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
13302                   MachinePointerInfo(Ptr), false, false, false, 0);
13303
13304   unsigned char OperandFlags = 0;
13305   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
13306   // initialexec.
13307   unsigned WrapperKind = X86ISD::Wrapper;
13308   if (model == TLSModel::LocalExec) {
13309     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
13310   } else if (model == TLSModel::InitialExec) {
13311     if (is64Bit) {
13312       OperandFlags = X86II::MO_GOTTPOFF;
13313       WrapperKind = X86ISD::WrapperRIP;
13314     } else {
13315       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
13316     }
13317   } else {
13318     llvm_unreachable("Unexpected model");
13319   }
13320
13321   // emit "addl x@ntpoff,%eax" (local exec)
13322   // or "addl x@indntpoff,%eax" (initial exec)
13323   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
13324   SDValue TGA =
13325       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
13326                                  GA->getOffset(), OperandFlags);
13327   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13328
13329   if (model == TLSModel::InitialExec) {
13330     if (isPIC && !is64Bit) {
13331       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
13332                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13333                            Offset);
13334     }
13335
13336     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
13337                          MachinePointerInfo::getGOT(), false, false, false, 0);
13338   }
13339
13340   // The address of the thread local variable is the add of the thread
13341   // pointer with the offset of the variable.
13342   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
13343 }
13344
13345 SDValue
13346 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
13347
13348   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
13349   const GlobalValue *GV = GA->getGlobal();
13350
13351   if (Subtarget->isTargetELF()) {
13352     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
13353
13354     switch (model) {
13355       case TLSModel::GeneralDynamic:
13356         if (Subtarget->is64Bit())
13357           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
13358         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
13359       case TLSModel::LocalDynamic:
13360         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
13361                                            Subtarget->is64Bit());
13362       case TLSModel::InitialExec:
13363       case TLSModel::LocalExec:
13364         return LowerToTLSExecModel(
13365             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
13366             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
13367     }
13368     llvm_unreachable("Unknown TLS model.");
13369   }
13370
13371   if (Subtarget->isTargetDarwin()) {
13372     // Darwin only has one model of TLS.  Lower to that.
13373     unsigned char OpFlag = 0;
13374     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
13375                            X86ISD::WrapperRIP : X86ISD::Wrapper;
13376
13377     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13378     // global base reg.
13379     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
13380                  !Subtarget->is64Bit();
13381     if (PIC32)
13382       OpFlag = X86II::MO_TLVP_PIC_BASE;
13383     else
13384       OpFlag = X86II::MO_TLVP;
13385     SDLoc DL(Op);
13386     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13387                                                 GA->getValueType(0),
13388                                                 GA->getOffset(), OpFlag);
13389     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
13390
13391     // With PIC32, the address is actually $g + Offset.
13392     if (PIC32)
13393       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13394                            DAG.getNode(X86ISD::GlobalBaseReg,
13395                                        SDLoc(), getPointerTy()),
13396                            Offset);
13397
13398     // Lowering the machine isd will make sure everything is in the right
13399     // location.
13400     SDValue Chain = DAG.getEntryNode();
13401     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13402     SDValue Args[] = { Chain, Offset };
13403     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13404
13405     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13406     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13407     MFI->setAdjustsStack(true);
13408
13409     // And our return value (tls address) is in the standard call return value
13410     // location.
13411     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13412     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
13413                               Chain.getValue(1));
13414   }
13415
13416   if (Subtarget->isTargetKnownWindowsMSVC() ||
13417       Subtarget->isTargetWindowsGNU()) {
13418     // Just use the implicit TLS architecture
13419     // Need to generate someting similar to:
13420     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13421     //                                  ; from TEB
13422     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
13423     //   mov     rcx, qword [rdx+rcx*8]
13424     //   mov     eax, .tls$:tlsvar
13425     //   [rax+rcx] contains the address
13426     // Windows 64bit: gs:0x58
13427     // Windows 32bit: fs:__tls_array
13428
13429     SDLoc dl(GA);
13430     SDValue Chain = DAG.getEntryNode();
13431
13432     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13433     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13434     // use its literal value of 0x2C.
13435     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
13436                                         ? Type::getInt8PtrTy(*DAG.getContext(),
13437                                                              256)
13438                                         : Type::getInt32PtrTy(*DAG.getContext(),
13439                                                               257));
13440
13441     SDValue TlsArray =
13442         Subtarget->is64Bit()
13443             ? DAG.getIntPtrConstant(0x58)
13444             : (Subtarget->isTargetWindowsGNU()
13445                    ? DAG.getIntPtrConstant(0x2C)
13446                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
13447
13448     SDValue ThreadPointer =
13449         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
13450                     MachinePointerInfo(Ptr), false, false, false, 0);
13451
13452     // Load the _tls_index variable
13453     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
13454     if (Subtarget->is64Bit())
13455       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
13456                            IDX, MachinePointerInfo(), MVT::i32,
13457                            false, false, false, 0);
13458     else
13459       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
13460                         false, false, false, 0);
13461
13462     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
13463                                     getPointerTy());
13464     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
13465
13466     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
13467     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
13468                       false, false, false, 0);
13469
13470     // Get the offset of start of .tls section
13471     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13472                                              GA->getValueType(0),
13473                                              GA->getOffset(), X86II::MO_SECREL);
13474     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
13475
13476     // The address of the thread local variable is the add of the thread
13477     // pointer with the offset of the variable.
13478     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
13479   }
13480
13481   llvm_unreachable("TLS not implemented for this target.");
13482 }
13483
13484 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
13485 /// and take a 2 x i32 value to shift plus a shift amount.
13486 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
13487   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
13488   MVT VT = Op.getSimpleValueType();
13489   unsigned VTBits = VT.getSizeInBits();
13490   SDLoc dl(Op);
13491   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
13492   SDValue ShOpLo = Op.getOperand(0);
13493   SDValue ShOpHi = Op.getOperand(1);
13494   SDValue ShAmt  = Op.getOperand(2);
13495   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
13496   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
13497   // during isel.
13498   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13499                                   DAG.getConstant(VTBits - 1, MVT::i8));
13500   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
13501                                      DAG.getConstant(VTBits - 1, MVT::i8))
13502                        : DAG.getConstant(0, VT);
13503
13504   SDValue Tmp2, Tmp3;
13505   if (Op.getOpcode() == ISD::SHL_PARTS) {
13506     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
13507     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
13508   } else {
13509     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
13510     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
13511   }
13512
13513   // If the shift amount is larger or equal than the width of a part we can't
13514   // rely on the results of shld/shrd. Insert a test and select the appropriate
13515   // values for large shift amounts.
13516   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13517                                 DAG.getConstant(VTBits, MVT::i8));
13518   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13519                              AndNode, DAG.getConstant(0, MVT::i8));
13520
13521   SDValue Hi, Lo;
13522   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13523   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
13524   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
13525
13526   if (Op.getOpcode() == ISD::SHL_PARTS) {
13527     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13528     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13529   } else {
13530     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13531     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13532   }
13533
13534   SDValue Ops[2] = { Lo, Hi };
13535   return DAG.getMergeValues(Ops, dl);
13536 }
13537
13538 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
13539                                            SelectionDAG &DAG) const {
13540   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13541   SDLoc dl(Op);
13542
13543   if (SrcVT.isVector()) {
13544     if (SrcVT.getVectorElementType() == MVT::i1) {
13545       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
13546       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13547                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
13548                                      Op.getOperand(0)));
13549     }
13550     return SDValue();
13551   }
13552   
13553   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
13554          "Unknown SINT_TO_FP to lower!");
13555
13556   // These are really Legal; return the operand so the caller accepts it as
13557   // Legal.
13558   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
13559     return Op;
13560   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13561       Subtarget->is64Bit()) {
13562     return Op;
13563   }
13564
13565   unsigned Size = SrcVT.getSizeInBits()/8;
13566   MachineFunction &MF = DAG.getMachineFunction();
13567   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
13568   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13569   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13570                                StackSlot,
13571                                MachinePointerInfo::getFixedStack(SSFI),
13572                                false, false, 0);
13573   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
13574 }
13575
13576 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
13577                                      SDValue StackSlot,
13578                                      SelectionDAG &DAG) const {
13579   // Build the FILD
13580   SDLoc DL(Op);
13581   SDVTList Tys;
13582   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
13583   if (useSSE)
13584     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
13585   else
13586     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
13587
13588   unsigned ByteSize = SrcVT.getSizeInBits()/8;
13589
13590   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
13591   MachineMemOperand *MMO;
13592   if (FI) {
13593     int SSFI = FI->getIndex();
13594     MMO =
13595       DAG.getMachineFunction()
13596       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13597                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
13598   } else {
13599     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
13600     StackSlot = StackSlot.getOperand(1);
13601   }
13602   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
13603   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
13604                                            X86ISD::FILD, DL,
13605                                            Tys, Ops, SrcVT, MMO);
13606
13607   if (useSSE) {
13608     Chain = Result.getValue(1);
13609     SDValue InFlag = Result.getValue(2);
13610
13611     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
13612     // shouldn't be necessary except that RFP cannot be live across
13613     // multiple blocks. When stackifier is fixed, they can be uncoupled.
13614     MachineFunction &MF = DAG.getMachineFunction();
13615     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
13616     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
13617     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13618     Tys = DAG.getVTList(MVT::Other);
13619     SDValue Ops[] = {
13620       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
13621     };
13622     MachineMemOperand *MMO =
13623       DAG.getMachineFunction()
13624       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13625                             MachineMemOperand::MOStore, SSFISize, SSFISize);
13626
13627     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
13628                                     Ops, Op.getValueType(), MMO);
13629     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
13630                          MachinePointerInfo::getFixedStack(SSFI),
13631                          false, false, false, 0);
13632   }
13633
13634   return Result;
13635 }
13636
13637 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
13638 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
13639                                                SelectionDAG &DAG) const {
13640   // This algorithm is not obvious. Here it is what we're trying to output:
13641   /*
13642      movq       %rax,  %xmm0
13643      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
13644      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
13645      #ifdef __SSE3__
13646        haddpd   %xmm0, %xmm0
13647      #else
13648        pshufd   $0x4e, %xmm0, %xmm1
13649        addpd    %xmm1, %xmm0
13650      #endif
13651   */
13652
13653   SDLoc dl(Op);
13654   LLVMContext *Context = DAG.getContext();
13655
13656   // Build some magic constants.
13657   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
13658   Constant *C0 = ConstantDataVector::get(*Context, CV0);
13659   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
13660
13661   SmallVector<Constant*,2> CV1;
13662   CV1.push_back(
13663     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13664                                       APInt(64, 0x4330000000000000ULL))));
13665   CV1.push_back(
13666     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13667                                       APInt(64, 0x4530000000000000ULL))));
13668   Constant *C1 = ConstantVector::get(CV1);
13669   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
13670
13671   // Load the 64-bit value into an XMM register.
13672   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
13673                             Op.getOperand(0));
13674   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
13675                               MachinePointerInfo::getConstantPool(),
13676                               false, false, false, 16);
13677   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
13678                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
13679                               CLod0);
13680
13681   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
13682                               MachinePointerInfo::getConstantPool(),
13683                               false, false, false, 16);
13684   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
13685   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
13686   SDValue Result;
13687
13688   if (Subtarget->hasSSE3()) {
13689     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
13690     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
13691   } else {
13692     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
13693     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
13694                                            S2F, 0x4E, DAG);
13695     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
13696                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
13697                          Sub);
13698   }
13699
13700   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
13701                      DAG.getIntPtrConstant(0));
13702 }
13703
13704 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
13705 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
13706                                                SelectionDAG &DAG) const {
13707   SDLoc dl(Op);
13708   // FP constant to bias correct the final result.
13709   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13710                                    MVT::f64);
13711
13712   // Load the 32-bit value into an XMM register.
13713   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
13714                              Op.getOperand(0));
13715
13716   // Zero out the upper parts of the register.
13717   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
13718
13719   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13720                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
13721                      DAG.getIntPtrConstant(0));
13722
13723   // Or the load with the bias.
13724   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
13725                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13726                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13727                                                    MVT::v2f64, Load)),
13728                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
13729                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13730                                                    MVT::v2f64, Bias)));
13731   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13732                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
13733                    DAG.getIntPtrConstant(0));
13734
13735   // Subtract the bias.
13736   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
13737
13738   // Handle final rounding.
13739   EVT DestVT = Op.getValueType();
13740
13741   if (DestVT.bitsLT(MVT::f64))
13742     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
13743                        DAG.getIntPtrConstant(0));
13744   if (DestVT.bitsGT(MVT::f64))
13745     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
13746
13747   // Handle final rounding.
13748   return Sub;
13749 }
13750
13751 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
13752                                      const X86Subtarget &Subtarget) {
13753   // The algorithm is the following:
13754   // #ifdef __SSE4_1__
13755   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13756   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13757   //                                 (uint4) 0x53000000, 0xaa);
13758   // #else
13759   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13760   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13761   // #endif
13762   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13763   //     return (float4) lo + fhi;
13764
13765   SDLoc DL(Op);
13766   SDValue V = Op->getOperand(0);
13767   EVT VecIntVT = V.getValueType();
13768   bool Is128 = VecIntVT == MVT::v4i32;
13769   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
13770   // If we convert to something else than the supported type, e.g., to v4f64,
13771   // abort early.
13772   if (VecFloatVT != Op->getValueType(0))
13773     return SDValue();
13774
13775   unsigned NumElts = VecIntVT.getVectorNumElements();
13776   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
13777          "Unsupported custom type");
13778   assert(NumElts <= 8 && "The size of the constant array must be fixed");
13779
13780   // In the #idef/#else code, we have in common:
13781   // - The vector of constants:
13782   // -- 0x4b000000
13783   // -- 0x53000000
13784   // - A shift:
13785   // -- v >> 16
13786
13787   // Create the splat vector for 0x4b000000.
13788   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
13789   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
13790                            CstLow, CstLow, CstLow, CstLow};
13791   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13792                                   makeArrayRef(&CstLowArray[0], NumElts));
13793   // Create the splat vector for 0x53000000.
13794   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
13795   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
13796                             CstHigh, CstHigh, CstHigh, CstHigh};
13797   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13798                                    makeArrayRef(&CstHighArray[0], NumElts));
13799
13800   // Create the right shift.
13801   SDValue CstShift = DAG.getConstant(16, MVT::i32);
13802   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
13803                              CstShift, CstShift, CstShift, CstShift};
13804   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
13805                                     makeArrayRef(&CstShiftArray[0], NumElts));
13806   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
13807
13808   SDValue Low, High;
13809   if (Subtarget.hasSSE41()) {
13810     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
13811     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13812     SDValue VecCstLowBitcast =
13813         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
13814     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
13815     // Low will be bitcasted right away, so do not bother bitcasting back to its
13816     // original type.
13817     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
13818                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
13819     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13820     //                                 (uint4) 0x53000000, 0xaa);
13821     SDValue VecCstHighBitcast =
13822         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
13823     SDValue VecShiftBitcast =
13824         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
13825     // High will be bitcasted right away, so do not bother bitcasting back to
13826     // its original type.
13827     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
13828                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
13829   } else {
13830     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
13831     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13832                                      CstMask, CstMask, CstMask);
13833     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13834     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13835     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13836
13837     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
13838     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13839   }
13840
13841   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13842   SDValue CstFAdd = DAG.getConstantFP(
13843       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
13844   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13845                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13846   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13847                                    makeArrayRef(&CstFAddArray[0], NumElts));
13848
13849   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13850   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
13851   SDValue FHigh =
13852       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13853   //     return (float4) lo + fhi;
13854   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
13855   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13856 }
13857
13858 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13859                                                SelectionDAG &DAG) const {
13860   SDValue N0 = Op.getOperand(0);
13861   MVT SVT = N0.getSimpleValueType();
13862   SDLoc dl(Op);
13863
13864   switch (SVT.SimpleTy) {
13865   default:
13866     llvm_unreachable("Custom UINT_TO_FP is not supported!");
13867   case MVT::v4i8:
13868   case MVT::v4i16:
13869   case MVT::v8i8:
13870   case MVT::v8i16: {
13871     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13872     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13873                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13874   }
13875   case MVT::v4i32:
13876   case MVT::v8i32:
13877     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13878   }
13879   llvm_unreachable(nullptr);
13880 }
13881
13882 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13883                                            SelectionDAG &DAG) const {
13884   SDValue N0 = Op.getOperand(0);
13885   SDLoc dl(Op);
13886
13887   if (Op.getValueType().isVector())
13888     return lowerUINT_TO_FP_vec(Op, DAG);
13889
13890   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13891   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13892   // the optimization here.
13893   if (DAG.SignBitIsZero(N0))
13894     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13895
13896   MVT SrcVT = N0.getSimpleValueType();
13897   MVT DstVT = Op.getSimpleValueType();
13898   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13899     return LowerUINT_TO_FP_i64(Op, DAG);
13900   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13901     return LowerUINT_TO_FP_i32(Op, DAG);
13902   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13903     return SDValue();
13904
13905   // Make a 64-bit buffer, and use it to build an FILD.
13906   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13907   if (SrcVT == MVT::i32) {
13908     SDValue WordOff = DAG.getConstant(4, getPointerTy());
13909     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
13910                                      getPointerTy(), StackSlot, WordOff);
13911     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13912                                   StackSlot, MachinePointerInfo(),
13913                                   false, false, 0);
13914     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
13915                                   OffsetSlot, MachinePointerInfo(),
13916                                   false, false, 0);
13917     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13918     return Fild;
13919   }
13920
13921   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13922   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13923                                StackSlot, MachinePointerInfo(),
13924                                false, false, 0);
13925   // For i64 source, we need to add the appropriate power of 2 if the input
13926   // was negative.  This is the same as the optimization in
13927   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13928   // we must be careful to do the computation in x87 extended precision, not
13929   // in SSE. (The generic code can't know it's OK to do this, or how to.)
13930   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13931   MachineMemOperand *MMO =
13932     DAG.getMachineFunction()
13933     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13934                           MachineMemOperand::MOLoad, 8, 8);
13935
13936   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13937   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13938   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13939                                          MVT::i64, MMO);
13940
13941   APInt FF(32, 0x5F800000ULL);
13942
13943   // Check whether the sign bit is set.
13944   SDValue SignSet = DAG.getSetCC(dl,
13945                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
13946                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
13947                                  ISD::SETLT);
13948
13949   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13950   SDValue FudgePtr = DAG.getConstantPool(
13951                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
13952                                          getPointerTy());
13953
13954   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13955   SDValue Zero = DAG.getIntPtrConstant(0);
13956   SDValue Four = DAG.getIntPtrConstant(4);
13957   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13958                                Zero, Four);
13959   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
13960
13961   // Load the value out, extending it from f32 to f80.
13962   // FIXME: Avoid the extend by constructing the right constant pool?
13963   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
13964                                  FudgePtr, MachinePointerInfo::getConstantPool(),
13965                                  MVT::f32, false, false, false, 4);
13966   // Extend everything to 80 bits to force it to be done on x87.
13967   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13968   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
13969 }
13970
13971 std::pair<SDValue,SDValue>
13972 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13973                                     bool IsSigned, bool IsReplace) const {
13974   SDLoc DL(Op);
13975
13976   EVT DstTy = Op.getValueType();
13977
13978   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
13979     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13980     DstTy = MVT::i64;
13981   }
13982
13983   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13984          DstTy.getSimpleVT() >= MVT::i16 &&
13985          "Unknown FP_TO_INT to lower!");
13986
13987   // These are really Legal.
13988   if (DstTy == MVT::i32 &&
13989       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13990     return std::make_pair(SDValue(), SDValue());
13991   if (Subtarget->is64Bit() &&
13992       DstTy == MVT::i64 &&
13993       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13994     return std::make_pair(SDValue(), SDValue());
13995
13996   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
13997   // stack slot, or into the FTOL runtime function.
13998   MachineFunction &MF = DAG.getMachineFunction();
13999   unsigned MemSize = DstTy.getSizeInBits()/8;
14000   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14001   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14002
14003   unsigned Opc;
14004   if (!IsSigned && isIntegerTypeFTOL(DstTy))
14005     Opc = X86ISD::WIN_FTOL;
14006   else
14007     switch (DstTy.getSimpleVT().SimpleTy) {
14008     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
14009     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
14010     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
14011     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
14012     }
14013
14014   SDValue Chain = DAG.getEntryNode();
14015   SDValue Value = Op.getOperand(0);
14016   EVT TheVT = Op.getOperand(0).getValueType();
14017   // FIXME This causes a redundant load/store if the SSE-class value is already
14018   // in memory, such as if it is on the callstack.
14019   if (isScalarFPTypeInSSEReg(TheVT)) {
14020     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
14021     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
14022                          MachinePointerInfo::getFixedStack(SSFI),
14023                          false, false, 0);
14024     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
14025     SDValue Ops[] = {
14026       Chain, StackSlot, DAG.getValueType(TheVT)
14027     };
14028
14029     MachineMemOperand *MMO =
14030       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14031                               MachineMemOperand::MOLoad, MemSize, MemSize);
14032     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
14033     Chain = Value.getValue(1);
14034     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
14035     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14036   }
14037
14038   MachineMemOperand *MMO =
14039     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14040                             MachineMemOperand::MOStore, MemSize, MemSize);
14041
14042   if (Opc != X86ISD::WIN_FTOL) {
14043     // Build the FP_TO_INT*_IN_MEM
14044     SDValue Ops[] = { Chain, Value, StackSlot };
14045     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
14046                                            Ops, DstTy, MMO);
14047     return std::make_pair(FIST, StackSlot);
14048   } else {
14049     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
14050       DAG.getVTList(MVT::Other, MVT::Glue),
14051       Chain, Value);
14052     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
14053       MVT::i32, ftol.getValue(1));
14054     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
14055       MVT::i32, eax.getValue(2));
14056     SDValue Ops[] = { eax, edx };
14057     SDValue pair = IsReplace
14058       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
14059       : DAG.getMergeValues(Ops, DL);
14060     return std::make_pair(pair, SDValue());
14061   }
14062 }
14063
14064 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
14065                               const X86Subtarget *Subtarget) {
14066   MVT VT = Op->getSimpleValueType(0);
14067   SDValue In = Op->getOperand(0);
14068   MVT InVT = In.getSimpleValueType();
14069   SDLoc dl(Op);
14070
14071   // Optimize vectors in AVX mode:
14072   //
14073   //   v8i16 -> v8i32
14074   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14075   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14076   //   Concat upper and lower parts.
14077   //
14078   //   v4i32 -> v4i64
14079   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14080   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14081   //   Concat upper and lower parts.
14082   //
14083
14084   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
14085       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
14086       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
14087     return SDValue();
14088
14089   if (Subtarget->hasInt256())
14090     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
14091
14092   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
14093   SDValue Undef = DAG.getUNDEF(InVT);
14094   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
14095   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14096   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14097
14098   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
14099                              VT.getVectorNumElements()/2);
14100
14101   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14102   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14103
14104   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14105 }
14106
14107 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
14108                                         SelectionDAG &DAG) {
14109   MVT VT = Op->getSimpleValueType(0);
14110   SDValue In = Op->getOperand(0);
14111   MVT InVT = In.getSimpleValueType();
14112   SDLoc DL(Op);
14113   unsigned int NumElts = VT.getVectorNumElements();
14114   if (NumElts != 8 && NumElts != 16)
14115     return SDValue();
14116
14117   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
14118     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
14119
14120   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
14121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14122   // Now we have only mask extension
14123   assert(InVT.getVectorElementType() == MVT::i1);
14124   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
14125   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14126   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
14127   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14128   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14129                            MachinePointerInfo::getConstantPool(),
14130                            false, false, false, Alignment);
14131
14132   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
14133   if (VT.is512BitVector())
14134     return Brcst;
14135   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
14136 }
14137
14138 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14139                                SelectionDAG &DAG) {
14140   if (Subtarget->hasFp256()) {
14141     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14142     if (Res.getNode())
14143       return Res;
14144   }
14145
14146   return SDValue();
14147 }
14148
14149 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14150                                 SelectionDAG &DAG) {
14151   SDLoc DL(Op);
14152   MVT VT = Op.getSimpleValueType();
14153   SDValue In = Op.getOperand(0);
14154   MVT SVT = In.getSimpleValueType();
14155
14156   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
14157     return LowerZERO_EXTEND_AVX512(Op, DAG);
14158
14159   if (Subtarget->hasFp256()) {
14160     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
14161     if (Res.getNode())
14162       return Res;
14163   }
14164
14165   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
14166          VT.getVectorNumElements() != SVT.getVectorNumElements());
14167   return SDValue();
14168 }
14169
14170 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
14171   SDLoc DL(Op);
14172   MVT VT = Op.getSimpleValueType();
14173   SDValue In = Op.getOperand(0);
14174   MVT InVT = In.getSimpleValueType();
14175
14176   if (VT == MVT::i1) {
14177     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
14178            "Invalid scalar TRUNCATE operation");
14179     if (InVT.getSizeInBits() >= 32)
14180       return SDValue();
14181     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
14182     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
14183   }
14184   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
14185          "Invalid TRUNCATE operation");
14186
14187   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
14188     if (VT.getVectorElementType().getSizeInBits() >=8)
14189       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
14190
14191     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14192     unsigned NumElts = InVT.getVectorNumElements();
14193     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
14194     if (InVT.getSizeInBits() < 512) {
14195       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
14196       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
14197       InVT = ExtVT;
14198     }
14199     
14200     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
14201     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
14202     SDValue CP = DAG.getConstantPool(C, getPointerTy());
14203     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14204     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
14205                            MachinePointerInfo::getConstantPool(),
14206                            false, false, false, Alignment);
14207     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
14208     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
14209     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
14210   }
14211
14212   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
14213     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
14214     if (Subtarget->hasInt256()) {
14215       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14216       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
14217       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
14218                                 ShufMask);
14219       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
14220                          DAG.getIntPtrConstant(0));
14221     }
14222
14223     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14224                                DAG.getIntPtrConstant(0));
14225     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14226                                DAG.getIntPtrConstant(2));
14227     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14228     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14229     static const int ShufMask[] = {0, 2, 4, 6};
14230     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
14231   }
14232
14233   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
14234     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
14235     if (Subtarget->hasInt256()) {
14236       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
14237
14238       SmallVector<SDValue,32> pshufbMask;
14239       for (unsigned i = 0; i < 2; ++i) {
14240         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14241         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14242         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14243         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14244         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14245         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14246         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14247         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14248         for (unsigned j = 0; j < 8; ++j)
14249           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14250       }
14251       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
14252       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
14253       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
14254
14255       static const int ShufMask[] = {0,  2,  -1,  -1};
14256       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
14257                                 &ShufMask[0]);
14258       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14259                        DAG.getIntPtrConstant(0));
14260       return DAG.getNode(ISD::BITCAST, DL, VT, In);
14261     }
14262
14263     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14264                                DAG.getIntPtrConstant(0));
14265
14266     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14267                                DAG.getIntPtrConstant(4));
14268
14269     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
14270     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
14271
14272     // The PSHUFB mask:
14273     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14274                                    -1, -1, -1, -1, -1, -1, -1, -1};
14275
14276     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14277     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
14278     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
14279
14280     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
14281     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
14282
14283     // The MOVLHPS Mask:
14284     static const int ShufMask2[] = {0, 1, 4, 5};
14285     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
14286     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
14287   }
14288
14289   // Handle truncation of V256 to V128 using shuffles.
14290   if (!VT.is128BitVector() || !InVT.is256BitVector())
14291     return SDValue();
14292
14293   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
14294
14295   unsigned NumElems = VT.getVectorNumElements();
14296   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
14297
14298   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
14299   // Prepare truncation shuffle mask
14300   for (unsigned i = 0; i != NumElems; ++i)
14301     MaskVec[i] = i * 2;
14302   SDValue V = DAG.getVectorShuffle(NVT, DL,
14303                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
14304                                    DAG.getUNDEF(NVT), &MaskVec[0]);
14305   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
14306                      DAG.getIntPtrConstant(0));
14307 }
14308
14309 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
14310                                            SelectionDAG &DAG) const {
14311   assert(!Op.getSimpleValueType().isVector());
14312
14313   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14314     /*IsSigned=*/ true, /*IsReplace=*/ false);
14315   SDValue FIST = Vals.first, StackSlot = Vals.second;
14316   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
14317   if (!FIST.getNode()) return Op;
14318
14319   if (StackSlot.getNode())
14320     // Load the result.
14321     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14322                        FIST, StackSlot, MachinePointerInfo(),
14323                        false, false, false, 0);
14324
14325   // The node is the result.
14326   return FIST;
14327 }
14328
14329 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
14330                                            SelectionDAG &DAG) const {
14331   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14332     /*IsSigned=*/ false, /*IsReplace=*/ false);
14333   SDValue FIST = Vals.first, StackSlot = Vals.second;
14334   assert(FIST.getNode() && "Unexpected failure");
14335
14336   if (StackSlot.getNode())
14337     // Load the result.
14338     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
14339                        FIST, StackSlot, MachinePointerInfo(),
14340                        false, false, false, 0);
14341
14342   // The node is the result.
14343   return FIST;
14344 }
14345
14346 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
14347   SDLoc DL(Op);
14348   MVT VT = Op.getSimpleValueType();
14349   SDValue In = Op.getOperand(0);
14350   MVT SVT = In.getSimpleValueType();
14351
14352   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
14353
14354   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
14355                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
14356                                  In, DAG.getUNDEF(SVT)));
14357 }
14358
14359 /// The only differences between FABS and FNEG are the mask and the logic op.
14360 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
14361 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
14362   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
14363          "Wrong opcode for lowering FABS or FNEG.");
14364
14365   bool IsFABS = (Op.getOpcode() == ISD::FABS);
14366
14367   // If this is a FABS and it has an FNEG user, bail out to fold the combination
14368   // into an FNABS. We'll lower the FABS after that if it is still in use.
14369   if (IsFABS)
14370     for (SDNode *User : Op->uses())
14371       if (User->getOpcode() == ISD::FNEG)
14372         return Op;
14373
14374   SDValue Op0 = Op.getOperand(0);
14375   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
14376
14377   SDLoc dl(Op);
14378   MVT VT = Op.getSimpleValueType();
14379   // Assume scalar op for initialization; update for vector if needed.
14380   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
14381   // generate a 16-byte vector constant and logic op even for the scalar case.
14382   // Using a 16-byte mask allows folding the load of the mask with
14383   // the logic op, so it can save (~4 bytes) on code size.
14384   MVT EltVT = VT;
14385   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
14386   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
14387   // decide if we should generate a 16-byte constant mask when we only need 4 or
14388   // 8 bytes for the scalar case.
14389   if (VT.isVector()) {
14390     EltVT = VT.getVectorElementType();
14391     NumElts = VT.getVectorNumElements();
14392   }
14393   
14394   unsigned EltBits = EltVT.getSizeInBits();
14395   LLVMContext *Context = DAG.getContext();
14396   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14397   APInt MaskElt =
14398     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14399   Constant *C = ConstantInt::get(*Context, MaskElt);
14400   C = ConstantVector::getSplat(NumElts, C);
14401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14402   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
14403   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14404   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14405                              MachinePointerInfo::getConstantPool(),
14406                              false, false, false, Alignment);
14407
14408   if (VT.isVector()) {
14409     // For a vector, cast operands to a vector type, perform the logic op,
14410     // and cast the result back to the original value type.
14411     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
14412     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
14413     SDValue Operand = IsFNABS ?
14414       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
14415       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
14416     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
14417     return DAG.getNode(ISD::BITCAST, dl, VT,
14418                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
14419   }
14420   
14421   // If not vector, then scalar.
14422   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14423   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14424   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
14425 }
14426
14427 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14429   LLVMContext *Context = DAG.getContext();
14430   SDValue Op0 = Op.getOperand(0);
14431   SDValue Op1 = Op.getOperand(1);
14432   SDLoc dl(Op);
14433   MVT VT = Op.getSimpleValueType();
14434   MVT SrcVT = Op1.getSimpleValueType();
14435
14436   // If second operand is smaller, extend it first.
14437   if (SrcVT.bitsLT(VT)) {
14438     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14439     SrcVT = VT;
14440   }
14441   // And if it is bigger, shrink it first.
14442   if (SrcVT.bitsGT(VT)) {
14443     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
14444     SrcVT = VT;
14445   }
14446
14447   // At this point the operands and the result should have the same
14448   // type, and that won't be f80 since that is not custom lowered.
14449
14450   // First get the sign bit of second operand.
14451   SmallVector<Constant*,4> CV;
14452   if (SrcVT == MVT::f64) {
14453     const fltSemantics &Sem = APFloat::IEEEdouble;
14454     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
14455     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
14456   } else {
14457     const fltSemantics &Sem = APFloat::IEEEsingle;
14458     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
14459     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14460     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14461     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14462   }
14463   Constant *C = ConstantVector::get(CV);
14464   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14465   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
14466                               MachinePointerInfo::getConstantPool(),
14467                               false, false, false, 16);
14468   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
14469
14470   // Shift sign bit right or left if the two operands have different types.
14471   if (SrcVT.bitsGT(VT)) {
14472     // Op0 is MVT::f32, Op1 is MVT::f64.
14473     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
14474     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
14475                           DAG.getConstant(32, MVT::i32));
14476     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
14477     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
14478                           DAG.getIntPtrConstant(0));
14479   }
14480
14481   // Clear first operand sign bit.
14482   CV.clear();
14483   if (VT == MVT::f64) {
14484     const fltSemantics &Sem = APFloat::IEEEdouble;
14485     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
14486                                                    APInt(64, ~(1ULL << 63)))));
14487     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
14488   } else {
14489     const fltSemantics &Sem = APFloat::IEEEsingle;
14490     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
14491                                                    APInt(32, ~(1U << 31)))));
14492     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14493     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14494     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
14495   }
14496   C = ConstantVector::get(CV);
14497   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
14498   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
14499                               MachinePointerInfo::getConstantPool(),
14500                               false, false, false, 16);
14501   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
14502
14503   // Or the value with the sign bit.
14504   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
14505 }
14506
14507 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
14508   SDValue N0 = Op.getOperand(0);
14509   SDLoc dl(Op);
14510   MVT VT = Op.getSimpleValueType();
14511
14512   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
14513   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
14514                                   DAG.getConstant(1, VT));
14515   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
14516 }
14517
14518 // Check whether an OR'd tree is PTEST-able.
14519 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
14520                                       SelectionDAG &DAG) {
14521   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
14522
14523   if (!Subtarget->hasSSE41())
14524     return SDValue();
14525
14526   if (!Op->hasOneUse())
14527     return SDValue();
14528
14529   SDNode *N = Op.getNode();
14530   SDLoc DL(N);
14531
14532   SmallVector<SDValue, 8> Opnds;
14533   DenseMap<SDValue, unsigned> VecInMap;
14534   SmallVector<SDValue, 8> VecIns;
14535   EVT VT = MVT::Other;
14536
14537   // Recognize a special case where a vector is casted into wide integer to
14538   // test all 0s.
14539   Opnds.push_back(N->getOperand(0));
14540   Opnds.push_back(N->getOperand(1));
14541
14542   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14543     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
14544     // BFS traverse all OR'd operands.
14545     if (I->getOpcode() == ISD::OR) {
14546       Opnds.push_back(I->getOperand(0));
14547       Opnds.push_back(I->getOperand(1));
14548       // Re-evaluate the number of nodes to be traversed.
14549       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14550       continue;
14551     }
14552
14553     // Quit if a non-EXTRACT_VECTOR_ELT
14554     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14555       return SDValue();
14556
14557     // Quit if without a constant index.
14558     SDValue Idx = I->getOperand(1);
14559     if (!isa<ConstantSDNode>(Idx))
14560       return SDValue();
14561
14562     SDValue ExtractedFromVec = I->getOperand(0);
14563     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
14564     if (M == VecInMap.end()) {
14565       VT = ExtractedFromVec.getValueType();
14566       // Quit if not 128/256-bit vector.
14567       if (!VT.is128BitVector() && !VT.is256BitVector())
14568         return SDValue();
14569       // Quit if not the same type.
14570       if (VecInMap.begin() != VecInMap.end() &&
14571           VT != VecInMap.begin()->first.getValueType())
14572         return SDValue();
14573       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
14574       VecIns.push_back(ExtractedFromVec);
14575     }
14576     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14577   }
14578
14579   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14580          "Not extracted from 128-/256-bit vector.");
14581
14582   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
14583
14584   for (DenseMap<SDValue, unsigned>::const_iterator
14585         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
14586     // Quit if not all elements are used.
14587     if (I->second != FullMask)
14588       return SDValue();
14589   }
14590
14591   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
14592
14593   // Cast all vectors into TestVT for PTEST.
14594   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
14595     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
14596
14597   // If more than one full vectors are evaluated, OR them first before PTEST.
14598   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
14599     // Each iteration will OR 2 nodes and append the result until there is only
14600     // 1 node left, i.e. the final OR'd value of all vectors.
14601     SDValue LHS = VecIns[Slot];
14602     SDValue RHS = VecIns[Slot + 1];
14603     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
14604   }
14605
14606   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
14607                      VecIns.back(), VecIns.back());
14608 }
14609
14610 /// \brief return true if \c Op has a use that doesn't just read flags.
14611 static bool hasNonFlagsUse(SDValue Op) {
14612   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
14613        ++UI) {
14614     SDNode *User = *UI;
14615     unsigned UOpNo = UI.getOperandNo();
14616     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
14617       // Look pass truncate.
14618       UOpNo = User->use_begin().getOperandNo();
14619       User = *User->use_begin();
14620     }
14621
14622     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
14623         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
14624       return true;
14625   }
14626   return false;
14627 }
14628
14629 /// Emit nodes that will be selected as "test Op0,Op0", or something
14630 /// equivalent.
14631 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
14632                                     SelectionDAG &DAG) const {
14633   if (Op.getValueType() == MVT::i1)
14634     // KORTEST instruction should be selected
14635     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14636                        DAG.getConstant(0, Op.getValueType()));
14637
14638   // CF and OF aren't always set the way we want. Determine which
14639   // of these we need.
14640   bool NeedCF = false;
14641   bool NeedOF = false;
14642   switch (X86CC) {
14643   default: break;
14644   case X86::COND_A: case X86::COND_AE:
14645   case X86::COND_B: case X86::COND_BE:
14646     NeedCF = true;
14647     break;
14648   case X86::COND_G: case X86::COND_GE:
14649   case X86::COND_L: case X86::COND_LE:
14650   case X86::COND_O: case X86::COND_NO: {
14651     // Check if we really need to set the
14652     // Overflow flag. If NoSignedWrap is present
14653     // that is not actually needed.
14654     switch (Op->getOpcode()) {
14655     case ISD::ADD:
14656     case ISD::SUB:
14657     case ISD::MUL:
14658     case ISD::SHL: {
14659       const BinaryWithFlagsSDNode *BinNode =
14660           cast<BinaryWithFlagsSDNode>(Op.getNode());
14661       if (BinNode->hasNoSignedWrap())
14662         break;
14663     }
14664     default:
14665       NeedOF = true;
14666       break;
14667     }
14668     break;
14669   }
14670   }
14671   // See if we can use the EFLAGS value from the operand instead of
14672   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14673   // we prove that the arithmetic won't overflow, we can't use OF or CF.
14674   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14675     // Emit a CMP with 0, which is the TEST pattern.
14676     //if (Op.getValueType() == MVT::i1)
14677     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14678     //                     DAG.getConstant(0, MVT::i1));
14679     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14680                        DAG.getConstant(0, Op.getValueType()));
14681   }
14682   unsigned Opcode = 0;
14683   unsigned NumOperands = 0;
14684
14685   // Truncate operations may prevent the merge of the SETCC instruction
14686   // and the arithmetic instruction before it. Attempt to truncate the operands
14687   // of the arithmetic instruction and use a reduced bit-width instruction.
14688   bool NeedTruncation = false;
14689   SDValue ArithOp = Op;
14690   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14691     SDValue Arith = Op->getOperand(0);
14692     // Both the trunc and the arithmetic op need to have one user each.
14693     if (Arith->hasOneUse())
14694       switch (Arith.getOpcode()) {
14695         default: break;
14696         case ISD::ADD:
14697         case ISD::SUB:
14698         case ISD::AND:
14699         case ISD::OR:
14700         case ISD::XOR: {
14701           NeedTruncation = true;
14702           ArithOp = Arith;
14703         }
14704       }
14705   }
14706
14707   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14708   // which may be the result of a CAST.  We use the variable 'Op', which is the
14709   // non-casted variable when we check for possible users.
14710   switch (ArithOp.getOpcode()) {
14711   case ISD::ADD:
14712     // Due to an isel shortcoming, be conservative if this add is likely to be
14713     // selected as part of a load-modify-store instruction. When the root node
14714     // in a match is a store, isel doesn't know how to remap non-chain non-flag
14715     // uses of other nodes in the match, such as the ADD in this case. This
14716     // leads to the ADD being left around and reselected, with the result being
14717     // two adds in the output.  Alas, even if none our users are stores, that
14718     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
14719     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
14720     // climbing the DAG back to the root, and it doesn't seem to be worth the
14721     // effort.
14722     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14723          UE = Op.getNode()->use_end(); UI != UE; ++UI)
14724       if (UI->getOpcode() != ISD::CopyToReg &&
14725           UI->getOpcode() != ISD::SETCC &&
14726           UI->getOpcode() != ISD::STORE)
14727         goto default_case;
14728
14729     if (ConstantSDNode *C =
14730         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14731       // An add of one will be selected as an INC.
14732       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
14733         Opcode = X86ISD::INC;
14734         NumOperands = 1;
14735         break;
14736       }
14737
14738       // An add of negative one (subtract of one) will be selected as a DEC.
14739       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
14740         Opcode = X86ISD::DEC;
14741         NumOperands = 1;
14742         break;
14743       }
14744     }
14745
14746     // Otherwise use a regular EFLAGS-setting add.
14747     Opcode = X86ISD::ADD;
14748     NumOperands = 2;
14749     break;
14750   case ISD::SHL:
14751   case ISD::SRL:
14752     // If we have a constant logical shift that's only used in a comparison
14753     // against zero turn it into an equivalent AND. This allows turning it into
14754     // a TEST instruction later.
14755     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14756         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14757       EVT VT = Op.getValueType();
14758       unsigned BitWidth = VT.getSizeInBits();
14759       unsigned ShAmt = Op->getConstantOperandVal(1);
14760       if (ShAmt >= BitWidth) // Avoid undefined shifts.
14761         break;
14762       APInt Mask = ArithOp.getOpcode() == ISD::SRL
14763                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14764                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14765       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14766         break;
14767       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14768                                 DAG.getConstant(Mask, VT));
14769       DAG.ReplaceAllUsesWith(Op, New);
14770       Op = New;
14771     }
14772     break;
14773
14774   case ISD::AND:
14775     // If the primary and result isn't used, don't bother using X86ISD::AND,
14776     // because a TEST instruction will be better.
14777     if (!hasNonFlagsUse(Op))
14778       break;
14779     // FALL THROUGH
14780   case ISD::SUB:
14781   case ISD::OR:
14782   case ISD::XOR:
14783     // Due to the ISEL shortcoming noted above, be conservative if this op is
14784     // likely to be selected as part of a load-modify-store instruction.
14785     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14786            UE = Op.getNode()->use_end(); UI != UE; ++UI)
14787       if (UI->getOpcode() == ISD::STORE)
14788         goto default_case;
14789
14790     // Otherwise use a regular EFLAGS-setting instruction.
14791     switch (ArithOp.getOpcode()) {
14792     default: llvm_unreachable("unexpected operator!");
14793     case ISD::SUB: Opcode = X86ISD::SUB; break;
14794     case ISD::XOR: Opcode = X86ISD::XOR; break;
14795     case ISD::AND: Opcode = X86ISD::AND; break;
14796     case ISD::OR: {
14797       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14798         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14799         if (EFLAGS.getNode())
14800           return EFLAGS;
14801       }
14802       Opcode = X86ISD::OR;
14803       break;
14804     }
14805     }
14806
14807     NumOperands = 2;
14808     break;
14809   case X86ISD::ADD:
14810   case X86ISD::SUB:
14811   case X86ISD::INC:
14812   case X86ISD::DEC:
14813   case X86ISD::OR:
14814   case X86ISD::XOR:
14815   case X86ISD::AND:
14816     return SDValue(Op.getNode(), 1);
14817   default:
14818   default_case:
14819     break;
14820   }
14821
14822   // If we found that truncation is beneficial, perform the truncation and
14823   // update 'Op'.
14824   if (NeedTruncation) {
14825     EVT VT = Op.getValueType();
14826     SDValue WideVal = Op->getOperand(0);
14827     EVT WideVT = WideVal.getValueType();
14828     unsigned ConvertedOp = 0;
14829     // Use a target machine opcode to prevent further DAGCombine
14830     // optimizations that may separate the arithmetic operations
14831     // from the setcc node.
14832     switch (WideVal.getOpcode()) {
14833       default: break;
14834       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14835       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14836       case ISD::AND: ConvertedOp = X86ISD::AND; break;
14837       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
14838       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14839     }
14840
14841     if (ConvertedOp) {
14842       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14843       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14844         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14845         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14846         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14847       }
14848     }
14849   }
14850
14851   if (Opcode == 0)
14852     // Emit a CMP with 0, which is the TEST pattern.
14853     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14854                        DAG.getConstant(0, Op.getValueType()));
14855
14856   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14857   SmallVector<SDValue, 4> Ops;
14858   for (unsigned i = 0; i != NumOperands; ++i)
14859     Ops.push_back(Op.getOperand(i));
14860
14861   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14862   DAG.ReplaceAllUsesWith(Op, New);
14863   return SDValue(New.getNode(), 1);
14864 }
14865
14866 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14867 /// equivalent.
14868 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14869                                    SDLoc dl, SelectionDAG &DAG) const {
14870   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
14871     if (C->getAPIntValue() == 0)
14872       return EmitTest(Op0, X86CC, dl, DAG);
14873
14874      if (Op0.getValueType() == MVT::i1)
14875        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
14876   }
14877  
14878   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14879        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14880     // Do the comparison at i32 if it's smaller, besides the Atom case. 
14881     // This avoids subregister aliasing issues. Keep the smaller reference 
14882     // if we're optimizing for size, however, as that'll allow better folding 
14883     // of memory operations.
14884     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14885         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
14886              AttributeSet::FunctionIndex, Attribute::MinSize) &&
14887         !Subtarget->isAtom()) {
14888       unsigned ExtendOp =
14889           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14890       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14891       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14892     }
14893     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14894     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14895     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14896                               Op0, Op1);
14897     return SDValue(Sub.getNode(), 1);
14898   }
14899   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14900 }
14901
14902 /// Convert a comparison if required by the subtarget.
14903 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14904                                                  SelectionDAG &DAG) const {
14905   // If the subtarget does not support the FUCOMI instruction, floating-point
14906   // comparisons have to be converted.
14907   if (Subtarget->hasCMov() ||
14908       Cmp.getOpcode() != X86ISD::CMP ||
14909       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14910       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14911     return Cmp;
14912
14913   // The instruction selector will select an FUCOM instruction instead of
14914   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14915   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14916   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14917   SDLoc dl(Cmp);
14918   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14919   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14920   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14921                             DAG.getConstant(8, MVT::i8));
14922   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14923   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14924 }
14925
14926 /// The minimum architected relative accuracy is 2^-12. We need one
14927 /// Newton-Raphson step to have a good float result (24 bits of precision).
14928 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14929                                             DAGCombinerInfo &DCI,
14930                                             unsigned &RefinementSteps,
14931                                             bool &UseOneConstNR) const {
14932   // FIXME: We should use instruction latency models to calculate the cost of
14933   // each potential sequence, but this is very hard to do reliably because
14934   // at least Intel's Core* chips have variable timing based on the number of
14935   // significant digits in the divisor and/or sqrt operand.
14936   if (!Subtarget->useSqrtEst())
14937     return SDValue();
14938
14939   EVT VT = Op.getValueType();
14940   
14941   // SSE1 has rsqrtss and rsqrtps.
14942   // TODO: Add support for AVX512 (v16f32).
14943   // It is likely not profitable to do this for f64 because a double-precision
14944   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14945   // instructions: convert to single, rsqrtss, convert back to double, refine
14946   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14947   // along with FMA, this could be a throughput win.
14948   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14949       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14950     RefinementSteps = 1;
14951     UseOneConstNR = false;
14952     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14953   }
14954   return SDValue();
14955 }
14956
14957 /// The minimum architected relative accuracy is 2^-12. We need one
14958 /// Newton-Raphson step to have a good float result (24 bits of precision).
14959 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14960                                             DAGCombinerInfo &DCI,
14961                                             unsigned &RefinementSteps) const {
14962   // FIXME: We should use instruction latency models to calculate the cost of
14963   // each potential sequence, but this is very hard to do reliably because
14964   // at least Intel's Core* chips have variable timing based on the number of
14965   // significant digits in the divisor.
14966   if (!Subtarget->useReciprocalEst())
14967     return SDValue();
14968   
14969   EVT VT = Op.getValueType();
14970   
14971   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14972   // TODO: Add support for AVX512 (v16f32).
14973   // It is likely not profitable to do this for f64 because a double-precision
14974   // reciprocal estimate with refinement on x86 prior to FMA requires
14975   // 15 instructions: convert to single, rcpss, convert back to double, refine
14976   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14977   // along with FMA, this could be a throughput win.
14978   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
14979       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
14980     RefinementSteps = ReciprocalEstimateRefinementSteps;
14981     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14982   }
14983   return SDValue();
14984 }
14985
14986 static bool isAllOnes(SDValue V) {
14987   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
14988   return C && C->isAllOnesValue();
14989 }
14990
14991 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14992 /// if it's possible.
14993 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14994                                      SDLoc dl, SelectionDAG &DAG) const {
14995   SDValue Op0 = And.getOperand(0);
14996   SDValue Op1 = And.getOperand(1);
14997   if (Op0.getOpcode() == ISD::TRUNCATE)
14998     Op0 = Op0.getOperand(0);
14999   if (Op1.getOpcode() == ISD::TRUNCATE)
15000     Op1 = Op1.getOperand(0);
15001
15002   SDValue LHS, RHS;
15003   if (Op1.getOpcode() == ISD::SHL)
15004     std::swap(Op0, Op1);
15005   if (Op0.getOpcode() == ISD::SHL) {
15006     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
15007       if (And00C->getZExtValue() == 1) {
15008         // If we looked past a truncate, check that it's only truncating away
15009         // known zeros.
15010         unsigned BitWidth = Op0.getValueSizeInBits();
15011         unsigned AndBitWidth = And.getValueSizeInBits();
15012         if (BitWidth > AndBitWidth) {
15013           APInt Zeros, Ones;
15014           DAG.computeKnownBits(Op0, Zeros, Ones);
15015           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
15016             return SDValue();
15017         }
15018         LHS = Op1;
15019         RHS = Op0.getOperand(1);
15020       }
15021   } else if (Op1.getOpcode() == ISD::Constant) {
15022     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
15023     uint64_t AndRHSVal = AndRHS->getZExtValue();
15024     SDValue AndLHS = Op0;
15025
15026     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
15027       LHS = AndLHS.getOperand(0);
15028       RHS = AndLHS.getOperand(1);
15029     }
15030
15031     // Use BT if the immediate can't be encoded in a TEST instruction.
15032     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
15033       LHS = AndLHS;
15034       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
15035     }
15036   }
15037
15038   if (LHS.getNode()) {
15039     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
15040     // instruction.  Since the shift amount is in-range-or-undefined, we know
15041     // that doing a bittest on the i32 value is ok.  We extend to i32 because
15042     // the encoding for the i16 version is larger than the i32 version.
15043     // Also promote i16 to i32 for performance / code size reason.
15044     if (LHS.getValueType() == MVT::i8 ||
15045         LHS.getValueType() == MVT::i16)
15046       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
15047
15048     // If the operand types disagree, extend the shift amount to match.  Since
15049     // BT ignores high bits (like shifts) we can use anyextend.
15050     if (LHS.getValueType() != RHS.getValueType())
15051       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
15052
15053     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
15054     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
15055     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15056                        DAG.getConstant(Cond, MVT::i8), BT);
15057   }
15058
15059   return SDValue();
15060 }
15061
15062 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
15063 /// mask CMPs.
15064 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
15065                               SDValue &Op1) {
15066   unsigned SSECC;
15067   bool Swap = false;
15068
15069   // SSE Condition code mapping:
15070   //  0 - EQ
15071   //  1 - LT
15072   //  2 - LE
15073   //  3 - UNORD
15074   //  4 - NEQ
15075   //  5 - NLT
15076   //  6 - NLE
15077   //  7 - ORD
15078   switch (SetCCOpcode) {
15079   default: llvm_unreachable("Unexpected SETCC condition");
15080   case ISD::SETOEQ:
15081   case ISD::SETEQ:  SSECC = 0; break;
15082   case ISD::SETOGT:
15083   case ISD::SETGT:  Swap = true; // Fallthrough
15084   case ISD::SETLT:
15085   case ISD::SETOLT: SSECC = 1; break;
15086   case ISD::SETOGE:
15087   case ISD::SETGE:  Swap = true; // Fallthrough
15088   case ISD::SETLE:
15089   case ISD::SETOLE: SSECC = 2; break;
15090   case ISD::SETUO:  SSECC = 3; break;
15091   case ISD::SETUNE:
15092   case ISD::SETNE:  SSECC = 4; break;
15093   case ISD::SETULE: Swap = true; // Fallthrough
15094   case ISD::SETUGE: SSECC = 5; break;
15095   case ISD::SETULT: Swap = true; // Fallthrough
15096   case ISD::SETUGT: SSECC = 6; break;
15097   case ISD::SETO:   SSECC = 7; break;
15098   case ISD::SETUEQ:
15099   case ISD::SETONE: SSECC = 8; break;
15100   }
15101   if (Swap)
15102     std::swap(Op0, Op1);
15103
15104   return SSECC;
15105 }
15106
15107 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
15108 // ones, and then concatenate the result back.
15109 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
15110   MVT VT = Op.getSimpleValueType();
15111
15112   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
15113          "Unsupported value type for operation");
15114
15115   unsigned NumElems = VT.getVectorNumElements();
15116   SDLoc dl(Op);
15117   SDValue CC = Op.getOperand(2);
15118
15119   // Extract the LHS vectors
15120   SDValue LHS = Op.getOperand(0);
15121   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15122   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15123
15124   // Extract the RHS vectors
15125   SDValue RHS = Op.getOperand(1);
15126   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15127   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15128
15129   // Issue the operation on the smaller types and concatenate the result back
15130   MVT EltVT = VT.getVectorElementType();
15131   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15132   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15133                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
15134                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
15135 }
15136
15137 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
15138                                      const X86Subtarget *Subtarget) {
15139   SDValue Op0 = Op.getOperand(0);
15140   SDValue Op1 = Op.getOperand(1);
15141   SDValue CC = Op.getOperand(2);
15142   MVT VT = Op.getSimpleValueType();
15143   SDLoc dl(Op);
15144
15145   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
15146          Op.getValueType().getScalarType() == MVT::i1 &&
15147          "Cannot set masked compare for this operation");
15148
15149   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15150   unsigned  Opc = 0;
15151   bool Unsigned = false;
15152   bool Swap = false;
15153   unsigned SSECC;
15154   switch (SetCCOpcode) {
15155   default: llvm_unreachable("Unexpected SETCC condition");
15156   case ISD::SETNE:  SSECC = 4; break;
15157   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
15158   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
15159   case ISD::SETLT:  Swap = true; //fall-through
15160   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
15161   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
15162   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
15163   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
15164   case ISD::SETULE: Unsigned = true; //fall-through
15165   case ISD::SETLE:  SSECC = 2; break;
15166   }
15167
15168   if (Swap)
15169     std::swap(Op0, Op1);
15170   if (Opc)
15171     return DAG.getNode(Opc, dl, VT, Op0, Op1);
15172   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
15173   return DAG.getNode(Opc, dl, VT, Op0, Op1,
15174                      DAG.getConstant(SSECC, MVT::i8));
15175 }
15176
15177 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
15178 /// operand \p Op1.  If non-trivial (for example because it's not constant)
15179 /// return an empty value.
15180 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
15181 {
15182   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
15183   if (!BV)
15184     return SDValue();
15185
15186   MVT VT = Op1.getSimpleValueType();
15187   MVT EVT = VT.getVectorElementType();
15188   unsigned n = VT.getVectorNumElements();
15189   SmallVector<SDValue, 8> ULTOp1;
15190
15191   for (unsigned i = 0; i < n; ++i) {
15192     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
15193     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
15194       return SDValue();
15195
15196     // Avoid underflow.
15197     APInt Val = Elt->getAPIntValue();
15198     if (Val == 0)
15199       return SDValue();
15200
15201     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
15202   }
15203
15204   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
15205 }
15206
15207 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
15208                            SelectionDAG &DAG) {
15209   SDValue Op0 = Op.getOperand(0);
15210   SDValue Op1 = Op.getOperand(1);
15211   SDValue CC = Op.getOperand(2);
15212   MVT VT = Op.getSimpleValueType();
15213   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15214   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
15215   SDLoc dl(Op);
15216
15217   if (isFP) {
15218 #ifndef NDEBUG
15219     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
15220     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
15221 #endif
15222
15223     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
15224     unsigned Opc = X86ISD::CMPP;
15225     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
15226       assert(VT.getVectorNumElements() <= 16);
15227       Opc = X86ISD::CMPM;
15228     }
15229     // In the two special cases we can't handle, emit two comparisons.
15230     if (SSECC == 8) {
15231       unsigned CC0, CC1;
15232       unsigned CombineOpc;
15233       if (SetCCOpcode == ISD::SETUEQ) {
15234         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
15235       } else {
15236         assert(SetCCOpcode == ISD::SETONE);
15237         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
15238       }
15239
15240       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15241                                  DAG.getConstant(CC0, MVT::i8));
15242       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15243                                  DAG.getConstant(CC1, MVT::i8));
15244       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
15245     }
15246     // Handle all other FP comparisons here.
15247     return DAG.getNode(Opc, dl, VT, Op0, Op1,
15248                        DAG.getConstant(SSECC, MVT::i8));
15249   }
15250
15251   // Break 256-bit integer vector compare into smaller ones.
15252   if (VT.is256BitVector() && !Subtarget->hasInt256())
15253     return Lower256IntVSETCC(Op, DAG);
15254
15255   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
15256   EVT OpVT = Op1.getValueType();
15257   if (Subtarget->hasAVX512()) {
15258     if (Op1.getValueType().is512BitVector() ||
15259         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
15260         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
15261       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
15262
15263     // In AVX-512 architecture setcc returns mask with i1 elements,
15264     // But there is no compare instruction for i8 and i16 elements in KNL.
15265     // We are not talking about 512-bit operands in this case, these
15266     // types are illegal.
15267     if (MaskResult &&
15268         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
15269          OpVT.getVectorElementType().getSizeInBits() >= 8))
15270       return DAG.getNode(ISD::TRUNCATE, dl, VT,
15271                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
15272   }
15273
15274   // We are handling one of the integer comparisons here.  Since SSE only has
15275   // GT and EQ comparisons for integer, swapping operands and multiple
15276   // operations may be required for some comparisons.
15277   unsigned Opc;
15278   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
15279   bool Subus = false;
15280
15281   switch (SetCCOpcode) {
15282   default: llvm_unreachable("Unexpected SETCC condition");
15283   case ISD::SETNE:  Invert = true;
15284   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
15285   case ISD::SETLT:  Swap = true;
15286   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
15287   case ISD::SETGE:  Swap = true;
15288   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
15289                     Invert = true; break;
15290   case ISD::SETULT: Swap = true;
15291   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
15292                     FlipSigns = true; break;
15293   case ISD::SETUGE: Swap = true;
15294   case ISD::SETULE: Opc = X86ISD::PCMPGT;
15295                     FlipSigns = true; Invert = true; break;
15296   }
15297
15298   // Special case: Use min/max operations for SETULE/SETUGE
15299   MVT VET = VT.getVectorElementType();
15300   bool hasMinMax =
15301        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
15302     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
15303
15304   if (hasMinMax) {
15305     switch (SetCCOpcode) {
15306     default: break;
15307     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
15308     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
15309     }
15310
15311     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
15312   }
15313
15314   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
15315   if (!MinMax && hasSubus) {
15316     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
15317     // Op0 u<= Op1:
15318     //   t = psubus Op0, Op1
15319     //   pcmpeq t, <0..0>
15320     switch (SetCCOpcode) {
15321     default: break;
15322     case ISD::SETULT: {
15323       // If the comparison is against a constant we can turn this into a
15324       // setule.  With psubus, setule does not require a swap.  This is
15325       // beneficial because the constant in the register is no longer
15326       // destructed as the destination so it can be hoisted out of a loop.
15327       // Only do this pre-AVX since vpcmp* is no longer destructive.
15328       if (Subtarget->hasAVX())
15329         break;
15330       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
15331       if (ULEOp1.getNode()) {
15332         Op1 = ULEOp1;
15333         Subus = true; Invert = false; Swap = false;
15334       }
15335       break;
15336     }
15337     // Psubus is better than flip-sign because it requires no inversion.
15338     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
15339     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
15340     }
15341
15342     if (Subus) {
15343       Opc = X86ISD::SUBUS;
15344       FlipSigns = false;
15345     }
15346   }
15347
15348   if (Swap)
15349     std::swap(Op0, Op1);
15350
15351   // Check that the operation in question is available (most are plain SSE2,
15352   // but PCMPGTQ and PCMPEQQ have different requirements).
15353   if (VT == MVT::v2i64) {
15354     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
15355       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
15356
15357       // First cast everything to the right type.
15358       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15359       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15360
15361       // Since SSE has no unsigned integer comparisons, we need to flip the sign
15362       // bits of the inputs before performing those operations. The lower
15363       // compare is always unsigned.
15364       SDValue SB;
15365       if (FlipSigns) {
15366         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
15367       } else {
15368         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
15369         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
15370         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
15371                          Sign, Zero, Sign, Zero);
15372       }
15373       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
15374       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
15375
15376       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
15377       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
15378       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
15379
15380       // Create masks for only the low parts/high parts of the 64 bit integers.
15381       static const int MaskHi[] = { 1, 1, 3, 3 };
15382       static const int MaskLo[] = { 0, 0, 2, 2 };
15383       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
15384       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
15385       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
15386
15387       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
15388       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15389
15390       if (Invert)
15391         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15392
15393       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15394     }
15395
15396     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
15397       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15398       // pcmpeqd + pshufd + pand.
15399       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
15400
15401       // First cast everything to the right type.
15402       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
15403       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
15404
15405       // Do the compare.
15406       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15407
15408       // Make sure the lower and upper halves are both all-ones.
15409       static const int Mask[] = { 1, 0, 3, 2 };
15410       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15411       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15412
15413       if (Invert)
15414         Result = DAG.getNOT(dl, Result, MVT::v4i32);
15415
15416       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15417     }
15418   }
15419
15420   // Since SSE has no unsigned integer comparisons, we need to flip the sign
15421   // bits of the inputs before performing those operations.
15422   if (FlipSigns) {
15423     EVT EltVT = VT.getVectorElementType();
15424     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
15425     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15426     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15427   }
15428
15429   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15430
15431   // If the logical-not of the result is required, perform that now.
15432   if (Invert)
15433     Result = DAG.getNOT(dl, Result, VT);
15434
15435   if (MinMax)
15436     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15437
15438   if (Subus)
15439     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15440                          getZeroVector(VT, Subtarget, DAG, dl));
15441
15442   return Result;
15443 }
15444
15445 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15446
15447   MVT VT = Op.getSimpleValueType();
15448
15449   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15450
15451   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15452          && "SetCC type must be 8-bit or 1-bit integer");
15453   SDValue Op0 = Op.getOperand(0);
15454   SDValue Op1 = Op.getOperand(1);
15455   SDLoc dl(Op);
15456   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15457
15458   // Optimize to BT if possible.
15459   // Lower (X & (1 << N)) == 0 to BT(X, N).
15460   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15461   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15462   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15463       Op1.getOpcode() == ISD::Constant &&
15464       cast<ConstantSDNode>(Op1)->isNullValue() &&
15465       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15466     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
15467     if (NewSetCC.getNode())
15468       return NewSetCC;
15469   }
15470
15471   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
15472   // these.
15473   if (Op1.getOpcode() == ISD::Constant &&
15474       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
15475        cast<ConstantSDNode>(Op1)->isNullValue()) &&
15476       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15477
15478     // If the input is a setcc, then reuse the input setcc or use a new one with
15479     // the inverted condition.
15480     if (Op0.getOpcode() == X86ISD::SETCC) {
15481       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15482       bool Invert = (CC == ISD::SETNE) ^
15483         cast<ConstantSDNode>(Op1)->isNullValue();
15484       if (!Invert)
15485         return Op0;
15486
15487       CCode = X86::GetOppositeBranchCondition(CCode);
15488       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15489                                   DAG.getConstant(CCode, MVT::i8),
15490                                   Op0.getOperand(1));
15491       if (VT == MVT::i1)
15492         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15493       return SetCC;
15494     }
15495   }
15496   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
15497       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
15498       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15499
15500     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
15501     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
15502   }
15503
15504   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
15505   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
15506   if (X86CC == X86::COND_INVALID)
15507     return SDValue();
15508
15509   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
15510   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
15511   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15512                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
15513   if (VT == MVT::i1)
15514     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15515   return SetCC;
15516 }
15517
15518 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
15519 static bool isX86LogicalCmp(SDValue Op) {
15520   unsigned Opc = Op.getNode()->getOpcode();
15521   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
15522       Opc == X86ISD::SAHF)
15523     return true;
15524   if (Op.getResNo() == 1 &&
15525       (Opc == X86ISD::ADD ||
15526        Opc == X86ISD::SUB ||
15527        Opc == X86ISD::ADC ||
15528        Opc == X86ISD::SBB ||
15529        Opc == X86ISD::SMUL ||
15530        Opc == X86ISD::UMUL ||
15531        Opc == X86ISD::INC ||
15532        Opc == X86ISD::DEC ||
15533        Opc == X86ISD::OR ||
15534        Opc == X86ISD::XOR ||
15535        Opc == X86ISD::AND))
15536     return true;
15537
15538   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15539     return true;
15540
15541   return false;
15542 }
15543
15544 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15545   if (V.getOpcode() != ISD::TRUNCATE)
15546     return false;
15547
15548   SDValue VOp0 = V.getOperand(0);
15549   unsigned InBits = VOp0.getValueSizeInBits();
15550   unsigned Bits = V.getValueSizeInBits();
15551   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15552 }
15553
15554 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15555   bool addTest = true;
15556   SDValue Cond  = Op.getOperand(0);
15557   SDValue Op1 = Op.getOperand(1);
15558   SDValue Op2 = Op.getOperand(2);
15559   SDLoc DL(Op);
15560   EVT VT = Op1.getValueType();
15561   SDValue CC;
15562
15563   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15564   // are available. Otherwise fp cmovs get lowered into a less efficient branch
15565   // sequence later on.
15566   if (Cond.getOpcode() == ISD::SETCC &&
15567       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15568        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15569       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
15570     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15571     int SSECC = translateX86FSETCC(
15572         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15573
15574     if (SSECC != 8) {
15575       if (Subtarget->hasAVX512()) {
15576         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15577                                   DAG.getConstant(SSECC, MVT::i8));
15578         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15579       }
15580       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15581                                 DAG.getConstant(SSECC, MVT::i8));
15582       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15583       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15584       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15585     }
15586   }
15587
15588   if (Cond.getOpcode() == ISD::SETCC) {
15589     SDValue NewCond = LowerSETCC(Cond, DAG);
15590     if (NewCond.getNode())
15591       Cond = NewCond;
15592   }
15593
15594   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15595   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15596   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15597   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15598   if (Cond.getOpcode() == X86ISD::SETCC &&
15599       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15600       isZero(Cond.getOperand(1).getOperand(1))) {
15601     SDValue Cmp = Cond.getOperand(1);
15602
15603     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15604
15605     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
15606         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15607       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
15608
15609       SDValue CmpOp0 = Cmp.getOperand(0);
15610       // Apply further optimizations for special cases
15611       // (select (x != 0), -1, 0) -> neg & sbb
15612       // (select (x == 0), 0, -1) -> neg & sbb
15613       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
15614         if (YC->isNullValue() &&
15615             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
15616           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15617           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15618                                     DAG.getConstant(0, CmpOp0.getValueType()),
15619                                     CmpOp0);
15620           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15621                                     DAG.getConstant(X86::COND_B, MVT::i8),
15622                                     SDValue(Neg.getNode(), 1));
15623           return Res;
15624         }
15625
15626       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15627                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
15628       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15629
15630       SDValue Res =   // Res = 0 or -1.
15631         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15632                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
15633
15634       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
15635         Res = DAG.getNOT(DL, Res, Res.getValueType());
15636
15637       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
15638       if (!N2C || !N2C->isNullValue())
15639         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15640       return Res;
15641     }
15642   }
15643
15644   // Look past (and (setcc_carry (cmp ...)), 1).
15645   if (Cond.getOpcode() == ISD::AND &&
15646       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15647     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15648     if (C && C->getAPIntValue() == 1)
15649       Cond = Cond.getOperand(0);
15650   }
15651
15652   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15653   // setting operand in place of the X86ISD::SETCC.
15654   unsigned CondOpcode = Cond.getOpcode();
15655   if (CondOpcode == X86ISD::SETCC ||
15656       CondOpcode == X86ISD::SETCC_CARRY) {
15657     CC = Cond.getOperand(0);
15658
15659     SDValue Cmp = Cond.getOperand(1);
15660     unsigned Opc = Cmp.getOpcode();
15661     MVT VT = Op.getSimpleValueType();
15662
15663     bool IllegalFPCMov = false;
15664     if (VT.isFloatingPoint() && !VT.isVector() &&
15665         !isScalarFPTypeInSSEReg(VT))  // FPStack?
15666       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15667
15668     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15669         Opc == X86ISD::BT) { // FIXME
15670       Cond = Cmp;
15671       addTest = false;
15672     }
15673   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15674              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15675              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15676               Cond.getOperand(0).getValueType() != MVT::i8)) {
15677     SDValue LHS = Cond.getOperand(0);
15678     SDValue RHS = Cond.getOperand(1);
15679     unsigned X86Opcode;
15680     unsigned X86Cond;
15681     SDVTList VTs;
15682     switch (CondOpcode) {
15683     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15684     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15685     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15686     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15687     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15688     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15689     default: llvm_unreachable("unexpected overflowing operator");
15690     }
15691     if (CondOpcode == ISD::UMULO)
15692       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15693                           MVT::i32);
15694     else
15695       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15696
15697     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15698
15699     if (CondOpcode == ISD::UMULO)
15700       Cond = X86Op.getValue(2);
15701     else
15702       Cond = X86Op.getValue(1);
15703
15704     CC = DAG.getConstant(X86Cond, MVT::i8);
15705     addTest = false;
15706   }
15707
15708   if (addTest) {
15709     // Look pass the truncate if the high bits are known zero.
15710     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15711         Cond = Cond.getOperand(0);
15712
15713     // We know the result of AND is compared against zero. Try to match
15714     // it to BT.
15715     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15716       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
15717       if (NewSetCC.getNode()) {
15718         CC = NewSetCC.getOperand(0);
15719         Cond = NewSetCC.getOperand(1);
15720         addTest = false;
15721       }
15722     }
15723   }
15724
15725   if (addTest) {
15726     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15727     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15728   }
15729
15730   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15731   // a <  b ?  0 : -1 -> RES = setcc_carry
15732   // a >= b ? -1 :  0 -> RES = setcc_carry
15733   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15734   if (Cond.getOpcode() == X86ISD::SUB) {
15735     Cond = ConvertCmpIfNecessary(Cond, DAG);
15736     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15737
15738     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15739         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
15740       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15741                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
15742       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
15743         return DAG.getNOT(DL, Res, Res.getValueType());
15744       return Res;
15745     }
15746   }
15747
15748   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15749   // widen the cmov and push the truncate through. This avoids introducing a new
15750   // branch during isel and doesn't add any extensions.
15751   if (Op.getValueType() == MVT::i8 &&
15752       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15753     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15754     if (T1.getValueType() == T2.getValueType() &&
15755         // Blacklist CopyFromReg to avoid partial register stalls.
15756         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15757       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15758       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15759       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15760     }
15761   }
15762
15763   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15764   // condition is true.
15765   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15766   SDValue Ops[] = { Op2, Op1, CC, Cond };
15767   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15768 }
15769
15770 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
15771                                        SelectionDAG &DAG) {
15772   MVT VT = Op->getSimpleValueType(0);
15773   SDValue In = Op->getOperand(0);
15774   MVT InVT = In.getSimpleValueType();
15775   MVT VTElt = VT.getVectorElementType();
15776   MVT InVTElt = InVT.getVectorElementType();
15777   SDLoc dl(Op);
15778
15779   // SKX processor
15780   if ((InVTElt == MVT::i1) &&
15781       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15782         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15783
15784        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15785         VTElt.getSizeInBits() <= 16)) ||
15786
15787        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15788         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15789     
15790        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15791         VTElt.getSizeInBits() >= 32))))
15792     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15793     
15794   unsigned int NumElts = VT.getVectorNumElements();
15795
15796   if (NumElts != 8 && NumElts != 16)
15797     return SDValue();
15798
15799   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15800     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15801       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15802     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15803   }
15804
15805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15806   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15807
15808   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
15809   Constant *C = ConstantInt::get(*DAG.getContext(),
15810     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
15811
15812   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
15813   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
15814   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
15815                           MachinePointerInfo::getConstantPool(),
15816                           false, false, false, Alignment);
15817   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
15818   if (VT.is512BitVector())
15819     return Brcst;
15820   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
15821 }
15822
15823 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15824                                 SelectionDAG &DAG) {
15825   MVT VT = Op->getSimpleValueType(0);
15826   SDValue In = Op->getOperand(0);
15827   MVT InVT = In.getSimpleValueType();
15828   SDLoc dl(Op);
15829
15830   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15831     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15832
15833   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15834       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15835       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15836     return SDValue();
15837
15838   if (Subtarget->hasInt256())
15839     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15840
15841   // Optimize vectors in AVX mode
15842   // Sign extend  v8i16 to v8i32 and
15843   //              v4i32 to v4i64
15844   //
15845   // Divide input vector into two parts
15846   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15847   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15848   // concat the vectors to original VT
15849
15850   unsigned NumElems = InVT.getVectorNumElements();
15851   SDValue Undef = DAG.getUNDEF(InVT);
15852
15853   SmallVector<int,8> ShufMask1(NumElems, -1);
15854   for (unsigned i = 0; i != NumElems/2; ++i)
15855     ShufMask1[i] = i;
15856
15857   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15858
15859   SmallVector<int,8> ShufMask2(NumElems, -1);
15860   for (unsigned i = 0; i != NumElems/2; ++i)
15861     ShufMask2[i] = i + NumElems/2;
15862
15863   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15864
15865   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15866                                 VT.getVectorNumElements()/2);
15867
15868   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15869   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15870
15871   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15872 }
15873
15874 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15875 // may emit an illegal shuffle but the expansion is still better than scalar
15876 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15877 // we'll emit a shuffle and a arithmetic shift.
15878 // TODO: It is possible to support ZExt by zeroing the undef values during
15879 // the shuffle phase or after the shuffle.
15880 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15881                                  SelectionDAG &DAG) {
15882   MVT RegVT = Op.getSimpleValueType();
15883   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15884   assert(RegVT.isInteger() &&
15885          "We only custom lower integer vector sext loads.");
15886
15887   // Nothing useful we can do without SSE2 shuffles.
15888   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15889
15890   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15891   SDLoc dl(Ld);
15892   EVT MemVT = Ld->getMemoryVT();
15893   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15894   unsigned RegSz = RegVT.getSizeInBits();
15895
15896   ISD::LoadExtType Ext = Ld->getExtensionType();
15897
15898   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15899          && "Only anyext and sext are currently implemented.");
15900   assert(MemVT != RegVT && "Cannot extend to the same type");
15901   assert(MemVT.isVector() && "Must load a vector from memory");
15902
15903   unsigned NumElems = RegVT.getVectorNumElements();
15904   unsigned MemSz = MemVT.getSizeInBits();
15905   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15906
15907   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15908     // The only way in which we have a legal 256-bit vector result but not the
15909     // integer 256-bit operations needed to directly lower a sextload is if we
15910     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15911     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15912     // correctly legalized. We do this late to allow the canonical form of
15913     // sextload to persist throughout the rest of the DAG combiner -- it wants
15914     // to fold together any extensions it can, and so will fuse a sign_extend
15915     // of an sextload into a sextload targeting a wider value.
15916     SDValue Load;
15917     if (MemSz == 128) {
15918       // Just switch this to a normal load.
15919       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15920                                        "it must be a legal 128-bit vector "
15921                                        "type!");
15922       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15923                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15924                   Ld->isInvariant(), Ld->getAlignment());
15925     } else {
15926       assert(MemSz < 128 &&
15927              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15928       // Do an sext load to a 128-bit vector type. We want to use the same
15929       // number of elements, but elements half as wide. This will end up being
15930       // recursively lowered by this routine, but will succeed as we definitely
15931       // have all the necessary features if we're using AVX1.
15932       EVT HalfEltVT =
15933           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15934       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15935       Load =
15936           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15937                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15938                          Ld->isNonTemporal(), Ld->isInvariant(),
15939                          Ld->getAlignment());
15940     }
15941
15942     // Replace chain users with the new chain.
15943     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15944     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15945
15946     // Finally, do a normal sign-extend to the desired register.
15947     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15948   }
15949
15950   // All sizes must be a power of two.
15951   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15952          "Non-power-of-two elements are not custom lowered!");
15953
15954   // Attempt to load the original value using scalar loads.
15955   // Find the largest scalar type that divides the total loaded size.
15956   MVT SclrLoadTy = MVT::i8;
15957   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15958        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15959     MVT Tp = (MVT::SimpleValueType)tp;
15960     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15961       SclrLoadTy = Tp;
15962     }
15963   }
15964
15965   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15966   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15967       (64 <= MemSz))
15968     SclrLoadTy = MVT::f64;
15969
15970   // Calculate the number of scalar loads that we need to perform
15971   // in order to load our vector from memory.
15972   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15973
15974   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15975          "Can only lower sext loads with a single scalar load!");
15976
15977   unsigned loadRegZize = RegSz;
15978   if (Ext == ISD::SEXTLOAD && RegSz == 256)
15979     loadRegZize /= 2;
15980
15981   // Represent our vector as a sequence of elements which are the
15982   // largest scalar that we can load.
15983   EVT LoadUnitVecVT = EVT::getVectorVT(
15984       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15985
15986   // Represent the data using the same element type that is stored in
15987   // memory. In practice, we ''widen'' MemVT.
15988   EVT WideVecVT =
15989       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15990                        loadRegZize / MemVT.getScalarType().getSizeInBits());
15991
15992   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15993          "Invalid vector type");
15994
15995   // We can't shuffle using an illegal type.
15996   assert(TLI.isTypeLegal(WideVecVT) &&
15997          "We only lower types that form legal widened vector types");
15998
15999   SmallVector<SDValue, 8> Chains;
16000   SDValue Ptr = Ld->getBasePtr();
16001   SDValue Increment =
16002       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
16003   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16004
16005   for (unsigned i = 0; i < NumLoads; ++i) {
16006     // Perform a single load.
16007     SDValue ScalarLoad =
16008         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
16009                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
16010                     Ld->getAlignment());
16011     Chains.push_back(ScalarLoad.getValue(1));
16012     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16013     // another round of DAGCombining.
16014     if (i == 0)
16015       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16016     else
16017       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16018                         ScalarLoad, DAG.getIntPtrConstant(i));
16019
16020     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16021   }
16022
16023   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
16024
16025   // Bitcast the loaded value to a vector of the original element type, in
16026   // the size of the target vector type.
16027   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16028   unsigned SizeRatio = RegSz / MemSz;
16029
16030   if (Ext == ISD::SEXTLOAD) {
16031     // If we have SSE4.1, we can directly emit a VSEXT node.
16032     if (Subtarget->hasSSE41()) {
16033       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16034       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16035       return Sext;
16036     }
16037
16038     // Otherwise we'll shuffle the small elements in the high bits of the
16039     // larger type and perform an arithmetic shift. If the shift is not legal
16040     // it's better to scalarize.
16041     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
16042            "We can't implement a sext load without an arithmetic right shift!");
16043
16044     // Redistribute the loaded elements into the different locations.
16045     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16046     for (unsigned i = 0; i != NumElems; ++i)
16047       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
16048
16049     SDValue Shuff = DAG.getVectorShuffle(
16050         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16051
16052     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16053
16054     // Build the arithmetic shift.
16055     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16056                    MemVT.getVectorElementType().getSizeInBits();
16057     Shuff =
16058         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
16059
16060     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16061     return Shuff;
16062   }
16063
16064   // Redistribute the loaded elements into the different locations.
16065   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16066   for (unsigned i = 0; i != NumElems; ++i)
16067     ShuffleVec[i * SizeRatio] = i;
16068
16069   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16070                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
16071
16072   // Bitcast to the requested type.
16073   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16074   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16075   return Shuff;
16076 }
16077
16078 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
16079 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
16080 // from the AND / OR.
16081 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
16082   Opc = Op.getOpcode();
16083   if (Opc != ISD::OR && Opc != ISD::AND)
16084     return false;
16085   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16086           Op.getOperand(0).hasOneUse() &&
16087           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
16088           Op.getOperand(1).hasOneUse());
16089 }
16090
16091 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
16092 // 1 and that the SETCC node has a single use.
16093 static bool isXor1OfSetCC(SDValue Op) {
16094   if (Op.getOpcode() != ISD::XOR)
16095     return false;
16096   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16097   if (N1C && N1C->getAPIntValue() == 1) {
16098     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16099       Op.getOperand(0).hasOneUse();
16100   }
16101   return false;
16102 }
16103
16104 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
16105   bool addTest = true;
16106   SDValue Chain = Op.getOperand(0);
16107   SDValue Cond  = Op.getOperand(1);
16108   SDValue Dest  = Op.getOperand(2);
16109   SDLoc dl(Op);
16110   SDValue CC;
16111   bool Inverted = false;
16112
16113   if (Cond.getOpcode() == ISD::SETCC) {
16114     // Check for setcc([su]{add,sub,mul}o == 0).
16115     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
16116         isa<ConstantSDNode>(Cond.getOperand(1)) &&
16117         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
16118         Cond.getOperand(0).getResNo() == 1 &&
16119         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
16120          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
16121          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
16122          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
16123          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
16124          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
16125       Inverted = true;
16126       Cond = Cond.getOperand(0);
16127     } else {
16128       SDValue NewCond = LowerSETCC(Cond, DAG);
16129       if (NewCond.getNode())
16130         Cond = NewCond;
16131     }
16132   }
16133 #if 0
16134   // FIXME: LowerXALUO doesn't handle these!!
16135   else if (Cond.getOpcode() == X86ISD::ADD  ||
16136            Cond.getOpcode() == X86ISD::SUB  ||
16137            Cond.getOpcode() == X86ISD::SMUL ||
16138            Cond.getOpcode() == X86ISD::UMUL)
16139     Cond = LowerXALUO(Cond, DAG);
16140 #endif
16141
16142   // Look pass (and (setcc_carry (cmp ...)), 1).
16143   if (Cond.getOpcode() == ISD::AND &&
16144       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
16145     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
16146     if (C && C->getAPIntValue() == 1)
16147       Cond = Cond.getOperand(0);
16148   }
16149
16150   // If condition flag is set by a X86ISD::CMP, then use it as the condition
16151   // setting operand in place of the X86ISD::SETCC.
16152   unsigned CondOpcode = Cond.getOpcode();
16153   if (CondOpcode == X86ISD::SETCC ||
16154       CondOpcode == X86ISD::SETCC_CARRY) {
16155     CC = Cond.getOperand(0);
16156
16157     SDValue Cmp = Cond.getOperand(1);
16158     unsigned Opc = Cmp.getOpcode();
16159     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
16160     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
16161       Cond = Cmp;
16162       addTest = false;
16163     } else {
16164       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
16165       default: break;
16166       case X86::COND_O:
16167       case X86::COND_B:
16168         // These can only come from an arithmetic instruction with overflow,
16169         // e.g. SADDO, UADDO.
16170         Cond = Cond.getNode()->getOperand(1);
16171         addTest = false;
16172         break;
16173       }
16174     }
16175   }
16176   CondOpcode = Cond.getOpcode();
16177   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
16178       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
16179       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
16180        Cond.getOperand(0).getValueType() != MVT::i8)) {
16181     SDValue LHS = Cond.getOperand(0);
16182     SDValue RHS = Cond.getOperand(1);
16183     unsigned X86Opcode;
16184     unsigned X86Cond;
16185     SDVTList VTs;
16186     // Keep this in sync with LowerXALUO, otherwise we might create redundant
16187     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
16188     // X86ISD::INC).
16189     switch (CondOpcode) {
16190     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
16191     case ISD::SADDO:
16192       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16193         if (C->isOne()) {
16194           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
16195           break;
16196         }
16197       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
16198     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
16199     case ISD::SSUBO:
16200       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16201         if (C->isOne()) {
16202           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
16203           break;
16204         }
16205       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
16206     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
16207     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
16208     default: llvm_unreachable("unexpected overflowing operator");
16209     }
16210     if (Inverted)
16211       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
16212     if (CondOpcode == ISD::UMULO)
16213       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
16214                           MVT::i32);
16215     else
16216       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
16217
16218     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
16219
16220     if (CondOpcode == ISD::UMULO)
16221       Cond = X86Op.getValue(2);
16222     else
16223       Cond = X86Op.getValue(1);
16224
16225     CC = DAG.getConstant(X86Cond, MVT::i8);
16226     addTest = false;
16227   } else {
16228     unsigned CondOpc;
16229     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
16230       SDValue Cmp = Cond.getOperand(0).getOperand(1);
16231       if (CondOpc == ISD::OR) {
16232         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
16233         // two branches instead of an explicit OR instruction with a
16234         // separate test.
16235         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16236             isX86LogicalCmp(Cmp)) {
16237           CC = Cond.getOperand(0).getOperand(0);
16238           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16239                               Chain, Dest, CC, Cmp);
16240           CC = Cond.getOperand(1).getOperand(0);
16241           Cond = Cmp;
16242           addTest = false;
16243         }
16244       } else { // ISD::AND
16245         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
16246         // two branches instead of an explicit AND instruction with a
16247         // separate test. However, we only do this if this block doesn't
16248         // have a fall-through edge, because this requires an explicit
16249         // jmp when the condition is false.
16250         if (Cmp == Cond.getOperand(1).getOperand(1) &&
16251             isX86LogicalCmp(Cmp) &&
16252             Op.getNode()->hasOneUse()) {
16253           X86::CondCode CCode =
16254             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16255           CCode = X86::GetOppositeBranchCondition(CCode);
16256           CC = DAG.getConstant(CCode, MVT::i8);
16257           SDNode *User = *Op.getNode()->use_begin();
16258           // Look for an unconditional branch following this conditional branch.
16259           // We need this because we need to reverse the successors in order
16260           // to implement FCMP_OEQ.
16261           if (User->getOpcode() == ISD::BR) {
16262             SDValue FalseBB = User->getOperand(1);
16263             SDNode *NewBR =
16264               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16265             assert(NewBR == User);
16266             (void)NewBR;
16267             Dest = FalseBB;
16268
16269             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16270                                 Chain, Dest, CC, Cmp);
16271             X86::CondCode CCode =
16272               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
16273             CCode = X86::GetOppositeBranchCondition(CCode);
16274             CC = DAG.getConstant(CCode, MVT::i8);
16275             Cond = Cmp;
16276             addTest = false;
16277           }
16278         }
16279       }
16280     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
16281       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
16282       // It should be transformed during dag combiner except when the condition
16283       // is set by a arithmetics with overflow node.
16284       X86::CondCode CCode =
16285         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16286       CCode = X86::GetOppositeBranchCondition(CCode);
16287       CC = DAG.getConstant(CCode, MVT::i8);
16288       Cond = Cond.getOperand(0).getOperand(1);
16289       addTest = false;
16290     } else if (Cond.getOpcode() == ISD::SETCC &&
16291                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
16292       // For FCMP_OEQ, we can emit
16293       // two branches instead of an explicit AND instruction with a
16294       // separate test. However, we only do this if this block doesn't
16295       // have a fall-through edge, because this requires an explicit
16296       // jmp when the condition is false.
16297       if (Op.getNode()->hasOneUse()) {
16298         SDNode *User = *Op.getNode()->use_begin();
16299         // Look for an unconditional branch following this conditional branch.
16300         // We need this because we need to reverse the successors in order
16301         // to implement FCMP_OEQ.
16302         if (User->getOpcode() == ISD::BR) {
16303           SDValue FalseBB = User->getOperand(1);
16304           SDNode *NewBR =
16305             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16306           assert(NewBR == User);
16307           (void)NewBR;
16308           Dest = FalseBB;
16309
16310           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16311                                     Cond.getOperand(0), Cond.getOperand(1));
16312           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16313           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16314           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16315                               Chain, Dest, CC, Cmp);
16316           CC = DAG.getConstant(X86::COND_P, MVT::i8);
16317           Cond = Cmp;
16318           addTest = false;
16319         }
16320       }
16321     } else if (Cond.getOpcode() == ISD::SETCC &&
16322                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
16323       // For FCMP_UNE, we can emit
16324       // two branches instead of an explicit AND instruction with a
16325       // separate test. However, we only do this if this block doesn't
16326       // have a fall-through edge, because this requires an explicit
16327       // jmp when the condition is false.
16328       if (Op.getNode()->hasOneUse()) {
16329         SDNode *User = *Op.getNode()->use_begin();
16330         // Look for an unconditional branch following this conditional branch.
16331         // We need this because we need to reverse the successors in order
16332         // to implement FCMP_UNE.
16333         if (User->getOpcode() == ISD::BR) {
16334           SDValue FalseBB = User->getOperand(1);
16335           SDNode *NewBR =
16336             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16337           assert(NewBR == User);
16338           (void)NewBR;
16339
16340           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16341                                     Cond.getOperand(0), Cond.getOperand(1));
16342           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16343           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
16344           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16345                               Chain, Dest, CC, Cmp);
16346           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
16347           Cond = Cmp;
16348           addTest = false;
16349           Dest = FalseBB;
16350         }
16351       }
16352     }
16353   }
16354
16355   if (addTest) {
16356     // Look pass the truncate if the high bits are known zero.
16357     if (isTruncWithZeroHighBitsInput(Cond, DAG))
16358         Cond = Cond.getOperand(0);
16359
16360     // We know the result of AND is compared against zero. Try to match
16361     // it to BT.
16362     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16363       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
16364       if (NewSetCC.getNode()) {
16365         CC = NewSetCC.getOperand(0);
16366         Cond = NewSetCC.getOperand(1);
16367         addTest = false;
16368       }
16369     }
16370   }
16371
16372   if (addTest) {
16373     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
16374     CC = DAG.getConstant(X86Cond, MVT::i8);
16375     Cond = EmitTest(Cond, X86Cond, dl, DAG);
16376   }
16377   Cond = ConvertCmpIfNecessary(Cond, DAG);
16378   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16379                      Chain, Dest, CC, Cond);
16380 }
16381
16382 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
16383 // Calls to _alloca are needed to probe the stack when allocating more than 4k
16384 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
16385 // that the guard pages used by the OS virtual memory manager are allocated in
16386 // correct sequence.
16387 SDValue
16388 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
16389                                            SelectionDAG &DAG) const {
16390   MachineFunction &MF = DAG.getMachineFunction();
16391   bool SplitStack = MF.shouldSplitStack();
16392   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
16393                SplitStack;
16394   SDLoc dl(Op);
16395
16396   if (!Lower) {
16397     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16398     SDNode* Node = Op.getNode();
16399
16400     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16401     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16402         " not tell us which reg is the stack pointer!");
16403     EVT VT = Node->getValueType(0);
16404     SDValue Tmp1 = SDValue(Node, 0);
16405     SDValue Tmp2 = SDValue(Node, 1);
16406     SDValue Tmp3 = Node->getOperand(2);
16407     SDValue Chain = Tmp1.getOperand(0);
16408
16409     // Chain the dynamic stack allocation so that it doesn't modify the stack
16410     // pointer when other instructions are using the stack.
16411     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
16412         SDLoc(Node));
16413
16414     SDValue Size = Tmp2.getOperand(1);
16415     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16416     Chain = SP.getValue(1);
16417     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
16418     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
16419     unsigned StackAlign = TFI.getStackAlignment();
16420     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16421     if (Align > StackAlign)
16422       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
16423           DAG.getConstant(-(uint64_t)Align, VT));
16424     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
16425
16426     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
16427         DAG.getIntPtrConstant(0, true), SDValue(),
16428         SDLoc(Node));
16429
16430     SDValue Ops[2] = { Tmp1, Tmp2 };
16431     return DAG.getMergeValues(Ops, dl);
16432   }
16433
16434   // Get the inputs.
16435   SDValue Chain = Op.getOperand(0);
16436   SDValue Size  = Op.getOperand(1);
16437   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16438   EVT VT = Op.getNode()->getValueType(0);
16439
16440   bool Is64Bit = Subtarget->is64Bit();
16441   EVT SPTy = getPointerTy();
16442
16443   if (SplitStack) {
16444     MachineRegisterInfo &MRI = MF.getRegInfo();
16445
16446     if (Is64Bit) {
16447       // The 64 bit implementation of segmented stacks needs to clobber both r10
16448       // r11. This makes it impossible to use it along with nested parameters.
16449       const Function *F = MF.getFunction();
16450
16451       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16452            I != E; ++I)
16453         if (I->hasNestAttr())
16454           report_fatal_error("Cannot use segmented stacks with functions that "
16455                              "have nested arguments.");
16456     }
16457
16458     const TargetRegisterClass *AddrRegClass =
16459       getRegClassFor(getPointerTy());
16460     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16461     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16462     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16463                                 DAG.getRegister(Vreg, SPTy));
16464     SDValue Ops1[2] = { Value, Chain };
16465     return DAG.getMergeValues(Ops1, dl);
16466   } else {
16467     SDValue Flag;
16468     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16469
16470     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16471     Flag = Chain.getValue(1);
16472     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16473
16474     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16475
16476     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16477         DAG.getSubtarget().getRegisterInfo());
16478     unsigned SPReg = RegInfo->getStackRegister();
16479     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16480     Chain = SP.getValue(1);
16481
16482     if (Align) {
16483       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16484                        DAG.getConstant(-(uint64_t)Align, VT));
16485       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16486     }
16487
16488     SDValue Ops1[2] = { SP, Chain };
16489     return DAG.getMergeValues(Ops1, dl);
16490   }
16491 }
16492
16493 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16494   MachineFunction &MF = DAG.getMachineFunction();
16495   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16496
16497   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16498   SDLoc DL(Op);
16499
16500   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
16501     // vastart just stores the address of the VarArgsFrameIndex slot into the
16502     // memory location argument.
16503     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16504                                    getPointerTy());
16505     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16506                         MachinePointerInfo(SV), false, false, 0);
16507   }
16508
16509   // __va_list_tag:
16510   //   gp_offset         (0 - 6 * 8)
16511   //   fp_offset         (48 - 48 + 8 * 16)
16512   //   overflow_arg_area (point to parameters coming in memory).
16513   //   reg_save_area
16514   SmallVector<SDValue, 8> MemOps;
16515   SDValue FIN = Op.getOperand(1);
16516   // Store gp_offset
16517   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16518                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16519                                                MVT::i32),
16520                                FIN, MachinePointerInfo(SV), false, false, 0);
16521   MemOps.push_back(Store);
16522
16523   // Store fp_offset
16524   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16525                     FIN, DAG.getIntPtrConstant(4));
16526   Store = DAG.getStore(Op.getOperand(0), DL,
16527                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
16528                                        MVT::i32),
16529                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
16530   MemOps.push_back(Store);
16531
16532   // Store ptr to overflow_arg_area
16533   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16534                     FIN, DAG.getIntPtrConstant(4));
16535   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
16536                                     getPointerTy());
16537   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16538                        MachinePointerInfo(SV, 8),
16539                        false, false, 0);
16540   MemOps.push_back(Store);
16541
16542   // Store ptr to reg_save_area.
16543   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
16544                     FIN, DAG.getIntPtrConstant(8));
16545   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
16546                                     getPointerTy());
16547   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
16548                        MachinePointerInfo(SV, 16), false, false, 0);
16549   MemOps.push_back(Store);
16550   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16551 }
16552
16553 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16554   assert(Subtarget->is64Bit() &&
16555          "LowerVAARG only handles 64-bit va_arg!");
16556   assert((Subtarget->isTargetLinux() ||
16557           Subtarget->isTargetDarwin()) &&
16558           "Unhandled target in LowerVAARG");
16559   assert(Op.getNode()->getNumOperands() == 4);
16560   SDValue Chain = Op.getOperand(0);
16561   SDValue SrcPtr = Op.getOperand(1);
16562   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16563   unsigned Align = Op.getConstantOperandVal(3);
16564   SDLoc dl(Op);
16565
16566   EVT ArgVT = Op.getNode()->getValueType(0);
16567   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16568   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
16569   uint8_t ArgMode;
16570
16571   // Decide which area this value should be read from.
16572   // TODO: Implement the AMD64 ABI in its entirety. This simple
16573   // selection mechanism works only for the basic types.
16574   if (ArgVT == MVT::f80) {
16575     llvm_unreachable("va_arg for f80 not yet implemented");
16576   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16577     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
16578   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16579     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
16580   } else {
16581     llvm_unreachable("Unhandled argument type in LowerVAARG");
16582   }
16583
16584   if (ArgMode == 2) {
16585     // Sanity Check: Make sure using fp_offset makes sense.
16586     assert(!DAG.getTarget().Options.UseSoftFloat &&
16587            !(DAG.getMachineFunction()
16588                 .getFunction()->getAttributes()
16589                 .hasAttribute(AttributeSet::FunctionIndex,
16590                               Attribute::NoImplicitFloat)) &&
16591            Subtarget->hasSSE1());
16592   }
16593
16594   // Insert VAARG_64 node into the DAG
16595   // VAARG_64 returns two values: Variable Argument Address, Chain
16596   SmallVector<SDValue, 11> InstOps;
16597   InstOps.push_back(Chain);
16598   InstOps.push_back(SrcPtr);
16599   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
16600   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
16601   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
16602   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
16603   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16604                                           VTs, InstOps, MVT::i64,
16605                                           MachinePointerInfo(SV),
16606                                           /*Align=*/0,
16607                                           /*Volatile=*/false,
16608                                           /*ReadMem=*/true,
16609                                           /*WriteMem=*/true);
16610   Chain = VAARG.getValue(1);
16611
16612   // Load the next argument and return it
16613   return DAG.getLoad(ArgVT, dl,
16614                      Chain,
16615                      VAARG,
16616                      MachinePointerInfo(),
16617                      false, false, false, 0);
16618 }
16619
16620 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16621                            SelectionDAG &DAG) {
16622   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
16623   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16624   SDValue Chain = Op.getOperand(0);
16625   SDValue DstPtr = Op.getOperand(1);
16626   SDValue SrcPtr = Op.getOperand(2);
16627   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16628   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16629   SDLoc DL(Op);
16630
16631   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16632                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
16633                        false,
16634                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16635 }
16636
16637 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16638 // amount is a constant. Takes immediate version of shift as input.
16639 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16640                                           SDValue SrcOp, uint64_t ShiftAmt,
16641                                           SelectionDAG &DAG) {
16642   MVT ElementType = VT.getVectorElementType();
16643
16644   // Fold this packed shift into its first operand if ShiftAmt is 0.
16645   if (ShiftAmt == 0)
16646     return SrcOp;
16647
16648   // Check for ShiftAmt >= element width
16649   if (ShiftAmt >= ElementType.getSizeInBits()) {
16650     if (Opc == X86ISD::VSRAI)
16651       ShiftAmt = ElementType.getSizeInBits() - 1;
16652     else
16653       return DAG.getConstant(0, VT);
16654   }
16655
16656   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16657          && "Unknown target vector shift-by-constant node");
16658
16659   // Fold this packed vector shift into a build vector if SrcOp is a
16660   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16661   if (VT == SrcOp.getSimpleValueType() &&
16662       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16663     SmallVector<SDValue, 8> Elts;
16664     unsigned NumElts = SrcOp->getNumOperands();
16665     ConstantSDNode *ND;
16666
16667     switch(Opc) {
16668     default: llvm_unreachable(nullptr);
16669     case X86ISD::VSHLI:
16670       for (unsigned i=0; i!=NumElts; ++i) {
16671         SDValue CurrentOp = SrcOp->getOperand(i);
16672         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16673           Elts.push_back(CurrentOp);
16674           continue;
16675         }
16676         ND = cast<ConstantSDNode>(CurrentOp);
16677         const APInt &C = ND->getAPIntValue();
16678         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
16679       }
16680       break;
16681     case X86ISD::VSRLI:
16682       for (unsigned i=0; i!=NumElts; ++i) {
16683         SDValue CurrentOp = SrcOp->getOperand(i);
16684         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16685           Elts.push_back(CurrentOp);
16686           continue;
16687         }
16688         ND = cast<ConstantSDNode>(CurrentOp);
16689         const APInt &C = ND->getAPIntValue();
16690         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
16691       }
16692       break;
16693     case X86ISD::VSRAI:
16694       for (unsigned i=0; i!=NumElts; ++i) {
16695         SDValue CurrentOp = SrcOp->getOperand(i);
16696         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16697           Elts.push_back(CurrentOp);
16698           continue;
16699         }
16700         ND = cast<ConstantSDNode>(CurrentOp);
16701         const APInt &C = ND->getAPIntValue();
16702         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
16703       }
16704       break;
16705     }
16706
16707     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16708   }
16709
16710   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
16711 }
16712
16713 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16714 // may or may not be a constant. Takes immediate version of shift as input.
16715 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16716                                    SDValue SrcOp, SDValue ShAmt,
16717                                    SelectionDAG &DAG) {
16718   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
16719
16720   // Catch shift-by-constant.
16721   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16722     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16723                                       CShAmt->getZExtValue(), DAG);
16724
16725   // Change opcode to non-immediate version
16726   switch (Opc) {
16727     default: llvm_unreachable("Unknown target vector shift node");
16728     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16729     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16730     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16731   }
16732
16733   // Need to build a vector containing shift amount
16734   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
16735   SDValue ShOps[4];
16736   ShOps[0] = ShAmt;
16737   ShOps[1] = DAG.getConstant(0, MVT::i32);
16738   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
16739   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
16740
16741   // The return type has to be a 128-bit type with the same element
16742   // type as the input type.
16743   MVT EltVT = VT.getVectorElementType();
16744   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16745
16746   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
16747   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16748 }
16749
16750 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16751 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16752 /// necessary casting for \p Mask when lowering masking intrinsics.
16753 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16754                                     SDValue PreservedSrc,
16755                                     const X86Subtarget *Subtarget,
16756                                     SelectionDAG &DAG) {
16757     EVT VT = Op.getValueType();
16758     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16759                                   MVT::i1, VT.getVectorNumElements());
16760     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16761                                      Mask.getValueType().getSizeInBits());
16762     SDLoc dl(Op);
16763
16764     assert(MaskVT.isSimple() && "invalid mask type");
16765
16766     if (isAllOnes(Mask))
16767       return Op;
16768
16769     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16770     // are extracted by EXTRACT_SUBVECTOR.
16771     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16772                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
16773                               DAG.getIntPtrConstant(0));
16774
16775     switch (Op.getOpcode()) {
16776       default: break;
16777       case X86ISD::PCMPEQM:
16778       case X86ISD::PCMPGTM:
16779       case X86ISD::CMPM:
16780       case X86ISD::CMPMU:
16781         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16782     }
16783     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16784       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16785     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
16786 }
16787
16788 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16789                                     SDValue PreservedSrc,
16790                                     const X86Subtarget *Subtarget,
16791                                     SelectionDAG &DAG) {
16792     if (isAllOnes(Mask))
16793       return Op;
16794
16795     EVT VT = Op.getValueType();
16796     SDLoc dl(Op);
16797     // The mask should be of type MVT::i1
16798     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16799
16800     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16801       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16802     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16803 }
16804
16805 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
16806     switch (IntNo) {
16807     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16808     case Intrinsic::x86_fma_vfmadd_ps:
16809     case Intrinsic::x86_fma_vfmadd_pd:
16810     case Intrinsic::x86_fma_vfmadd_ps_256:
16811     case Intrinsic::x86_fma_vfmadd_pd_256:
16812     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
16813     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
16814       return X86ISD::FMADD;
16815     case Intrinsic::x86_fma_vfmsub_ps:
16816     case Intrinsic::x86_fma_vfmsub_pd:
16817     case Intrinsic::x86_fma_vfmsub_ps_256:
16818     case Intrinsic::x86_fma_vfmsub_pd_256:
16819     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
16820     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
16821       return X86ISD::FMSUB;
16822     case Intrinsic::x86_fma_vfnmadd_ps:
16823     case Intrinsic::x86_fma_vfnmadd_pd:
16824     case Intrinsic::x86_fma_vfnmadd_ps_256:
16825     case Intrinsic::x86_fma_vfnmadd_pd_256:
16826     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
16827     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
16828       return X86ISD::FNMADD;
16829     case Intrinsic::x86_fma_vfnmsub_ps:
16830     case Intrinsic::x86_fma_vfnmsub_pd:
16831     case Intrinsic::x86_fma_vfnmsub_ps_256:
16832     case Intrinsic::x86_fma_vfnmsub_pd_256:
16833     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
16834     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
16835       return X86ISD::FNMSUB;
16836     case Intrinsic::x86_fma_vfmaddsub_ps:
16837     case Intrinsic::x86_fma_vfmaddsub_pd:
16838     case Intrinsic::x86_fma_vfmaddsub_ps_256:
16839     case Intrinsic::x86_fma_vfmaddsub_pd_256:
16840     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
16841     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
16842       return X86ISD::FMADDSUB;
16843     case Intrinsic::x86_fma_vfmsubadd_ps:
16844     case Intrinsic::x86_fma_vfmsubadd_pd:
16845     case Intrinsic::x86_fma_vfmsubadd_ps_256:
16846     case Intrinsic::x86_fma_vfmsubadd_pd_256:
16847     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
16848     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
16849       return X86ISD::FMSUBADD;
16850     }
16851 }
16852
16853 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16854                                        SelectionDAG &DAG) {
16855   SDLoc dl(Op);
16856   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16857   EVT VT = Op.getValueType();
16858   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16859   if (IntrData) {
16860     switch(IntrData->Type) {
16861     case INTR_TYPE_1OP:
16862       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16863     case INTR_TYPE_2OP:
16864       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16865         Op.getOperand(2));
16866     case INTR_TYPE_3OP:
16867       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16868         Op.getOperand(2), Op.getOperand(3));
16869     case INTR_TYPE_1OP_MASK_RM: {
16870       SDValue Src = Op.getOperand(1);
16871       SDValue Src0 = Op.getOperand(2);
16872       SDValue Mask = Op.getOperand(3);
16873       SDValue RoundingMode = Op.getOperand(4);
16874       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16875                                               RoundingMode),
16876                                   Mask, Src0, Subtarget, DAG);
16877     }
16878     case INTR_TYPE_SCALAR_MASK_RM: {
16879       SDValue Src1 = Op.getOperand(1);
16880       SDValue Src2 = Op.getOperand(2);
16881       SDValue Src0 = Op.getOperand(3);
16882       SDValue Mask = Op.getOperand(4);
16883       SDValue RoundingMode = Op.getOperand(5);
16884       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16885                                               RoundingMode),
16886                                   Mask, Src0, Subtarget, DAG);
16887     }                                              
16888     case INTR_TYPE_2OP_MASK: {
16889       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Op.getOperand(1),
16890                                               Op.getOperand(2)),
16891                                   Op.getOperand(4), Op.getOperand(3), Subtarget, DAG);
16892     }                                             
16893     case CMP_MASK:
16894     case CMP_MASK_CC: {
16895       // Comparison intrinsics with masks.
16896       // Example of transformation:
16897       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16898       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16899       // (i8 (bitcast
16900       //   (v8i1 (insert_subvector undef,
16901       //           (v2i1 (and (PCMPEQM %a, %b),
16902       //                      (extract_subvector
16903       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16904       EVT VT = Op.getOperand(1).getValueType();
16905       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16906                                     VT.getVectorNumElements());
16907       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16908       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16909                                        Mask.getValueType().getSizeInBits());
16910       SDValue Cmp;
16911       if (IntrData->Type == CMP_MASK_CC) {
16912         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16913                     Op.getOperand(2), Op.getOperand(3));
16914       } else {
16915         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16916         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16917                     Op.getOperand(2));
16918       }
16919       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16920                                              DAG.getTargetConstant(0, MaskVT),
16921                                              Subtarget, DAG);
16922       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16923                                 DAG.getUNDEF(BitcastVT), CmpMask,
16924                                 DAG.getIntPtrConstant(0));
16925       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
16926     }
16927     case COMI: { // Comparison intrinsics
16928       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16929       SDValue LHS = Op.getOperand(1);
16930       SDValue RHS = Op.getOperand(2);
16931       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
16932       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16933       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16934       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16935                                   DAG.getConstant(X86CC, MVT::i8), Cond);
16936       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16937     }
16938     case VSHIFT:
16939       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16940                                  Op.getOperand(1), Op.getOperand(2), DAG);
16941     case VSHIFT_MASK:
16942       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16943                                                       Op.getOperand(1), Op.getOperand(2), DAG),
16944                                   Op.getOperand(4), Op.getOperand(3), Subtarget, DAG);
16945     default:
16946       break;
16947     }
16948   }
16949
16950   switch (IntNo) {
16951   default: return SDValue();    // Don't custom lower most intrinsics.
16952
16953   // Arithmetic intrinsics.
16954   case Intrinsic::x86_sse2_pmulu_dq:
16955   case Intrinsic::x86_avx2_pmulu_dq:
16956     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
16957                        Op.getOperand(1), Op.getOperand(2));
16958
16959   case Intrinsic::x86_sse41_pmuldq:
16960   case Intrinsic::x86_avx2_pmul_dq:
16961     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
16962                        Op.getOperand(1), Op.getOperand(2));
16963
16964   case Intrinsic::x86_sse2_pmulhu_w:
16965   case Intrinsic::x86_avx2_pmulhu_w:
16966     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
16967                        Op.getOperand(1), Op.getOperand(2));
16968
16969   case Intrinsic::x86_sse2_pmulh_w:
16970   case Intrinsic::x86_avx2_pmulh_w:
16971     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
16972                        Op.getOperand(1), Op.getOperand(2));
16973
16974   // SSE/SSE2/AVX floating point max/min intrinsics.
16975   case Intrinsic::x86_sse_max_ps:
16976   case Intrinsic::x86_sse2_max_pd:
16977   case Intrinsic::x86_avx_max_ps_256:
16978   case Intrinsic::x86_avx_max_pd_256:
16979   case Intrinsic::x86_sse_min_ps:
16980   case Intrinsic::x86_sse2_min_pd:
16981   case Intrinsic::x86_avx_min_ps_256:
16982   case Intrinsic::x86_avx_min_pd_256: {
16983     unsigned Opcode;
16984     switch (IntNo) {
16985     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16986     case Intrinsic::x86_sse_max_ps:
16987     case Intrinsic::x86_sse2_max_pd:
16988     case Intrinsic::x86_avx_max_ps_256:
16989     case Intrinsic::x86_avx_max_pd_256:
16990       Opcode = X86ISD::FMAX;
16991       break;
16992     case Intrinsic::x86_sse_min_ps:
16993     case Intrinsic::x86_sse2_min_pd:
16994     case Intrinsic::x86_avx_min_ps_256:
16995     case Intrinsic::x86_avx_min_pd_256:
16996       Opcode = X86ISD::FMIN;
16997       break;
16998     }
16999     return DAG.getNode(Opcode, dl, Op.getValueType(),
17000                        Op.getOperand(1), Op.getOperand(2));
17001   }
17002
17003   // AVX2 variable shift intrinsics
17004   case Intrinsic::x86_avx2_psllv_d:
17005   case Intrinsic::x86_avx2_psllv_q:
17006   case Intrinsic::x86_avx2_psllv_d_256:
17007   case Intrinsic::x86_avx2_psllv_q_256:
17008   case Intrinsic::x86_avx2_psrlv_d:
17009   case Intrinsic::x86_avx2_psrlv_q:
17010   case Intrinsic::x86_avx2_psrlv_d_256:
17011   case Intrinsic::x86_avx2_psrlv_q_256:
17012   case Intrinsic::x86_avx2_psrav_d:
17013   case Intrinsic::x86_avx2_psrav_d_256: {
17014     unsigned Opcode;
17015     switch (IntNo) {
17016     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17017     case Intrinsic::x86_avx2_psllv_d:
17018     case Intrinsic::x86_avx2_psllv_q:
17019     case Intrinsic::x86_avx2_psllv_d_256:
17020     case Intrinsic::x86_avx2_psllv_q_256:
17021       Opcode = ISD::SHL;
17022       break;
17023     case Intrinsic::x86_avx2_psrlv_d:
17024     case Intrinsic::x86_avx2_psrlv_q:
17025     case Intrinsic::x86_avx2_psrlv_d_256:
17026     case Intrinsic::x86_avx2_psrlv_q_256:
17027       Opcode = ISD::SRL;
17028       break;
17029     case Intrinsic::x86_avx2_psrav_d:
17030     case Intrinsic::x86_avx2_psrav_d_256:
17031       Opcode = ISD::SRA;
17032       break;
17033     }
17034     return DAG.getNode(Opcode, dl, Op.getValueType(),
17035                        Op.getOperand(1), Op.getOperand(2));
17036   }
17037
17038   case Intrinsic::x86_sse2_packssdw_128:
17039   case Intrinsic::x86_sse2_packsswb_128:
17040   case Intrinsic::x86_avx2_packssdw:
17041   case Intrinsic::x86_avx2_packsswb:
17042     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
17043                        Op.getOperand(1), Op.getOperand(2));
17044
17045   case Intrinsic::x86_sse2_packuswb_128:
17046   case Intrinsic::x86_sse41_packusdw:
17047   case Intrinsic::x86_avx2_packuswb:
17048   case Intrinsic::x86_avx2_packusdw:
17049     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
17050                        Op.getOperand(1), Op.getOperand(2));
17051
17052   case Intrinsic::x86_ssse3_pshuf_b_128:
17053   case Intrinsic::x86_avx2_pshuf_b:
17054     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
17055                        Op.getOperand(1), Op.getOperand(2));
17056
17057   case Intrinsic::x86_sse2_pshuf_d:
17058     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
17059                        Op.getOperand(1), Op.getOperand(2));
17060
17061   case Intrinsic::x86_sse2_pshufl_w:
17062     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
17063                        Op.getOperand(1), Op.getOperand(2));
17064
17065   case Intrinsic::x86_sse2_pshufh_w:
17066     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
17067                        Op.getOperand(1), Op.getOperand(2));
17068
17069   case Intrinsic::x86_ssse3_psign_b_128:
17070   case Intrinsic::x86_ssse3_psign_w_128:
17071   case Intrinsic::x86_ssse3_psign_d_128:
17072   case Intrinsic::x86_avx2_psign_b:
17073   case Intrinsic::x86_avx2_psign_w:
17074   case Intrinsic::x86_avx2_psign_d:
17075     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
17076                        Op.getOperand(1), Op.getOperand(2));
17077
17078   case Intrinsic::x86_avx2_permd:
17079   case Intrinsic::x86_avx2_permps:
17080     // Operands intentionally swapped. Mask is last operand to intrinsic,
17081     // but second operand for node/instruction.
17082     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
17083                        Op.getOperand(2), Op.getOperand(1));
17084
17085   case Intrinsic::x86_avx512_mask_valign_q_512:
17086   case Intrinsic::x86_avx512_mask_valign_d_512:
17087     // Vector source operands are swapped.
17088     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
17089                                             Op.getValueType(), Op.getOperand(2),
17090                                             Op.getOperand(1),
17091                                             Op.getOperand(3)),
17092                                 Op.getOperand(5), Op.getOperand(4),
17093                                 Subtarget, DAG);
17094
17095   // ptest and testp intrinsics. The intrinsic these come from are designed to
17096   // return an integer value, not just an instruction so lower it to the ptest
17097   // or testp pattern and a setcc for the result.
17098   case Intrinsic::x86_sse41_ptestz:
17099   case Intrinsic::x86_sse41_ptestc:
17100   case Intrinsic::x86_sse41_ptestnzc:
17101   case Intrinsic::x86_avx_ptestz_256:
17102   case Intrinsic::x86_avx_ptestc_256:
17103   case Intrinsic::x86_avx_ptestnzc_256:
17104   case Intrinsic::x86_avx_vtestz_ps:
17105   case Intrinsic::x86_avx_vtestc_ps:
17106   case Intrinsic::x86_avx_vtestnzc_ps:
17107   case Intrinsic::x86_avx_vtestz_pd:
17108   case Intrinsic::x86_avx_vtestc_pd:
17109   case Intrinsic::x86_avx_vtestnzc_pd:
17110   case Intrinsic::x86_avx_vtestz_ps_256:
17111   case Intrinsic::x86_avx_vtestc_ps_256:
17112   case Intrinsic::x86_avx_vtestnzc_ps_256:
17113   case Intrinsic::x86_avx_vtestz_pd_256:
17114   case Intrinsic::x86_avx_vtestc_pd_256:
17115   case Intrinsic::x86_avx_vtestnzc_pd_256: {
17116     bool IsTestPacked = false;
17117     unsigned X86CC;
17118     switch (IntNo) {
17119     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17120     case Intrinsic::x86_avx_vtestz_ps:
17121     case Intrinsic::x86_avx_vtestz_pd:
17122     case Intrinsic::x86_avx_vtestz_ps_256:
17123     case Intrinsic::x86_avx_vtestz_pd_256:
17124       IsTestPacked = true; // Fallthrough
17125     case Intrinsic::x86_sse41_ptestz:
17126     case Intrinsic::x86_avx_ptestz_256:
17127       // ZF = 1
17128       X86CC = X86::COND_E;
17129       break;
17130     case Intrinsic::x86_avx_vtestc_ps:
17131     case Intrinsic::x86_avx_vtestc_pd:
17132     case Intrinsic::x86_avx_vtestc_ps_256:
17133     case Intrinsic::x86_avx_vtestc_pd_256:
17134       IsTestPacked = true; // Fallthrough
17135     case Intrinsic::x86_sse41_ptestc:
17136     case Intrinsic::x86_avx_ptestc_256:
17137       // CF = 1
17138       X86CC = X86::COND_B;
17139       break;
17140     case Intrinsic::x86_avx_vtestnzc_ps:
17141     case Intrinsic::x86_avx_vtestnzc_pd:
17142     case Intrinsic::x86_avx_vtestnzc_ps_256:
17143     case Intrinsic::x86_avx_vtestnzc_pd_256:
17144       IsTestPacked = true; // Fallthrough
17145     case Intrinsic::x86_sse41_ptestnzc:
17146     case Intrinsic::x86_avx_ptestnzc_256:
17147       // ZF and CF = 0
17148       X86CC = X86::COND_A;
17149       break;
17150     }
17151
17152     SDValue LHS = Op.getOperand(1);
17153     SDValue RHS = Op.getOperand(2);
17154     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17155     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17156     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17157     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17158     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17159   }
17160   case Intrinsic::x86_avx512_kortestz_w:
17161   case Intrinsic::x86_avx512_kortestc_w: {
17162     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17163     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
17164     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
17165     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
17166     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17167     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17168     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17169   }
17170
17171   case Intrinsic::x86_sse42_pcmpistria128:
17172   case Intrinsic::x86_sse42_pcmpestria128:
17173   case Intrinsic::x86_sse42_pcmpistric128:
17174   case Intrinsic::x86_sse42_pcmpestric128:
17175   case Intrinsic::x86_sse42_pcmpistrio128:
17176   case Intrinsic::x86_sse42_pcmpestrio128:
17177   case Intrinsic::x86_sse42_pcmpistris128:
17178   case Intrinsic::x86_sse42_pcmpestris128:
17179   case Intrinsic::x86_sse42_pcmpistriz128:
17180   case Intrinsic::x86_sse42_pcmpestriz128: {
17181     unsigned Opcode;
17182     unsigned X86CC;
17183     switch (IntNo) {
17184     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17185     case Intrinsic::x86_sse42_pcmpistria128:
17186       Opcode = X86ISD::PCMPISTRI;
17187       X86CC = X86::COND_A;
17188       break;
17189     case Intrinsic::x86_sse42_pcmpestria128:
17190       Opcode = X86ISD::PCMPESTRI;
17191       X86CC = X86::COND_A;
17192       break;
17193     case Intrinsic::x86_sse42_pcmpistric128:
17194       Opcode = X86ISD::PCMPISTRI;
17195       X86CC = X86::COND_B;
17196       break;
17197     case Intrinsic::x86_sse42_pcmpestric128:
17198       Opcode = X86ISD::PCMPESTRI;
17199       X86CC = X86::COND_B;
17200       break;
17201     case Intrinsic::x86_sse42_pcmpistrio128:
17202       Opcode = X86ISD::PCMPISTRI;
17203       X86CC = X86::COND_O;
17204       break;
17205     case Intrinsic::x86_sse42_pcmpestrio128:
17206       Opcode = X86ISD::PCMPESTRI;
17207       X86CC = X86::COND_O;
17208       break;
17209     case Intrinsic::x86_sse42_pcmpistris128:
17210       Opcode = X86ISD::PCMPISTRI;
17211       X86CC = X86::COND_S;
17212       break;
17213     case Intrinsic::x86_sse42_pcmpestris128:
17214       Opcode = X86ISD::PCMPESTRI;
17215       X86CC = X86::COND_S;
17216       break;
17217     case Intrinsic::x86_sse42_pcmpistriz128:
17218       Opcode = X86ISD::PCMPISTRI;
17219       X86CC = X86::COND_E;
17220       break;
17221     case Intrinsic::x86_sse42_pcmpestriz128:
17222       Opcode = X86ISD::PCMPESTRI;
17223       X86CC = X86::COND_E;
17224       break;
17225     }
17226     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17227     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17228     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17229     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17230                                 DAG.getConstant(X86CC, MVT::i8),
17231                                 SDValue(PCMP.getNode(), 1));
17232     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17233   }
17234
17235   case Intrinsic::x86_sse42_pcmpistri128:
17236   case Intrinsic::x86_sse42_pcmpestri128: {
17237     unsigned Opcode;
17238     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17239       Opcode = X86ISD::PCMPISTRI;
17240     else
17241       Opcode = X86ISD::PCMPESTRI;
17242
17243     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17244     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17245     return DAG.getNode(Opcode, dl, VTs, NewOps);
17246   }
17247
17248   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
17249   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
17250   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
17251   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
17252   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
17253   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
17254   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
17255   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
17256   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
17257   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
17258   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
17259   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
17260     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
17261     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
17262       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
17263                                               dl, Op.getValueType(),
17264                                               Op.getOperand(1),
17265                                               Op.getOperand(2),
17266                                               Op.getOperand(3)),
17267                                   Op.getOperand(4), Op.getOperand(1),
17268                                   Subtarget, DAG);
17269     else
17270       return SDValue();
17271   }
17272
17273   case Intrinsic::x86_fma_vfmadd_ps:
17274   case Intrinsic::x86_fma_vfmadd_pd:
17275   case Intrinsic::x86_fma_vfmsub_ps:
17276   case Intrinsic::x86_fma_vfmsub_pd:
17277   case Intrinsic::x86_fma_vfnmadd_ps:
17278   case Intrinsic::x86_fma_vfnmadd_pd:
17279   case Intrinsic::x86_fma_vfnmsub_ps:
17280   case Intrinsic::x86_fma_vfnmsub_pd:
17281   case Intrinsic::x86_fma_vfmaddsub_ps:
17282   case Intrinsic::x86_fma_vfmaddsub_pd:
17283   case Intrinsic::x86_fma_vfmsubadd_ps:
17284   case Intrinsic::x86_fma_vfmsubadd_pd:
17285   case Intrinsic::x86_fma_vfmadd_ps_256:
17286   case Intrinsic::x86_fma_vfmadd_pd_256:
17287   case Intrinsic::x86_fma_vfmsub_ps_256:
17288   case Intrinsic::x86_fma_vfmsub_pd_256:
17289   case Intrinsic::x86_fma_vfnmadd_ps_256:
17290   case Intrinsic::x86_fma_vfnmadd_pd_256:
17291   case Intrinsic::x86_fma_vfnmsub_ps_256:
17292   case Intrinsic::x86_fma_vfnmsub_pd_256:
17293   case Intrinsic::x86_fma_vfmaddsub_ps_256:
17294   case Intrinsic::x86_fma_vfmaddsub_pd_256:
17295   case Intrinsic::x86_fma_vfmsubadd_ps_256:
17296   case Intrinsic::x86_fma_vfmsubadd_pd_256:
17297     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
17298                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
17299   }
17300 }
17301
17302 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17303                               SDValue Src, SDValue Mask, SDValue Base,
17304                               SDValue Index, SDValue ScaleOp, SDValue Chain,
17305                               const X86Subtarget * Subtarget) {
17306   SDLoc dl(Op);
17307   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17308   assert(C && "Invalid scale type");
17309   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17310   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17311                              Index.getSimpleValueType().getVectorNumElements());
17312   SDValue MaskInReg;
17313   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17314   if (MaskC)
17315     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17316   else
17317     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17318   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17319   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17320   SDValue Segment = DAG.getRegister(0, MVT::i32);
17321   if (Src.getOpcode() == ISD::UNDEF)
17322     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
17323   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17324   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17325   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17326   return DAG.getMergeValues(RetOps, dl);
17327 }
17328
17329 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17330                                SDValue Src, SDValue Mask, SDValue Base,
17331                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
17332   SDLoc dl(Op);
17333   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17334   assert(C && "Invalid scale type");
17335   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17336   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17337   SDValue Segment = DAG.getRegister(0, MVT::i32);
17338   EVT MaskVT = MVT::getVectorVT(MVT::i1,
17339                              Index.getSimpleValueType().getVectorNumElements());
17340   SDValue MaskInReg;
17341   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17342   if (MaskC)
17343     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17344   else
17345     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17346   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17347   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17348   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17349   return SDValue(Res, 1);
17350 }
17351
17352 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17353                                SDValue Mask, SDValue Base, SDValue Index,
17354                                SDValue ScaleOp, SDValue Chain) {
17355   SDLoc dl(Op);
17356   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
17357   assert(C && "Invalid scale type");
17358   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
17359   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
17360   SDValue Segment = DAG.getRegister(0, MVT::i32);
17361   EVT MaskVT =
17362     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17363   SDValue MaskInReg;
17364   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17365   if (MaskC)
17366     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
17367   else
17368     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
17369   //SDVTList VTs = DAG.getVTList(MVT::Other);
17370   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17371   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17372   return SDValue(Res, 0);
17373 }
17374
17375 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17376 // read performance monitor counters (x86_rdpmc).
17377 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17378                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17379                               SmallVectorImpl<SDValue> &Results) {
17380   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17381   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17382   SDValue LO, HI;
17383
17384   // The ECX register is used to select the index of the performance counter
17385   // to read.
17386   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17387                                    N->getOperand(2));
17388   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17389
17390   // Reads the content of a 64-bit performance counter and returns it in the
17391   // registers EDX:EAX.
17392   if (Subtarget->is64Bit()) {
17393     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17394     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17395                             LO.getValue(2));
17396   } else {
17397     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17398     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17399                             LO.getValue(2));
17400   }
17401   Chain = HI.getValue(1);
17402
17403   if (Subtarget->is64Bit()) {
17404     // The EAX register is loaded with the low-order 32 bits. The EDX register
17405     // is loaded with the supported high-order bits of the counter.
17406     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17407                               DAG.getConstant(32, MVT::i8));
17408     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17409     Results.push_back(Chain);
17410     return;
17411   }
17412
17413   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17414   SDValue Ops[] = { LO, HI };
17415   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17416   Results.push_back(Pair);
17417   Results.push_back(Chain);
17418 }
17419
17420 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17421 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17422 // also used to custom lower READCYCLECOUNTER nodes.
17423 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17424                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17425                               SmallVectorImpl<SDValue> &Results) {
17426   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17427   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17428   SDValue LO, HI;
17429
17430   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17431   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17432   // and the EAX register is loaded with the low-order 32 bits.
17433   if (Subtarget->is64Bit()) {
17434     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17435     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17436                             LO.getValue(2));
17437   } else {
17438     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17439     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17440                             LO.getValue(2));
17441   }
17442   SDValue Chain = HI.getValue(1);
17443
17444   if (Opcode == X86ISD::RDTSCP_DAG) {
17445     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17446
17447     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17448     // the ECX register. Add 'ecx' explicitly to the chain.
17449     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17450                                      HI.getValue(2));
17451     // Explicitly store the content of ECX at the location passed in input
17452     // to the 'rdtscp' intrinsic.
17453     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17454                          MachinePointerInfo(), false, false, 0);
17455   }
17456
17457   if (Subtarget->is64Bit()) {
17458     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17459     // the EAX register is loaded with the low-order 32 bits.
17460     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17461                               DAG.getConstant(32, MVT::i8));
17462     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17463     Results.push_back(Chain);
17464     return;
17465   }
17466
17467   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17468   SDValue Ops[] = { LO, HI };
17469   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17470   Results.push_back(Pair);
17471   Results.push_back(Chain);
17472 }
17473
17474 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17475                                      SelectionDAG &DAG) {
17476   SmallVector<SDValue, 2> Results;
17477   SDLoc DL(Op);
17478   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17479                           Results);
17480   return DAG.getMergeValues(Results, DL);
17481 }
17482
17483
17484 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17485                                       SelectionDAG &DAG) {
17486   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17487
17488   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17489   if (!IntrData)
17490     return SDValue();
17491
17492   SDLoc dl(Op);
17493   switch(IntrData->Type) {
17494   default:
17495     llvm_unreachable("Unknown Intrinsic Type");
17496     break;    
17497   case RDSEED:
17498   case RDRAND: {
17499     // Emit the node with the right value type.
17500     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17501     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17502
17503     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17504     // Otherwise return the value from Rand, which is always 0, casted to i32.
17505     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17506                       DAG.getConstant(1, Op->getValueType(1)),
17507                       DAG.getConstant(X86::COND_B, MVT::i32),
17508                       SDValue(Result.getNode(), 1) };
17509     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17510                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17511                                   Ops);
17512
17513     // Return { result, isValid, chain }.
17514     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17515                        SDValue(Result.getNode(), 2));
17516   }
17517   case GATHER: {
17518   //gather(v1, mask, index, base, scale);
17519     SDValue Chain = Op.getOperand(0);
17520     SDValue Src   = Op.getOperand(2);
17521     SDValue Base  = Op.getOperand(3);
17522     SDValue Index = Op.getOperand(4);
17523     SDValue Mask  = Op.getOperand(5);
17524     SDValue Scale = Op.getOperand(6);
17525     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
17526                           Subtarget);
17527   }
17528   case SCATTER: {
17529   //scatter(base, mask, index, v1, scale);
17530     SDValue Chain = Op.getOperand(0);
17531     SDValue Base  = Op.getOperand(2);
17532     SDValue Mask  = Op.getOperand(3);
17533     SDValue Index = Op.getOperand(4);
17534     SDValue Src   = Op.getOperand(5);
17535     SDValue Scale = Op.getOperand(6);
17536     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
17537   }
17538   case PREFETCH: {
17539     SDValue Hint = Op.getOperand(6);
17540     unsigned HintVal;
17541     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
17542         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
17543       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
17544     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17545     SDValue Chain = Op.getOperand(0);
17546     SDValue Mask  = Op.getOperand(2);
17547     SDValue Index = Op.getOperand(3);
17548     SDValue Base  = Op.getOperand(4);
17549     SDValue Scale = Op.getOperand(5);
17550     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17551   }
17552   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17553   case RDTSC: {
17554     SmallVector<SDValue, 2> Results;
17555     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
17556     return DAG.getMergeValues(Results, dl);
17557   }
17558   // Read Performance Monitoring Counters.
17559   case RDPMC: {
17560     SmallVector<SDValue, 2> Results;
17561     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17562     return DAG.getMergeValues(Results, dl);
17563   }
17564   // XTEST intrinsics.
17565   case XTEST: {
17566     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17567     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17568     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17569                                 DAG.getConstant(X86::COND_NE, MVT::i8),
17570                                 InTrans);
17571     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17572     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17573                        Ret, SDValue(InTrans.getNode(), 1));
17574   }
17575   // ADC/ADCX/SBB
17576   case ADX: {
17577     SmallVector<SDValue, 2> Results;
17578     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17579     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17580     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17581                                 DAG.getConstant(-1, MVT::i8));
17582     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17583                               Op.getOperand(4), GenCF.getValue(1));
17584     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17585                                  Op.getOperand(5), MachinePointerInfo(),
17586                                  false, false, 0);
17587     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17588                                 DAG.getConstant(X86::COND_B, MVT::i8),
17589                                 Res.getValue(1));
17590     Results.push_back(SetCC);
17591     Results.push_back(Store);
17592     return DAG.getMergeValues(Results, dl);
17593   }
17594   }
17595 }
17596
17597 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17598                                            SelectionDAG &DAG) const {
17599   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17600   MFI->setReturnAddressIsTaken(true);
17601
17602   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17603     return SDValue();
17604
17605   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17606   SDLoc dl(Op);
17607   EVT PtrVT = getPointerTy();
17608
17609   if (Depth > 0) {
17610     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17611     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17612         DAG.getSubtarget().getRegisterInfo());
17613     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
17614     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17615                        DAG.getNode(ISD::ADD, dl, PtrVT,
17616                                    FrameAddr, Offset),
17617                        MachinePointerInfo(), false, false, false, 0);
17618   }
17619
17620   // Just load the return address.
17621   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17622   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17623                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17624 }
17625
17626 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17627   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17628   MFI->setFrameAddressIsTaken(true);
17629
17630   EVT VT = Op.getValueType();
17631   SDLoc dl(Op);  // FIXME probably not meaningful
17632   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17633   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17634       DAG.getSubtarget().getRegisterInfo());
17635   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17636   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17637           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17638          "Invalid Frame Register!");
17639   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17640   while (Depth--)
17641     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17642                             MachinePointerInfo(),
17643                             false, false, false, 0);
17644   return FrameAddr;
17645 }
17646
17647 // FIXME? Maybe this could be a TableGen attribute on some registers and
17648 // this table could be generated automatically from RegInfo.
17649 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
17650                                               EVT VT) const {
17651   unsigned Reg = StringSwitch<unsigned>(RegName)
17652                        .Case("esp", X86::ESP)
17653                        .Case("rsp", X86::RSP)
17654                        .Default(0);
17655   if (Reg)
17656     return Reg;
17657   report_fatal_error("Invalid register name global variable");
17658 }
17659
17660 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17661                                                      SelectionDAG &DAG) const {
17662   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17663       DAG.getSubtarget().getRegisterInfo());
17664   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
17665 }
17666
17667 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17668   SDValue Chain     = Op.getOperand(0);
17669   SDValue Offset    = Op.getOperand(1);
17670   SDValue Handler   = Op.getOperand(2);
17671   SDLoc dl      (Op);
17672
17673   EVT PtrVT = getPointerTy();
17674   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
17675       DAG.getSubtarget().getRegisterInfo());
17676   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17677   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17678           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17679          "Invalid Frame Register!");
17680   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17681   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17682
17683   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17684                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
17685   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17686   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17687                        false, false, 0);
17688   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17689
17690   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17691                      DAG.getRegister(StoreAddrReg, PtrVT));
17692 }
17693
17694 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17695                                                SelectionDAG &DAG) const {
17696   SDLoc DL(Op);
17697   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17698                      DAG.getVTList(MVT::i32, MVT::Other),
17699                      Op.getOperand(0), Op.getOperand(1));
17700 }
17701
17702 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17703                                                 SelectionDAG &DAG) const {
17704   SDLoc DL(Op);
17705   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17706                      Op.getOperand(0), Op.getOperand(1));
17707 }
17708
17709 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17710   return Op.getOperand(0);
17711 }
17712
17713 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17714                                                 SelectionDAG &DAG) const {
17715   SDValue Root = Op.getOperand(0);
17716   SDValue Trmp = Op.getOperand(1); // trampoline
17717   SDValue FPtr = Op.getOperand(2); // nested function
17718   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17719   SDLoc dl (Op);
17720
17721   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17722   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
17723
17724   if (Subtarget->is64Bit()) {
17725     SDValue OutChains[6];
17726
17727     // Large code-model.
17728     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17729     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17730
17731     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17732     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17733
17734     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17735
17736     // Load the pointer to the nested function into R11.
17737     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17738     SDValue Addr = Trmp;
17739     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17740                                 Addr, MachinePointerInfo(TrmpAddr),
17741                                 false, false, 0);
17742
17743     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17744                        DAG.getConstant(2, MVT::i64));
17745     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17746                                 MachinePointerInfo(TrmpAddr, 2),
17747                                 false, false, 2);
17748
17749     // Load the 'nest' parameter value into R10.
17750     // R10 is specified in X86CallingConv.td
17751     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17752     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17753                        DAG.getConstant(10, MVT::i64));
17754     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17755                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17756                                 false, false, 0);
17757
17758     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17759                        DAG.getConstant(12, MVT::i64));
17760     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17761                                 MachinePointerInfo(TrmpAddr, 12),
17762                                 false, false, 2);
17763
17764     // Jump to the nested function.
17765     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17766     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17767                        DAG.getConstant(20, MVT::i64));
17768     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
17769                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17770                                 false, false, 0);
17771
17772     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17773     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17774                        DAG.getConstant(22, MVT::i64));
17775     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
17776                                 MachinePointerInfo(TrmpAddr, 22),
17777                                 false, false, 0);
17778
17779     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17780   } else {
17781     const Function *Func =
17782       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17783     CallingConv::ID CC = Func->getCallingConv();
17784     unsigned NestReg;
17785
17786     switch (CC) {
17787     default:
17788       llvm_unreachable("Unsupported calling convention");
17789     case CallingConv::C:
17790     case CallingConv::X86_StdCall: {
17791       // Pass 'nest' parameter in ECX.
17792       // Must be kept in sync with X86CallingConv.td
17793       NestReg = X86::ECX;
17794
17795       // Check that ECX wasn't needed by an 'inreg' parameter.
17796       FunctionType *FTy = Func->getFunctionType();
17797       const AttributeSet &Attrs = Func->getAttributes();
17798
17799       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17800         unsigned InRegCount = 0;
17801         unsigned Idx = 1;
17802
17803         for (FunctionType::param_iterator I = FTy->param_begin(),
17804              E = FTy->param_end(); I != E; ++I, ++Idx)
17805           if (Attrs.hasAttribute(Idx, Attribute::InReg))
17806             // FIXME: should only count parameters that are lowered to integers.
17807             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
17808
17809         if (InRegCount > 2) {
17810           report_fatal_error("Nest register in use - reduce number of inreg"
17811                              " parameters!");
17812         }
17813       }
17814       break;
17815     }
17816     case CallingConv::X86_FastCall:
17817     case CallingConv::X86_ThisCall:
17818     case CallingConv::Fast:
17819       // Pass 'nest' parameter in EAX.
17820       // Must be kept in sync with X86CallingConv.td
17821       NestReg = X86::EAX;
17822       break;
17823     }
17824
17825     SDValue OutChains[4];
17826     SDValue Addr, Disp;
17827
17828     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17829                        DAG.getConstant(10, MVT::i32));
17830     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17831
17832     // This is storing the opcode for MOV32ri.
17833     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17834     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17835     OutChains[0] = DAG.getStore(Root, dl,
17836                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
17837                                 Trmp, MachinePointerInfo(TrmpAddr),
17838                                 false, false, 0);
17839
17840     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17841                        DAG.getConstant(1, MVT::i32));
17842     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17843                                 MachinePointerInfo(TrmpAddr, 1),
17844                                 false, false, 1);
17845
17846     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17847     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17848                        DAG.getConstant(5, MVT::i32));
17849     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
17850                                 MachinePointerInfo(TrmpAddr, 5),
17851                                 false, false, 1);
17852
17853     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17854                        DAG.getConstant(6, MVT::i32));
17855     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17856                                 MachinePointerInfo(TrmpAddr, 6),
17857                                 false, false, 1);
17858
17859     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17860   }
17861 }
17862
17863 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17864                                             SelectionDAG &DAG) const {
17865   /*
17866    The rounding mode is in bits 11:10 of FPSR, and has the following
17867    settings:
17868      00 Round to nearest
17869      01 Round to -inf
17870      10 Round to +inf
17871      11 Round to 0
17872
17873   FLT_ROUNDS, on the other hand, expects the following:
17874     -1 Undefined
17875      0 Round to 0
17876      1 Round to nearest
17877      2 Round to +inf
17878      3 Round to -inf
17879
17880   To perform the conversion, we do:
17881     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17882   */
17883
17884   MachineFunction &MF = DAG.getMachineFunction();
17885   const TargetMachine &TM = MF.getTarget();
17886   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
17887   unsigned StackAlignment = TFI.getStackAlignment();
17888   MVT VT = Op.getSimpleValueType();
17889   SDLoc DL(Op);
17890
17891   // Save FP Control Word to stack slot
17892   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17893   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
17894
17895   MachineMemOperand *MMO =
17896    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
17897                            MachineMemOperand::MOStore, 2, 2);
17898
17899   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17900   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17901                                           DAG.getVTList(MVT::Other),
17902                                           Ops, MVT::i16, MMO);
17903
17904   // Load FP Control Word from stack slot
17905   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17906                             MachinePointerInfo(), false, false, false, 0);
17907
17908   // Transform as necessary
17909   SDValue CWD1 =
17910     DAG.getNode(ISD::SRL, DL, MVT::i16,
17911                 DAG.getNode(ISD::AND, DL, MVT::i16,
17912                             CWD, DAG.getConstant(0x800, MVT::i16)),
17913                 DAG.getConstant(11, MVT::i8));
17914   SDValue CWD2 =
17915     DAG.getNode(ISD::SRL, DL, MVT::i16,
17916                 DAG.getNode(ISD::AND, DL, MVT::i16,
17917                             CWD, DAG.getConstant(0x400, MVT::i16)),
17918                 DAG.getConstant(9, MVT::i8));
17919
17920   SDValue RetVal =
17921     DAG.getNode(ISD::AND, DL, MVT::i16,
17922                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17923                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17924                             DAG.getConstant(1, MVT::i16)),
17925                 DAG.getConstant(3, MVT::i16));
17926
17927   return DAG.getNode((VT.getSizeInBits() < 16 ?
17928                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17929 }
17930
17931 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17932   MVT VT = Op.getSimpleValueType();
17933   EVT OpVT = VT;
17934   unsigned NumBits = VT.getSizeInBits();
17935   SDLoc dl(Op);
17936
17937   Op = Op.getOperand(0);
17938   if (VT == MVT::i8) {
17939     // Zero extend to i32 since there is not an i8 bsr.
17940     OpVT = MVT::i32;
17941     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17942   }
17943
17944   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17945   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17946   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17947
17948   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17949   SDValue Ops[] = {
17950     Op,
17951     DAG.getConstant(NumBits+NumBits-1, OpVT),
17952     DAG.getConstant(X86::COND_E, MVT::i8),
17953     Op.getValue(1)
17954   };
17955   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17956
17957   // Finally xor with NumBits-1.
17958   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17959
17960   if (VT == MVT::i8)
17961     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17962   return Op;
17963 }
17964
17965 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17966   MVT VT = Op.getSimpleValueType();
17967   EVT OpVT = VT;
17968   unsigned NumBits = VT.getSizeInBits();
17969   SDLoc dl(Op);
17970
17971   Op = Op.getOperand(0);
17972   if (VT == MVT::i8) {
17973     // Zero extend to i32 since there is not an i8 bsr.
17974     OpVT = MVT::i32;
17975     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17976   }
17977
17978   // Issue a bsr (scan bits in reverse).
17979   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17980   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17981
17982   // And xor with NumBits-1.
17983   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
17984
17985   if (VT == MVT::i8)
17986     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17987   return Op;
17988 }
17989
17990 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17991   MVT VT = Op.getSimpleValueType();
17992   unsigned NumBits = VT.getSizeInBits();
17993   SDLoc dl(Op);
17994   Op = Op.getOperand(0);
17995
17996   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17997   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17998   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17999
18000   // If src is zero (i.e. bsf sets ZF), returns NumBits.
18001   SDValue Ops[] = {
18002     Op,
18003     DAG.getConstant(NumBits, VT),
18004     DAG.getConstant(X86::COND_E, MVT::i8),
18005     Op.getValue(1)
18006   };
18007   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18008 }
18009
18010 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18011 // ones, and then concatenate the result back.
18012 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18013   MVT VT = Op.getSimpleValueType();
18014
18015   assert(VT.is256BitVector() && VT.isInteger() &&
18016          "Unsupported value type for operation");
18017
18018   unsigned NumElems = VT.getVectorNumElements();
18019   SDLoc dl(Op);
18020
18021   // Extract the LHS vectors
18022   SDValue LHS = Op.getOperand(0);
18023   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18024   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18025
18026   // Extract the RHS vectors
18027   SDValue RHS = Op.getOperand(1);
18028   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18029   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18030
18031   MVT EltVT = VT.getVectorElementType();
18032   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18033
18034   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18035                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18036                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18037 }
18038
18039 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18040   assert(Op.getSimpleValueType().is256BitVector() &&
18041          Op.getSimpleValueType().isInteger() &&
18042          "Only handle AVX 256-bit vector integer operation");
18043   return Lower256IntArith(Op, DAG);
18044 }
18045
18046 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18047   assert(Op.getSimpleValueType().is256BitVector() &&
18048          Op.getSimpleValueType().isInteger() &&
18049          "Only handle AVX 256-bit vector integer operation");
18050   return Lower256IntArith(Op, DAG);
18051 }
18052
18053 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18054                         SelectionDAG &DAG) {
18055   SDLoc dl(Op);
18056   MVT VT = Op.getSimpleValueType();
18057
18058   // Decompose 256-bit ops into smaller 128-bit ops.
18059   if (VT.is256BitVector() && !Subtarget->hasInt256())
18060     return Lower256IntArith(Op, DAG);
18061
18062   SDValue A = Op.getOperand(0);
18063   SDValue B = Op.getOperand(1);
18064
18065   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18066   if (VT == MVT::v4i32) {
18067     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18068            "Should not custom lower when pmuldq is available!");
18069
18070     // Extract the odd parts.
18071     static const int UnpackMask[] = { 1, -1, 3, -1 };
18072     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18073     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18074
18075     // Multiply the even parts.
18076     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18077     // Now multiply odd parts.
18078     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18079
18080     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
18081     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
18082
18083     // Merge the two vectors back together with a shuffle. This expands into 2
18084     // shuffles.
18085     static const int ShufMask[] = { 0, 4, 2, 6 };
18086     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18087   }
18088
18089   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18090          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18091
18092   //  Ahi = psrlqi(a, 32);
18093   //  Bhi = psrlqi(b, 32);
18094   //
18095   //  AloBlo = pmuludq(a, b);
18096   //  AloBhi = pmuludq(a, Bhi);
18097   //  AhiBlo = pmuludq(Ahi, b);
18098
18099   //  AloBhi = psllqi(AloBhi, 32);
18100   //  AhiBlo = psllqi(AhiBlo, 32);
18101   //  return AloBlo + AloBhi + AhiBlo;
18102
18103   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18104   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18105
18106   // Bit cast to 32-bit vectors for MULUDQ
18107   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18108                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18109   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
18110   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
18111   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
18112   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
18113
18114   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18115   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18116   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18117
18118   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18119   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18120
18121   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18122   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18123 }
18124
18125 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18126   assert(Subtarget->isTargetWin64() && "Unexpected target");
18127   EVT VT = Op.getValueType();
18128   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18129          "Unexpected return type for lowering");
18130
18131   RTLIB::Libcall LC;
18132   bool isSigned;
18133   switch (Op->getOpcode()) {
18134   default: llvm_unreachable("Unexpected request for libcall!");
18135   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18136   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18137   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18138   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18139   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18140   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18141   }
18142
18143   SDLoc dl(Op);
18144   SDValue InChain = DAG.getEntryNode();
18145
18146   TargetLowering::ArgListTy Args;
18147   TargetLowering::ArgListEntry Entry;
18148   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18149     EVT ArgVT = Op->getOperand(i).getValueType();
18150     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18151            "Unexpected argument type for lowering");
18152     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18153     Entry.Node = StackPtr;
18154     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18155                            false, false, 16);
18156     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18157     Entry.Ty = PointerType::get(ArgTy,0);
18158     Entry.isSExt = false;
18159     Entry.isZExt = false;
18160     Args.push_back(Entry);
18161   }
18162
18163   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18164                                          getPointerTy());
18165
18166   TargetLowering::CallLoweringInfo CLI(DAG);
18167   CLI.setDebugLoc(dl).setChain(InChain)
18168     .setCallee(getLibcallCallingConv(LC),
18169                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18170                Callee, std::move(Args), 0)
18171     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18172
18173   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18174   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
18175 }
18176
18177 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18178                              SelectionDAG &DAG) {
18179   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18180   EVT VT = Op0.getValueType();
18181   SDLoc dl(Op);
18182
18183   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18184          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18185
18186   // PMULxD operations multiply each even value (starting at 0) of LHS with
18187   // the related value of RHS and produce a widen result.
18188   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18189   // => <2 x i64> <ae|cg>
18190   //
18191   // In other word, to have all the results, we need to perform two PMULxD:
18192   // 1. one with the even values.
18193   // 2. one with the odd values.
18194   // To achieve #2, with need to place the odd values at an even position.
18195   //
18196   // Place the odd value at an even position (basically, shift all values 1
18197   // step to the left):
18198   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18199   // <a|b|c|d> => <b|undef|d|undef>
18200   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18201   // <e|f|g|h> => <f|undef|h|undef>
18202   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18203
18204   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18205   // ints.
18206   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18207   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18208   unsigned Opcode =
18209       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18210   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18211   // => <2 x i64> <ae|cg>
18212   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
18213                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18214   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18215   // => <2 x i64> <bf|dh>
18216   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
18217                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18218
18219   // Shuffle it back into the right order.
18220   SDValue Highs, Lows;
18221   if (VT == MVT::v8i32) {
18222     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18223     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18224     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18225     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18226   } else {
18227     const int HighMask[] = {1, 5, 3, 7};
18228     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18229     const int LowMask[] = {0, 4, 2, 6};
18230     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18231   }
18232
18233   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18234   // unsigned multiply.
18235   if (IsSigned && !Subtarget->hasSSE41()) {
18236     SDValue ShAmt =
18237         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
18238     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18239                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18240     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18241                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18242
18243     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18244     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18245   }
18246
18247   // The first result of MUL_LOHI is actually the low value, followed by the
18248   // high value.
18249   SDValue Ops[] = {Lows, Highs};
18250   return DAG.getMergeValues(Ops, dl);
18251 }
18252
18253 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18254                                          const X86Subtarget *Subtarget) {
18255   MVT VT = Op.getSimpleValueType();
18256   SDLoc dl(Op);
18257   SDValue R = Op.getOperand(0);
18258   SDValue Amt = Op.getOperand(1);
18259
18260   // Optimize shl/srl/sra with constant shift amount.
18261   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18262     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18263       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18264
18265       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
18266           (Subtarget->hasInt256() &&
18267            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18268           (Subtarget->hasAVX512() &&
18269            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18270         if (Op.getOpcode() == ISD::SHL)
18271           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18272                                             DAG);
18273         if (Op.getOpcode() == ISD::SRL)
18274           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18275                                             DAG);
18276         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
18277           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18278                                             DAG);
18279       }
18280
18281       if (VT == MVT::v16i8) {
18282         if (Op.getOpcode() == ISD::SHL) {
18283           // Make a large shift.
18284           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18285                                                    MVT::v8i16, R, ShiftAmt,
18286                                                    DAG);
18287           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18288           // Zero out the rightmost bits.
18289           SmallVector<SDValue, 16> V(16,
18290                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18291                                                      MVT::i8));
18292           return DAG.getNode(ISD::AND, dl, VT, SHL,
18293                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18294         }
18295         if (Op.getOpcode() == ISD::SRL) {
18296           // Make a large shift.
18297           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18298                                                    MVT::v8i16, R, ShiftAmt,
18299                                                    DAG);
18300           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18301           // Zero out the leftmost bits.
18302           SmallVector<SDValue, 16> V(16,
18303                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18304                                                      MVT::i8));
18305           return DAG.getNode(ISD::AND, dl, VT, SRL,
18306                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18307         }
18308         if (Op.getOpcode() == ISD::SRA) {
18309           if (ShiftAmt == 7) {
18310             // R s>> 7  ===  R s< 0
18311             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18312             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18313           }
18314
18315           // R s>> a === ((R u>> a) ^ m) - m
18316           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18317           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
18318                                                          MVT::i8));
18319           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18320           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18321           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18322           return Res;
18323         }
18324         llvm_unreachable("Unknown shift opcode.");
18325       }
18326
18327       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
18328         if (Op.getOpcode() == ISD::SHL) {
18329           // Make a large shift.
18330           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
18331                                                    MVT::v16i16, R, ShiftAmt,
18332                                                    DAG);
18333           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
18334           // Zero out the rightmost bits.
18335           SmallVector<SDValue, 32> V(32,
18336                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
18337                                                      MVT::i8));
18338           return DAG.getNode(ISD::AND, dl, VT, SHL,
18339                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18340         }
18341         if (Op.getOpcode() == ISD::SRL) {
18342           // Make a large shift.
18343           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
18344                                                    MVT::v16i16, R, ShiftAmt,
18345                                                    DAG);
18346           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
18347           // Zero out the leftmost bits.
18348           SmallVector<SDValue, 32> V(32,
18349                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
18350                                                      MVT::i8));
18351           return DAG.getNode(ISD::AND, dl, VT, SRL,
18352                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18353         }
18354         if (Op.getOpcode() == ISD::SRA) {
18355           if (ShiftAmt == 7) {
18356             // R s>> 7  ===  R s< 0
18357             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18358             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18359           }
18360
18361           // R s>> a === ((R u>> a) ^ m) - m
18362           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18363           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
18364                                                          MVT::i8));
18365           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18366           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18367           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18368           return Res;
18369         }
18370         llvm_unreachable("Unknown shift opcode.");
18371       }
18372     }
18373   }
18374
18375   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18376   if (!Subtarget->is64Bit() &&
18377       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18378       Amt.getOpcode() == ISD::BITCAST &&
18379       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18380     Amt = Amt.getOperand(0);
18381     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18382                      VT.getVectorNumElements();
18383     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18384     uint64_t ShiftAmt = 0;
18385     for (unsigned i = 0; i != Ratio; ++i) {
18386       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
18387       if (!C)
18388         return SDValue();
18389       // 6 == Log2(64)
18390       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18391     }
18392     // Check remaining shift amounts.
18393     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18394       uint64_t ShAmt = 0;
18395       for (unsigned j = 0; j != Ratio; ++j) {
18396         ConstantSDNode *C =
18397           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18398         if (!C)
18399           return SDValue();
18400         // 6 == Log2(64)
18401         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18402       }
18403       if (ShAmt != ShiftAmt)
18404         return SDValue();
18405     }
18406     switch (Op.getOpcode()) {
18407     default:
18408       llvm_unreachable("Unknown shift opcode!");
18409     case ISD::SHL:
18410       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
18411                                         DAG);
18412     case ISD::SRL:
18413       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
18414                                         DAG);
18415     case ISD::SRA:
18416       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
18417                                         DAG);
18418     }
18419   }
18420
18421   return SDValue();
18422 }
18423
18424 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18425                                         const X86Subtarget* Subtarget) {
18426   MVT VT = Op.getSimpleValueType();
18427   SDLoc dl(Op);
18428   SDValue R = Op.getOperand(0);
18429   SDValue Amt = Op.getOperand(1);
18430
18431   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
18432       VT == MVT::v4i32 || VT == MVT::v8i16 ||
18433       (Subtarget->hasInt256() &&
18434        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
18435         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
18436        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
18437     SDValue BaseShAmt;
18438     EVT EltVT = VT.getVectorElementType();
18439
18440     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18441       unsigned NumElts = VT.getVectorNumElements();
18442       unsigned i, j;
18443       for (i = 0; i != NumElts; ++i) {
18444         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
18445           continue;
18446         break;
18447       }
18448       for (j = i; j != NumElts; ++j) {
18449         SDValue Arg = Amt.getOperand(j);
18450         if (Arg.getOpcode() == ISD::UNDEF) continue;
18451         if (Arg != Amt.getOperand(i))
18452           break;
18453       }
18454       if (i != NumElts && j == NumElts)
18455         BaseShAmt = Amt.getOperand(i);
18456     } else {
18457       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18458         Amt = Amt.getOperand(0);
18459       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
18460                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
18461         SDValue InVec = Amt.getOperand(0);
18462         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18463           unsigned NumElts = InVec.getValueType().getVectorNumElements();
18464           unsigned i = 0;
18465           for (; i != NumElts; ++i) {
18466             SDValue Arg = InVec.getOperand(i);
18467             if (Arg.getOpcode() == ISD::UNDEF) continue;
18468             BaseShAmt = Arg;
18469             break;
18470           }
18471         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18472            if (ConstantSDNode *C =
18473                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18474              unsigned SplatIdx =
18475                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
18476              if (C->getZExtValue() == SplatIdx)
18477                BaseShAmt = InVec.getOperand(1);
18478            }
18479         }
18480         if (!BaseShAmt.getNode())
18481           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
18482                                   DAG.getIntPtrConstant(0));
18483       }
18484     }
18485
18486     if (BaseShAmt.getNode()) {
18487       if (EltVT.bitsGT(MVT::i32))
18488         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
18489       else if (EltVT.bitsLT(MVT::i32))
18490         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18491
18492       switch (Op.getOpcode()) {
18493       default:
18494         llvm_unreachable("Unknown shift opcode!");
18495       case ISD::SHL:
18496         switch (VT.SimpleTy) {
18497         default: return SDValue();
18498         case MVT::v2i64:
18499         case MVT::v4i32:
18500         case MVT::v8i16:
18501         case MVT::v4i64:
18502         case MVT::v8i32:
18503         case MVT::v16i16:
18504         case MVT::v16i32:
18505         case MVT::v8i64:
18506           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
18507         }
18508       case ISD::SRA:
18509         switch (VT.SimpleTy) {
18510         default: return SDValue();
18511         case MVT::v4i32:
18512         case MVT::v8i16:
18513         case MVT::v8i32:
18514         case MVT::v16i16:
18515         case MVT::v16i32:
18516         case MVT::v8i64:
18517           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
18518         }
18519       case ISD::SRL:
18520         switch (VT.SimpleTy) {
18521         default: return SDValue();
18522         case MVT::v2i64:
18523         case MVT::v4i32:
18524         case MVT::v8i16:
18525         case MVT::v4i64:
18526         case MVT::v8i32:
18527         case MVT::v16i16:
18528         case MVT::v16i32:
18529         case MVT::v8i64:
18530           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
18531         }
18532       }
18533     }
18534   }
18535
18536   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18537   if (!Subtarget->is64Bit() &&
18538       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
18539       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
18540       Amt.getOpcode() == ISD::BITCAST &&
18541       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18542     Amt = Amt.getOperand(0);
18543     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18544                      VT.getVectorNumElements();
18545     std::vector<SDValue> Vals(Ratio);
18546     for (unsigned i = 0; i != Ratio; ++i)
18547       Vals[i] = Amt.getOperand(i);
18548     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18549       for (unsigned j = 0; j != Ratio; ++j)
18550         if (Vals[j] != Amt.getOperand(i + j))
18551           return SDValue();
18552     }
18553     switch (Op.getOpcode()) {
18554     default:
18555       llvm_unreachable("Unknown shift opcode!");
18556     case ISD::SHL:
18557       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
18558     case ISD::SRL:
18559       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
18560     case ISD::SRA:
18561       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
18562     }
18563   }
18564
18565   return SDValue();
18566 }
18567
18568 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18569                           SelectionDAG &DAG) {
18570   MVT VT = Op.getSimpleValueType();
18571   SDLoc dl(Op);
18572   SDValue R = Op.getOperand(0);
18573   SDValue Amt = Op.getOperand(1);
18574   SDValue V;
18575
18576   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18577   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18578
18579   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
18580   if (V.getNode())
18581     return V;
18582
18583   V = LowerScalarVariableShift(Op, DAG, Subtarget);
18584   if (V.getNode())
18585       return V;
18586
18587   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
18588     return Op;
18589   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
18590   if (Subtarget->hasInt256()) {
18591     if (Op.getOpcode() == ISD::SRL &&
18592         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18593          VT == MVT::v4i64 || VT == MVT::v8i32))
18594       return Op;
18595     if (Op.getOpcode() == ISD::SHL &&
18596         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18597          VT == MVT::v4i64 || VT == MVT::v8i32))
18598       return Op;
18599     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
18600       return Op;
18601   }
18602
18603   // If possible, lower this packed shift into a vector multiply instead of
18604   // expanding it into a sequence of scalar shifts.
18605   // Do this only if the vector shift count is a constant build_vector.
18606   if (Op.getOpcode() == ISD::SHL && 
18607       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18608        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18609       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18610     SmallVector<SDValue, 8> Elts;
18611     EVT SVT = VT.getScalarType();
18612     unsigned SVTBits = SVT.getSizeInBits();
18613     const APInt &One = APInt(SVTBits, 1);
18614     unsigned NumElems = VT.getVectorNumElements();
18615
18616     for (unsigned i=0; i !=NumElems; ++i) {
18617       SDValue Op = Amt->getOperand(i);
18618       if (Op->getOpcode() == ISD::UNDEF) {
18619         Elts.push_back(Op);
18620         continue;
18621       }
18622
18623       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18624       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18625       uint64_t ShAmt = C.getZExtValue();
18626       if (ShAmt >= SVTBits) {
18627         Elts.push_back(DAG.getUNDEF(SVT));
18628         continue;
18629       }
18630       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
18631     }
18632     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18633     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18634   }
18635
18636   // Lower SHL with variable shift amount.
18637   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18638     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
18639
18640     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
18641     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
18642     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18643     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18644   }
18645
18646   // If possible, lower this shift as a sequence of two shifts by
18647   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18648   // Example:
18649   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18650   //
18651   // Could be rewritten as:
18652   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18653   //
18654   // The advantage is that the two shifts from the example would be
18655   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18656   // the vector shift into four scalar shifts plus four pairs of vector
18657   // insert/extract.
18658   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18659       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18660     unsigned TargetOpcode = X86ISD::MOVSS;
18661     bool CanBeSimplified;
18662     // The splat value for the first packed shift (the 'X' from the example).
18663     SDValue Amt1 = Amt->getOperand(0);
18664     // The splat value for the second packed shift (the 'Y' from the example).
18665     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18666                                         Amt->getOperand(2);
18667
18668     // See if it is possible to replace this node with a sequence of
18669     // two shifts followed by a MOVSS/MOVSD
18670     if (VT == MVT::v4i32) {
18671       // Check if it is legal to use a MOVSS.
18672       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18673                         Amt2 == Amt->getOperand(3);
18674       if (!CanBeSimplified) {
18675         // Otherwise, check if we can still simplify this node using a MOVSD.
18676         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18677                           Amt->getOperand(2) == Amt->getOperand(3);
18678         TargetOpcode = X86ISD::MOVSD;
18679         Amt2 = Amt->getOperand(2);
18680       }
18681     } else {
18682       // Do similar checks for the case where the machine value type
18683       // is MVT::v8i16.
18684       CanBeSimplified = Amt1 == Amt->getOperand(1);
18685       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18686         CanBeSimplified = Amt2 == Amt->getOperand(i);
18687
18688       if (!CanBeSimplified) {
18689         TargetOpcode = X86ISD::MOVSD;
18690         CanBeSimplified = true;
18691         Amt2 = Amt->getOperand(4);
18692         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18693           CanBeSimplified = Amt1 == Amt->getOperand(i);
18694         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18695           CanBeSimplified = Amt2 == Amt->getOperand(j);
18696       }
18697     }
18698     
18699     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18700         isa<ConstantSDNode>(Amt2)) {
18701       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18702       EVT CastVT = MVT::v4i32;
18703       SDValue Splat1 = 
18704         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
18705       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18706       SDValue Splat2 = 
18707         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
18708       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18709       if (TargetOpcode == X86ISD::MOVSD)
18710         CastVT = MVT::v2i64;
18711       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
18712       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
18713       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18714                                             BitCast1, DAG);
18715       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
18716     }
18717   }
18718
18719   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
18720     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
18721
18722     // a = a << 5;
18723     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
18724     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
18725
18726     // Turn 'a' into a mask suitable for VSELECT
18727     SDValue VSelM = DAG.getConstant(0x80, VT);
18728     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18729     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18730
18731     SDValue CM1 = DAG.getConstant(0x0f, VT);
18732     SDValue CM2 = DAG.getConstant(0x3f, VT);
18733
18734     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
18735     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
18736     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
18737     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18738     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18739
18740     // a += a
18741     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18742     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18743     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18744
18745     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
18746     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
18747     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
18748     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
18749     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
18750
18751     // a += a
18752     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
18753     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
18754     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
18755
18756     // return VSELECT(r, r+r, a);
18757     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
18758                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
18759     return R;
18760   }
18761
18762   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18763   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18764   // solution better.
18765   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18766     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
18767     unsigned ExtOpc =
18768         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18769     R = DAG.getNode(ExtOpc, dl, NewVT, R);
18770     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
18771     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18772                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
18773     }
18774
18775   // Decompose 256-bit shifts into smaller 128-bit shifts.
18776   if (VT.is256BitVector()) {
18777     unsigned NumElems = VT.getVectorNumElements();
18778     MVT EltVT = VT.getVectorElementType();
18779     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18780
18781     // Extract the two vectors
18782     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18783     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18784
18785     // Recreate the shift amount vectors
18786     SDValue Amt1, Amt2;
18787     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18788       // Constant shift amount
18789       SmallVector<SDValue, 4> Amt1Csts;
18790       SmallVector<SDValue, 4> Amt2Csts;
18791       for (unsigned i = 0; i != NumElems/2; ++i)
18792         Amt1Csts.push_back(Amt->getOperand(i));
18793       for (unsigned i = NumElems/2; i != NumElems; ++i)
18794         Amt2Csts.push_back(Amt->getOperand(i));
18795
18796       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18797       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18798     } else {
18799       // Variable shift amount
18800       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18801       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18802     }
18803
18804     // Issue new vector shifts for the smaller types
18805     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18806     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18807
18808     // Concatenate the result back
18809     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18810   }
18811
18812   return SDValue();
18813 }
18814
18815 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18816   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18817   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18818   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18819   // has only one use.
18820   SDNode *N = Op.getNode();
18821   SDValue LHS = N->getOperand(0);
18822   SDValue RHS = N->getOperand(1);
18823   unsigned BaseOp = 0;
18824   unsigned Cond = 0;
18825   SDLoc DL(Op);
18826   switch (Op.getOpcode()) {
18827   default: llvm_unreachable("Unknown ovf instruction!");
18828   case ISD::SADDO:
18829     // A subtract of one will be selected as a INC. Note that INC doesn't
18830     // set CF, so we can't do this for UADDO.
18831     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18832       if (C->isOne()) {
18833         BaseOp = X86ISD::INC;
18834         Cond = X86::COND_O;
18835         break;
18836       }
18837     BaseOp = X86ISD::ADD;
18838     Cond = X86::COND_O;
18839     break;
18840   case ISD::UADDO:
18841     BaseOp = X86ISD::ADD;
18842     Cond = X86::COND_B;
18843     break;
18844   case ISD::SSUBO:
18845     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18846     // set CF, so we can't do this for USUBO.
18847     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18848       if (C->isOne()) {
18849         BaseOp = X86ISD::DEC;
18850         Cond = X86::COND_O;
18851         break;
18852       }
18853     BaseOp = X86ISD::SUB;
18854     Cond = X86::COND_O;
18855     break;
18856   case ISD::USUBO:
18857     BaseOp = X86ISD::SUB;
18858     Cond = X86::COND_B;
18859     break;
18860   case ISD::SMULO:
18861     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18862     Cond = X86::COND_O;
18863     break;
18864   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18865     if (N->getValueType(0) == MVT::i8) {
18866       BaseOp = X86ISD::UMUL8;
18867       Cond = X86::COND_O;
18868       break;
18869     }
18870     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18871                                  MVT::i32);
18872     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18873
18874     SDValue SetCC =
18875       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18876                   DAG.getConstant(X86::COND_O, MVT::i32),
18877                   SDValue(Sum.getNode(), 2));
18878
18879     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18880   }
18881   }
18882
18883   // Also sets EFLAGS.
18884   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18885   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18886
18887   SDValue SetCC =
18888     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18889                 DAG.getConstant(Cond, MVT::i32),
18890                 SDValue(Sum.getNode(), 1));
18891
18892   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18893 }
18894
18895 // Sign extension of the low part of vector elements. This may be used either
18896 // when sign extend instructions are not available or if the vector element
18897 // sizes already match the sign-extended size. If the vector elements are in
18898 // their pre-extended size and sign extend instructions are available, that will
18899 // be handled by LowerSIGN_EXTEND.
18900 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
18901                                                   SelectionDAG &DAG) const {
18902   SDLoc dl(Op);
18903   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
18904   MVT VT = Op.getSimpleValueType();
18905
18906   if (!Subtarget->hasSSE2() || !VT.isVector())
18907     return SDValue();
18908
18909   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
18910                       ExtraVT.getScalarType().getSizeInBits();
18911
18912   switch (VT.SimpleTy) {
18913     default: return SDValue();
18914     case MVT::v8i32:
18915     case MVT::v16i16:
18916       if (!Subtarget->hasFp256())
18917         return SDValue();
18918       if (!Subtarget->hasInt256()) {
18919         // needs to be split
18920         unsigned NumElems = VT.getVectorNumElements();
18921
18922         // Extract the LHS vectors
18923         SDValue LHS = Op.getOperand(0);
18924         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18925         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18926
18927         MVT EltVT = VT.getVectorElementType();
18928         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18929
18930         EVT ExtraEltVT = ExtraVT.getVectorElementType();
18931         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
18932         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
18933                                    ExtraNumElems/2);
18934         SDValue Extra = DAG.getValueType(ExtraVT);
18935
18936         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
18937         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
18938
18939         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
18940       }
18941       // fall through
18942     case MVT::v4i32:
18943     case MVT::v8i16: {
18944       SDValue Op0 = Op.getOperand(0);
18945
18946       // This is a sign extension of some low part of vector elements without
18947       // changing the size of the vector elements themselves:
18948       // Shift-Left + Shift-Right-Algebraic.
18949       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
18950                                                BitsDiff, DAG);
18951       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
18952                                         DAG);
18953     }
18954   }
18955 }
18956
18957 /// Returns true if the operand type is exactly twice the native width, and
18958 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18959 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18960 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18961 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
18962   const X86Subtarget &Subtarget =
18963       getTargetMachine().getSubtarget<X86Subtarget>();
18964   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18965
18966   if (OpWidth == 64)
18967     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18968   else if (OpWidth == 128)
18969     return Subtarget.hasCmpxchg16b();
18970   else
18971     return false;
18972 }
18973
18974 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18975   return needsCmpXchgNb(SI->getValueOperand()->getType());
18976 }
18977
18978 // Note: this turns large loads into lock cmpxchg8b/16b.
18979 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18980 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18981   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18982   return needsCmpXchgNb(PTy->getElementType());
18983 }
18984
18985 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18986   const X86Subtarget &Subtarget =
18987       getTargetMachine().getSubtarget<X86Subtarget>();
18988   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
18989   const Type *MemType = AI->getType();
18990
18991   // If the operand is too big, we must see if cmpxchg8/16b is available
18992   // and default to library calls otherwise.
18993   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18994     return needsCmpXchgNb(MemType);
18995
18996   AtomicRMWInst::BinOp Op = AI->getOperation();
18997   switch (Op) {
18998   default:
18999     llvm_unreachable("Unknown atomic operation");
19000   case AtomicRMWInst::Xchg:
19001   case AtomicRMWInst::Add:
19002   case AtomicRMWInst::Sub:
19003     // It's better to use xadd, xsub or xchg for these in all cases.
19004     return false;
19005   case AtomicRMWInst::Or:
19006   case AtomicRMWInst::And:
19007   case AtomicRMWInst::Xor:
19008     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19009     // prefix to a normal instruction for these operations.
19010     return !AI->use_empty();
19011   case AtomicRMWInst::Nand:
19012   case AtomicRMWInst::Max:
19013   case AtomicRMWInst::Min:
19014   case AtomicRMWInst::UMax:
19015   case AtomicRMWInst::UMin:
19016     // These always require a non-trivial set of data operations on x86. We must
19017     // use a cmpxchg loop.
19018     return true;
19019   }
19020 }
19021
19022 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19023   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19024   // no-sse2). There isn't any reason to disable it if the target processor
19025   // supports it.
19026   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19027 }
19028
19029 LoadInst *
19030 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19031   const X86Subtarget &Subtarget =
19032       getTargetMachine().getSubtarget<X86Subtarget>();
19033   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
19034   const Type *MemType = AI->getType();
19035   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19036   // there is no benefit in turning such RMWs into loads, and it is actually
19037   // harmful as it introduces a mfence.
19038   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19039     return nullptr;
19040
19041   auto Builder = IRBuilder<>(AI);
19042   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19043   auto SynchScope = AI->getSynchScope();
19044   // We must restrict the ordering to avoid generating loads with Release or
19045   // ReleaseAcquire orderings.
19046   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19047   auto Ptr = AI->getPointerOperand();
19048
19049   // Before the load we need a fence. Here is an example lifted from
19050   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19051   // is required:
19052   // Thread 0:
19053   //   x.store(1, relaxed);
19054   //   r1 = y.fetch_add(0, release);
19055   // Thread 1:
19056   //   y.fetch_add(42, acquire);
19057   //   r2 = x.load(relaxed);
19058   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19059   // lowered to just a load without a fence. A mfence flushes the store buffer,
19060   // making the optimization clearly correct.
19061   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19062   // otherwise, we might be able to be more agressive on relaxed idempotent
19063   // rmw. In practice, they do not look useful, so we don't try to be
19064   // especially clever.
19065   if (SynchScope == SingleThread) {
19066     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19067     // the IR level, so we must wrap it in an intrinsic.
19068     return nullptr;
19069   } else if (hasMFENCE(Subtarget)) {
19070     Function *MFence = llvm::Intrinsic::getDeclaration(M,
19071             Intrinsic::x86_sse2_mfence);
19072     Builder.CreateCall(MFence);
19073   } else {
19074     // FIXME: it might make sense to use a locked operation here but on a
19075     // different cache-line to prevent cache-line bouncing. In practice it
19076     // is probably a small win, and x86 processors without mfence are rare
19077     // enough that we do not bother.
19078     return nullptr;
19079   }
19080
19081   // Finally we can emit the atomic load.
19082   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19083           AI->getType()->getPrimitiveSizeInBits());
19084   Loaded->setAtomic(Order, SynchScope);
19085   AI->replaceAllUsesWith(Loaded);
19086   AI->eraseFromParent();
19087   return Loaded;
19088 }
19089
19090 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19091                                  SelectionDAG &DAG) {
19092   SDLoc dl(Op);
19093   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19094     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19095   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19096     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19097
19098   // The only fence that needs an instruction is a sequentially-consistent
19099   // cross-thread fence.
19100   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19101     if (hasMFENCE(*Subtarget))
19102       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19103
19104     SDValue Chain = Op.getOperand(0);
19105     SDValue Zero = DAG.getConstant(0, MVT::i32);
19106     SDValue Ops[] = {
19107       DAG.getRegister(X86::ESP, MVT::i32), // Base
19108       DAG.getTargetConstant(1, MVT::i8),   // Scale
19109       DAG.getRegister(0, MVT::i32),        // Index
19110       DAG.getTargetConstant(0, MVT::i32),  // Disp
19111       DAG.getRegister(0, MVT::i32),        // Segment.
19112       Zero,
19113       Chain
19114     };
19115     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19116     return SDValue(Res, 0);
19117   }
19118
19119   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19120   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19121 }
19122
19123 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19124                              SelectionDAG &DAG) {
19125   MVT T = Op.getSimpleValueType();
19126   SDLoc DL(Op);
19127   unsigned Reg = 0;
19128   unsigned size = 0;
19129   switch(T.SimpleTy) {
19130   default: llvm_unreachable("Invalid value type!");
19131   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19132   case MVT::i16: Reg = X86::AX;  size = 2; break;
19133   case MVT::i32: Reg = X86::EAX; size = 4; break;
19134   case MVT::i64:
19135     assert(Subtarget->is64Bit() && "Node not type legal!");
19136     Reg = X86::RAX; size = 8;
19137     break;
19138   }
19139   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19140                                   Op.getOperand(2), SDValue());
19141   SDValue Ops[] = { cpIn.getValue(0),
19142                     Op.getOperand(1),
19143                     Op.getOperand(3),
19144                     DAG.getTargetConstant(size, MVT::i8),
19145                     cpIn.getValue(1) };
19146   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19147   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19148   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19149                                            Ops, T, MMO);
19150
19151   SDValue cpOut =
19152     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19153   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19154                                       MVT::i32, cpOut.getValue(2));
19155   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19156                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19157
19158   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19159   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19160   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19161   return SDValue();
19162 }
19163
19164 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19165                             SelectionDAG &DAG) {
19166   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19167   MVT DstVT = Op.getSimpleValueType();
19168
19169   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19170     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19171     if (DstVT != MVT::f64)
19172       // This conversion needs to be expanded.
19173       return SDValue();
19174
19175     SDValue InVec = Op->getOperand(0);
19176     SDLoc dl(Op);
19177     unsigned NumElts = SrcVT.getVectorNumElements();
19178     EVT SVT = SrcVT.getVectorElementType();
19179
19180     // Widen the vector in input in the case of MVT::v2i32.
19181     // Example: from MVT::v2i32 to MVT::v4i32.
19182     SmallVector<SDValue, 16> Elts;
19183     for (unsigned i = 0, e = NumElts; i != e; ++i)
19184       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19185                                  DAG.getIntPtrConstant(i)));
19186
19187     // Explicitly mark the extra elements as Undef.
19188     SDValue Undef = DAG.getUNDEF(SVT);
19189     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
19190       Elts.push_back(Undef);
19191
19192     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19193     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19194     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
19195     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19196                        DAG.getIntPtrConstant(0));
19197   }
19198
19199   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19200          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19201   assert((DstVT == MVT::i64 ||
19202           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19203          "Unexpected custom BITCAST");
19204   // i64 <=> MMX conversions are Legal.
19205   if (SrcVT==MVT::i64 && DstVT.isVector())
19206     return Op;
19207   if (DstVT==MVT::i64 && SrcVT.isVector())
19208     return Op;
19209   // MMX <=> MMX conversions are Legal.
19210   if (SrcVT.isVector() && DstVT.isVector())
19211     return Op;
19212   // All other conversions need to be expanded.
19213   return SDValue();
19214 }
19215
19216 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19217   SDNode *Node = Op.getNode();
19218   SDLoc dl(Node);
19219   EVT T = Node->getValueType(0);
19220   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19221                               DAG.getConstant(0, T), Node->getOperand(2));
19222   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19223                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19224                        Node->getOperand(0),
19225                        Node->getOperand(1), negOp,
19226                        cast<AtomicSDNode>(Node)->getMemOperand(),
19227                        cast<AtomicSDNode>(Node)->getOrdering(),
19228                        cast<AtomicSDNode>(Node)->getSynchScope());
19229 }
19230
19231 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19232   SDNode *Node = Op.getNode();
19233   SDLoc dl(Node);
19234   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19235
19236   // Convert seq_cst store -> xchg
19237   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19238   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19239   //        (The only way to get a 16-byte store is cmpxchg16b)
19240   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19241   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19242       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19243     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19244                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19245                                  Node->getOperand(0),
19246                                  Node->getOperand(1), Node->getOperand(2),
19247                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19248                                  cast<AtomicSDNode>(Node)->getOrdering(),
19249                                  cast<AtomicSDNode>(Node)->getSynchScope());
19250     return Swap.getValue(1);
19251   }
19252   // Other atomic stores have a simple pattern.
19253   return Op;
19254 }
19255
19256 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19257   EVT VT = Op.getNode()->getSimpleValueType(0);
19258
19259   // Let legalize expand this if it isn't a legal type yet.
19260   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19261     return SDValue();
19262
19263   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19264
19265   unsigned Opc;
19266   bool ExtraOp = false;
19267   switch (Op.getOpcode()) {
19268   default: llvm_unreachable("Invalid code");
19269   case ISD::ADDC: Opc = X86ISD::ADD; break;
19270   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19271   case ISD::SUBC: Opc = X86ISD::SUB; break;
19272   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19273   }
19274
19275   if (!ExtraOp)
19276     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19277                        Op.getOperand(1));
19278   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19279                      Op.getOperand(1), Op.getOperand(2));
19280 }
19281
19282 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19283                             SelectionDAG &DAG) {
19284   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19285
19286   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19287   // which returns the values as { float, float } (in XMM0) or
19288   // { double, double } (which is returned in XMM0, XMM1).
19289   SDLoc dl(Op);
19290   SDValue Arg = Op.getOperand(0);
19291   EVT ArgVT = Arg.getValueType();
19292   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19293
19294   TargetLowering::ArgListTy Args;
19295   TargetLowering::ArgListEntry Entry;
19296
19297   Entry.Node = Arg;
19298   Entry.Ty = ArgTy;
19299   Entry.isSExt = false;
19300   Entry.isZExt = false;
19301   Args.push_back(Entry);
19302
19303   bool isF64 = ArgVT == MVT::f64;
19304   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19305   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19306   // the results are returned via SRet in memory.
19307   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19309   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
19310
19311   Type *RetTy = isF64
19312     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19313     : (Type*)VectorType::get(ArgTy, 4);
19314
19315   TargetLowering::CallLoweringInfo CLI(DAG);
19316   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19317     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19318
19319   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19320
19321   if (isF64)
19322     // Returned in xmm0 and xmm1.
19323     return CallResult.first;
19324
19325   // Returned in bits 0:31 and 32:64 xmm0.
19326   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19327                                CallResult.first, DAG.getIntPtrConstant(0));
19328   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19329                                CallResult.first, DAG.getIntPtrConstant(1));
19330   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19331   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19332 }
19333
19334 /// LowerOperation - Provide custom lowering hooks for some operations.
19335 ///
19336 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19337   switch (Op.getOpcode()) {
19338   default: llvm_unreachable("Should not custom lower this!");
19339   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
19340   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19341   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19342     return LowerCMP_SWAP(Op, Subtarget, DAG);
19343   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19344   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19345   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19346   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
19347   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
19348   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19349   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19350   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19351   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19352   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19353   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19354   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19355   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19356   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19357   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19358   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19359   case ISD::SHL_PARTS:
19360   case ISD::SRA_PARTS:
19361   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19362   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19363   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19364   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19365   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19366   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19367   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19368   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19369   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19370   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19371   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19372   case ISD::FABS:
19373   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19374   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19375   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19376   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19377   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19378   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19379   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19380   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19381   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19382   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19383   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19384   case ISD::INTRINSIC_VOID:
19385   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19386   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19387   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19388   case ISD::FRAME_TO_ARGS_OFFSET:
19389                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19390   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19391   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19392   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19393   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19394   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19395   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19396   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19397   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19398   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19399   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
19400   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19401   case ISD::UMUL_LOHI:
19402   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19403   case ISD::SRA:
19404   case ISD::SRL:
19405   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19406   case ISD::SADDO:
19407   case ISD::UADDO:
19408   case ISD::SSUBO:
19409   case ISD::USUBO:
19410   case ISD::SMULO:
19411   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19412   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19413   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19414   case ISD::ADDC:
19415   case ISD::ADDE:
19416   case ISD::SUBC:
19417   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19418   case ISD::ADD:                return LowerADD(Op, DAG);
19419   case ISD::SUB:                return LowerSUB(Op, DAG);
19420   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19421   }
19422 }
19423
19424 /// ReplaceNodeResults - Replace a node with an illegal result type
19425 /// with a new node built out of custom code.
19426 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19427                                            SmallVectorImpl<SDValue>&Results,
19428                                            SelectionDAG &DAG) const {
19429   SDLoc dl(N);
19430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19431   switch (N->getOpcode()) {
19432   default:
19433     llvm_unreachable("Do not know how to custom type legalize this operation!");
19434   case ISD::SIGN_EXTEND_INREG:
19435   case ISD::ADDC:
19436   case ISD::ADDE:
19437   case ISD::SUBC:
19438   case ISD::SUBE:
19439     // We don't want to expand or promote these.
19440     return;
19441   case ISD::SDIV:
19442   case ISD::UDIV:
19443   case ISD::SREM:
19444   case ISD::UREM:
19445   case ISD::SDIVREM:
19446   case ISD::UDIVREM: {
19447     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19448     Results.push_back(V);
19449     return;
19450   }
19451   case ISD::FP_TO_SINT:
19452   case ISD::FP_TO_UINT: {
19453     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19454
19455     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
19456       return;
19457
19458     std::pair<SDValue,SDValue> Vals =
19459         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19460     SDValue FIST = Vals.first, StackSlot = Vals.second;
19461     if (FIST.getNode()) {
19462       EVT VT = N->getValueType(0);
19463       // Return a load from the stack slot.
19464       if (StackSlot.getNode())
19465         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19466                                       MachinePointerInfo(),
19467                                       false, false, false, 0));
19468       else
19469         Results.push_back(FIST);
19470     }
19471     return;
19472   }
19473   case ISD::UINT_TO_FP: {
19474     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19475     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19476         N->getValueType(0) != MVT::v2f32)
19477       return;
19478     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19479                                  N->getOperand(0));
19480     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
19481                                      MVT::f64);
19482     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19483     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19484                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
19485     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
19486     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19487     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19488     return;
19489   }
19490   case ISD::FP_ROUND: {
19491     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19492         return;
19493     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19494     Results.push_back(V);
19495     return;
19496   }
19497   case ISD::INTRINSIC_W_CHAIN: {
19498     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19499     switch (IntNo) {
19500     default : llvm_unreachable("Do not know how to custom type "
19501                                "legalize this intrinsic operation!");
19502     case Intrinsic::x86_rdtsc:
19503       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19504                                      Results);
19505     case Intrinsic::x86_rdtscp:
19506       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19507                                      Results);
19508     case Intrinsic::x86_rdpmc:
19509       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19510     }
19511   }
19512   case ISD::READCYCLECOUNTER: {
19513     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19514                                    Results);
19515   }
19516   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19517     EVT T = N->getValueType(0);
19518     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19519     bool Regs64bit = T == MVT::i128;
19520     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19521     SDValue cpInL, cpInH;
19522     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19523                         DAG.getConstant(0, HalfT));
19524     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19525                         DAG.getConstant(1, HalfT));
19526     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19527                              Regs64bit ? X86::RAX : X86::EAX,
19528                              cpInL, SDValue());
19529     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19530                              Regs64bit ? X86::RDX : X86::EDX,
19531                              cpInH, cpInL.getValue(1));
19532     SDValue swapInL, swapInH;
19533     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19534                           DAG.getConstant(0, HalfT));
19535     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19536                           DAG.getConstant(1, HalfT));
19537     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19538                                Regs64bit ? X86::RBX : X86::EBX,
19539                                swapInL, cpInH.getValue(1));
19540     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19541                                Regs64bit ? X86::RCX : X86::ECX,
19542                                swapInH, swapInL.getValue(1));
19543     SDValue Ops[] = { swapInH.getValue(0),
19544                       N->getOperand(1),
19545                       swapInH.getValue(1) };
19546     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19547     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19548     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19549                                   X86ISD::LCMPXCHG8_DAG;
19550     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19551     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19552                                         Regs64bit ? X86::RAX : X86::EAX,
19553                                         HalfT, Result.getValue(1));
19554     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19555                                         Regs64bit ? X86::RDX : X86::EDX,
19556                                         HalfT, cpOutL.getValue(2));
19557     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19558
19559     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19560                                         MVT::i32, cpOutH.getValue(2));
19561     SDValue Success =
19562         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19563                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
19564     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19565
19566     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19567     Results.push_back(Success);
19568     Results.push_back(EFLAGS.getValue(1));
19569     return;
19570   }
19571   case ISD::ATOMIC_SWAP:
19572   case ISD::ATOMIC_LOAD_ADD:
19573   case ISD::ATOMIC_LOAD_SUB:
19574   case ISD::ATOMIC_LOAD_AND:
19575   case ISD::ATOMIC_LOAD_OR:
19576   case ISD::ATOMIC_LOAD_XOR:
19577   case ISD::ATOMIC_LOAD_NAND:
19578   case ISD::ATOMIC_LOAD_MIN:
19579   case ISD::ATOMIC_LOAD_MAX:
19580   case ISD::ATOMIC_LOAD_UMIN:
19581   case ISD::ATOMIC_LOAD_UMAX:
19582   case ISD::ATOMIC_LOAD: {
19583     // Delegate to generic TypeLegalization. Situations we can really handle
19584     // should have already been dealt with by AtomicExpandPass.cpp.
19585     break;
19586   }
19587   case ISD::BITCAST: {
19588     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19589     EVT DstVT = N->getValueType(0);
19590     EVT SrcVT = N->getOperand(0)->getValueType(0);
19591
19592     if (SrcVT != MVT::f64 ||
19593         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19594       return;
19595
19596     unsigned NumElts = DstVT.getVectorNumElements();
19597     EVT SVT = DstVT.getVectorElementType();
19598     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19599     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19600                                    MVT::v2f64, N->getOperand(0));
19601     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
19602
19603     if (ExperimentalVectorWideningLegalization) {
19604       // If we are legalizing vectors by widening, we already have the desired
19605       // legal vector type, just return it.
19606       Results.push_back(ToVecInt);
19607       return;
19608     }
19609
19610     SmallVector<SDValue, 8> Elts;
19611     for (unsigned i = 0, e = NumElts; i != e; ++i)
19612       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19613                                    ToVecInt, DAG.getIntPtrConstant(i)));
19614
19615     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19616   }
19617   }
19618 }
19619
19620 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19621   switch (Opcode) {
19622   default: return nullptr;
19623   case X86ISD::BSF:                return "X86ISD::BSF";
19624   case X86ISD::BSR:                return "X86ISD::BSR";
19625   case X86ISD::SHLD:               return "X86ISD::SHLD";
19626   case X86ISD::SHRD:               return "X86ISD::SHRD";
19627   case X86ISD::FAND:               return "X86ISD::FAND";
19628   case X86ISD::FANDN:              return "X86ISD::FANDN";
19629   case X86ISD::FOR:                return "X86ISD::FOR";
19630   case X86ISD::FXOR:               return "X86ISD::FXOR";
19631   case X86ISD::FSRL:               return "X86ISD::FSRL";
19632   case X86ISD::FILD:               return "X86ISD::FILD";
19633   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19634   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19635   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19636   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19637   case X86ISD::FLD:                return "X86ISD::FLD";
19638   case X86ISD::FST:                return "X86ISD::FST";
19639   case X86ISD::CALL:               return "X86ISD::CALL";
19640   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19641   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19642   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19643   case X86ISD::BT:                 return "X86ISD::BT";
19644   case X86ISD::CMP:                return "X86ISD::CMP";
19645   case X86ISD::COMI:               return "X86ISD::COMI";
19646   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19647   case X86ISD::CMPM:               return "X86ISD::CMPM";
19648   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19649   case X86ISD::SETCC:              return "X86ISD::SETCC";
19650   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19651   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19652   case X86ISD::CMOV:               return "X86ISD::CMOV";
19653   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19654   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19655   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19656   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19657   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19658   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19659   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19660   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19661   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19662   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19663   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19664   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19665   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19666   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19667   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19668   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19669   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19670   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19671   case X86ISD::HADD:               return "X86ISD::HADD";
19672   case X86ISD::HSUB:               return "X86ISD::HSUB";
19673   case X86ISD::FHADD:              return "X86ISD::FHADD";
19674   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19675   case X86ISD::UMAX:               return "X86ISD::UMAX";
19676   case X86ISD::UMIN:               return "X86ISD::UMIN";
19677   case X86ISD::SMAX:               return "X86ISD::SMAX";
19678   case X86ISD::SMIN:               return "X86ISD::SMIN";
19679   case X86ISD::FMAX:               return "X86ISD::FMAX";
19680   case X86ISD::FMIN:               return "X86ISD::FMIN";
19681   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19682   case X86ISD::FMINC:              return "X86ISD::FMINC";
19683   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19684   case X86ISD::FRCP:               return "X86ISD::FRCP";
19685   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19686   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19687   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19688   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19689   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19690   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19691   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19692   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19693   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19694   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19695   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19696   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19697   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19698   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19699   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19700   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19701   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19702   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
19703   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19704   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19705   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19706   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19707   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19708   case X86ISD::VSHL:               return "X86ISD::VSHL";
19709   case X86ISD::VSRL:               return "X86ISD::VSRL";
19710   case X86ISD::VSRA:               return "X86ISD::VSRA";
19711   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19712   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19713   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19714   case X86ISD::CMPP:               return "X86ISD::CMPP";
19715   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19716   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19717   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19718   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19719   case X86ISD::ADD:                return "X86ISD::ADD";
19720   case X86ISD::SUB:                return "X86ISD::SUB";
19721   case X86ISD::ADC:                return "X86ISD::ADC";
19722   case X86ISD::SBB:                return "X86ISD::SBB";
19723   case X86ISD::SMUL:               return "X86ISD::SMUL";
19724   case X86ISD::UMUL:               return "X86ISD::UMUL";
19725   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19726   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19727   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19728   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19729   case X86ISD::INC:                return "X86ISD::INC";
19730   case X86ISD::DEC:                return "X86ISD::DEC";
19731   case X86ISD::OR:                 return "X86ISD::OR";
19732   case X86ISD::XOR:                return "X86ISD::XOR";
19733   case X86ISD::AND:                return "X86ISD::AND";
19734   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19735   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19736   case X86ISD::PTEST:              return "X86ISD::PTEST";
19737   case X86ISD::TESTP:              return "X86ISD::TESTP";
19738   case X86ISD::TESTM:              return "X86ISD::TESTM";
19739   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19740   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19741   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19742   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19743   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19744   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19745   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19746   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19747   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19748   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19749   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19750   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19751   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19752   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19753   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19754   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19755   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19756   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19757   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19758   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19759   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19760   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19761   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19762   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
19763   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19764   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19765   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19766   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19767   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19768   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19769   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19770   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19771   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19772   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19773   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19774   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19775   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19776   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19777   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19778   case X86ISD::SAHF:               return "X86ISD::SAHF";
19779   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19780   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19781   case X86ISD::FMADD:              return "X86ISD::FMADD";
19782   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19783   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19784   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19785   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19786   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19787   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19788   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19789   case X86ISD::XTEST:              return "X86ISD::XTEST";
19790   }
19791 }
19792
19793 // isLegalAddressingMode - Return true if the addressing mode represented
19794 // by AM is legal for this target, for a load/store of the specified type.
19795 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
19796                                               Type *Ty) const {
19797   // X86 supports extremely general addressing modes.
19798   CodeModel::Model M = getTargetMachine().getCodeModel();
19799   Reloc::Model R = getTargetMachine().getRelocationModel();
19800
19801   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19802   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19803     return false;
19804
19805   if (AM.BaseGV) {
19806     unsigned GVFlags =
19807       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19808
19809     // If a reference to this global requires an extra load, we can't fold it.
19810     if (isGlobalStubReference(GVFlags))
19811       return false;
19812
19813     // If BaseGV requires a register for the PIC base, we cannot also have a
19814     // BaseReg specified.
19815     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19816       return false;
19817
19818     // If lower 4G is not available, then we must use rip-relative addressing.
19819     if ((M != CodeModel::Small || R != Reloc::Static) &&
19820         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19821       return false;
19822   }
19823
19824   switch (AM.Scale) {
19825   case 0:
19826   case 1:
19827   case 2:
19828   case 4:
19829   case 8:
19830     // These scales always work.
19831     break;
19832   case 3:
19833   case 5:
19834   case 9:
19835     // These scales are formed with basereg+scalereg.  Only accept if there is
19836     // no basereg yet.
19837     if (AM.HasBaseReg)
19838       return false;
19839     break;
19840   default:  // Other stuff never works.
19841     return false;
19842   }
19843
19844   return true;
19845 }
19846
19847 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19848   unsigned Bits = Ty->getScalarSizeInBits();
19849
19850   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19851   // particularly cheaper than those without.
19852   if (Bits == 8)
19853     return false;
19854
19855   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19856   // variable shifts just as cheap as scalar ones.
19857   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19858     return false;
19859
19860   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19861   // fully general vector.
19862   return true;
19863 }
19864
19865 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19866   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19867     return false;
19868   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19869   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19870   return NumBits1 > NumBits2;
19871 }
19872
19873 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19874   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19875     return false;
19876
19877   if (!isTypeLegal(EVT::getEVT(Ty1)))
19878     return false;
19879
19880   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19881
19882   // Assuming the caller doesn't have a zeroext or signext return parameter,
19883   // truncation all the way down to i1 is valid.
19884   return true;
19885 }
19886
19887 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19888   return isInt<32>(Imm);
19889 }
19890
19891 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19892   // Can also use sub to handle negated immediates.
19893   return isInt<32>(Imm);
19894 }
19895
19896 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19897   if (!VT1.isInteger() || !VT2.isInteger())
19898     return false;
19899   unsigned NumBits1 = VT1.getSizeInBits();
19900   unsigned NumBits2 = VT2.getSizeInBits();
19901   return NumBits1 > NumBits2;
19902 }
19903
19904 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19905   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19906   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19907 }
19908
19909 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19910   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19911   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19912 }
19913
19914 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19915   EVT VT1 = Val.getValueType();
19916   if (isZExtFree(VT1, VT2))
19917     return true;
19918
19919   if (Val.getOpcode() != ISD::LOAD)
19920     return false;
19921
19922   if (!VT1.isSimple() || !VT1.isInteger() ||
19923       !VT2.isSimple() || !VT2.isInteger())
19924     return false;
19925
19926   switch (VT1.getSimpleVT().SimpleTy) {
19927   default: break;
19928   case MVT::i8:
19929   case MVT::i16:
19930   case MVT::i32:
19931     // X86 has 8, 16, and 32-bit zero-extending loads.
19932     return true;
19933   }
19934
19935   return false;
19936 }
19937
19938 bool
19939 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19940   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
19941     return false;
19942
19943   VT = VT.getScalarType();
19944
19945   if (!VT.isSimple())
19946     return false;
19947
19948   switch (VT.getSimpleVT().SimpleTy) {
19949   case MVT::f32:
19950   case MVT::f64:
19951     return true;
19952   default:
19953     break;
19954   }
19955
19956   return false;
19957 }
19958
19959 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19960   // i16 instructions are longer (0x66 prefix) and potentially slower.
19961   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19962 }
19963
19964 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19965 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19966 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19967 /// are assumed to be legal.
19968 bool
19969 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19970                                       EVT VT) const {
19971   if (!VT.isSimple())
19972     return false;
19973
19974   MVT SVT = VT.getSimpleVT();
19975
19976   // Very little shuffling can be done for 64-bit vectors right now.
19977   if (VT.getSizeInBits() == 64)
19978     return false;
19979
19980   // If this is a single-input shuffle with no 128 bit lane crossings we can
19981   // lower it into pshufb.
19982   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
19983       (SVT.is256BitVector() && Subtarget->hasInt256())) {
19984     bool isLegal = true;
19985     for (unsigned I = 0, E = M.size(); I != E; ++I) {
19986       if (M[I] >= (int)SVT.getVectorNumElements() ||
19987           ShuffleCrosses128bitLane(SVT, I, M[I])) {
19988         isLegal = false;
19989         break;
19990       }
19991     }
19992     if (isLegal)
19993       return true;
19994   }
19995
19996   // FIXME: blends, shifts.
19997   return (SVT.getVectorNumElements() == 2 ||
19998           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
19999           isMOVLMask(M, SVT) ||
20000           isCommutedMOVLMask(M, SVT) ||
20001           isMOVHLPSMask(M, SVT) ||
20002           isSHUFPMask(M, SVT) ||
20003           isSHUFPMask(M, SVT, /* Commuted */ true) ||
20004           isPSHUFDMask(M, SVT) ||
20005           isPSHUFDMask(M, SVT, /* SecondOperand */ true) ||
20006           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
20007           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
20008           isPALIGNRMask(M, SVT, Subtarget) ||
20009           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
20010           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
20011           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20012           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
20013           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()) ||
20014           (Subtarget->hasSSE41() && isINSERTPSMask(M, SVT)));
20015 }
20016
20017 bool
20018 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20019                                           EVT VT) const {
20020   if (!VT.isSimple())
20021     return false;
20022
20023   MVT SVT = VT.getSimpleVT();
20024   unsigned NumElts = SVT.getVectorNumElements();
20025   // FIXME: This collection of masks seems suspect.
20026   if (NumElts == 2)
20027     return true;
20028   if (NumElts == 4 && SVT.is128BitVector()) {
20029     return (isMOVLMask(Mask, SVT)  ||
20030             isCommutedMOVLMask(Mask, SVT, true) ||
20031             isSHUFPMask(Mask, SVT) ||
20032             isSHUFPMask(Mask, SVT, /* Commuted */ true) ||
20033             isBlendMask(Mask, SVT, Subtarget->hasSSE41(),
20034                         Subtarget->hasInt256()));
20035   }
20036   return false;
20037 }
20038
20039 //===----------------------------------------------------------------------===//
20040 //                           X86 Scheduler Hooks
20041 //===----------------------------------------------------------------------===//
20042
20043 /// Utility function to emit xbegin specifying the start of an RTM region.
20044 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20045                                      const TargetInstrInfo *TII) {
20046   DebugLoc DL = MI->getDebugLoc();
20047
20048   const BasicBlock *BB = MBB->getBasicBlock();
20049   MachineFunction::iterator I = MBB;
20050   ++I;
20051
20052   // For the v = xbegin(), we generate
20053   //
20054   // thisMBB:
20055   //  xbegin sinkMBB
20056   //
20057   // mainMBB:
20058   //  eax = -1
20059   //
20060   // sinkMBB:
20061   //  v = eax
20062
20063   MachineBasicBlock *thisMBB = MBB;
20064   MachineFunction *MF = MBB->getParent();
20065   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20066   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20067   MF->insert(I, mainMBB);
20068   MF->insert(I, sinkMBB);
20069
20070   // Transfer the remainder of BB and its successor edges to sinkMBB.
20071   sinkMBB->splice(sinkMBB->begin(), MBB,
20072                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20073   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20074
20075   // thisMBB:
20076   //  xbegin sinkMBB
20077   //  # fallthrough to mainMBB
20078   //  # abortion to sinkMBB
20079   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20080   thisMBB->addSuccessor(mainMBB);
20081   thisMBB->addSuccessor(sinkMBB);
20082
20083   // mainMBB:
20084   //  EAX = -1
20085   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20086   mainMBB->addSuccessor(sinkMBB);
20087
20088   // sinkMBB:
20089   // EAX is live into the sinkMBB
20090   sinkMBB->addLiveIn(X86::EAX);
20091   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20092           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20093     .addReg(X86::EAX);
20094
20095   MI->eraseFromParent();
20096   return sinkMBB;
20097 }
20098
20099 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20100 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20101 // in the .td file.
20102 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20103                                        const TargetInstrInfo *TII) {
20104   unsigned Opc;
20105   switch (MI->getOpcode()) {
20106   default: llvm_unreachable("illegal opcode!");
20107   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20108   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20109   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20110   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20111   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20112   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20113   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20114   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20115   }
20116
20117   DebugLoc dl = MI->getDebugLoc();
20118   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20119
20120   unsigned NumArgs = MI->getNumOperands();
20121   for (unsigned i = 1; i < NumArgs; ++i) {
20122     MachineOperand &Op = MI->getOperand(i);
20123     if (!(Op.isReg() && Op.isImplicit()))
20124       MIB.addOperand(Op);
20125   }
20126   if (MI->hasOneMemOperand())
20127     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20128
20129   BuildMI(*BB, MI, dl,
20130     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20131     .addReg(X86::XMM0);
20132
20133   MI->eraseFromParent();
20134   return BB;
20135 }
20136
20137 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20138 // defs in an instruction pattern
20139 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20140                                        const TargetInstrInfo *TII) {
20141   unsigned Opc;
20142   switch (MI->getOpcode()) {
20143   default: llvm_unreachable("illegal opcode!");
20144   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20145   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20146   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20147   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20148   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20149   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20150   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20151   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20152   }
20153
20154   DebugLoc dl = MI->getDebugLoc();
20155   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20156
20157   unsigned NumArgs = MI->getNumOperands(); // remove the results
20158   for (unsigned i = 1; i < NumArgs; ++i) {
20159     MachineOperand &Op = MI->getOperand(i);
20160     if (!(Op.isReg() && Op.isImplicit()))
20161       MIB.addOperand(Op);
20162   }
20163   if (MI->hasOneMemOperand())
20164     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20165
20166   BuildMI(*BB, MI, dl,
20167     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20168     .addReg(X86::ECX);
20169
20170   MI->eraseFromParent();
20171   return BB;
20172 }
20173
20174 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20175                                        const TargetInstrInfo *TII,
20176                                        const X86Subtarget* Subtarget) {
20177   DebugLoc dl = MI->getDebugLoc();
20178
20179   // Address into RAX/EAX, other two args into ECX, EDX.
20180   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20181   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20182   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20183   for (int i = 0; i < X86::AddrNumOperands; ++i)
20184     MIB.addOperand(MI->getOperand(i));
20185
20186   unsigned ValOps = X86::AddrNumOperands;
20187   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20188     .addReg(MI->getOperand(ValOps).getReg());
20189   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20190     .addReg(MI->getOperand(ValOps+1).getReg());
20191
20192   // The instruction doesn't actually take any operands though.
20193   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20194
20195   MI->eraseFromParent(); // The pseudo is gone now.
20196   return BB;
20197 }
20198
20199 MachineBasicBlock *
20200 X86TargetLowering::EmitVAARG64WithCustomInserter(
20201                    MachineInstr *MI,
20202                    MachineBasicBlock *MBB) const {
20203   // Emit va_arg instruction on X86-64.
20204
20205   // Operands to this pseudo-instruction:
20206   // 0  ) Output        : destination address (reg)
20207   // 1-5) Input         : va_list address (addr, i64mem)
20208   // 6  ) ArgSize       : Size (in bytes) of vararg type
20209   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20210   // 8  ) Align         : Alignment of type
20211   // 9  ) EFLAGS (implicit-def)
20212
20213   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20214   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
20215
20216   unsigned DestReg = MI->getOperand(0).getReg();
20217   MachineOperand &Base = MI->getOperand(1);
20218   MachineOperand &Scale = MI->getOperand(2);
20219   MachineOperand &Index = MI->getOperand(3);
20220   MachineOperand &Disp = MI->getOperand(4);
20221   MachineOperand &Segment = MI->getOperand(5);
20222   unsigned ArgSize = MI->getOperand(6).getImm();
20223   unsigned ArgMode = MI->getOperand(7).getImm();
20224   unsigned Align = MI->getOperand(8).getImm();
20225
20226   // Memory Reference
20227   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20228   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20229   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20230
20231   // Machine Information
20232   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20233   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20234   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20235   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20236   DebugLoc DL = MI->getDebugLoc();
20237
20238   // struct va_list {
20239   //   i32   gp_offset
20240   //   i32   fp_offset
20241   //   i64   overflow_area (address)
20242   //   i64   reg_save_area (address)
20243   // }
20244   // sizeof(va_list) = 24
20245   // alignment(va_list) = 8
20246
20247   unsigned TotalNumIntRegs = 6;
20248   unsigned TotalNumXMMRegs = 8;
20249   bool UseGPOffset = (ArgMode == 1);
20250   bool UseFPOffset = (ArgMode == 2);
20251   unsigned MaxOffset = TotalNumIntRegs * 8 +
20252                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20253
20254   /* Align ArgSize to a multiple of 8 */
20255   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20256   bool NeedsAlign = (Align > 8);
20257
20258   MachineBasicBlock *thisMBB = MBB;
20259   MachineBasicBlock *overflowMBB;
20260   MachineBasicBlock *offsetMBB;
20261   MachineBasicBlock *endMBB;
20262
20263   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20264   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20265   unsigned OffsetReg = 0;
20266
20267   if (!UseGPOffset && !UseFPOffset) {
20268     // If we only pull from the overflow region, we don't create a branch.
20269     // We don't need to alter control flow.
20270     OffsetDestReg = 0; // unused
20271     OverflowDestReg = DestReg;
20272
20273     offsetMBB = nullptr;
20274     overflowMBB = thisMBB;
20275     endMBB = thisMBB;
20276   } else {
20277     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20278     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20279     // If not, pull from overflow_area. (branch to overflowMBB)
20280     //
20281     //       thisMBB
20282     //         |     .
20283     //         |        .
20284     //     offsetMBB   overflowMBB
20285     //         |        .
20286     //         |     .
20287     //        endMBB
20288
20289     // Registers for the PHI in endMBB
20290     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20291     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20292
20293     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20294     MachineFunction *MF = MBB->getParent();
20295     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20296     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20297     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20298
20299     MachineFunction::iterator MBBIter = MBB;
20300     ++MBBIter;
20301
20302     // Insert the new basic blocks
20303     MF->insert(MBBIter, offsetMBB);
20304     MF->insert(MBBIter, overflowMBB);
20305     MF->insert(MBBIter, endMBB);
20306
20307     // Transfer the remainder of MBB and its successor edges to endMBB.
20308     endMBB->splice(endMBB->begin(), thisMBB,
20309                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20310     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20311
20312     // Make offsetMBB and overflowMBB successors of thisMBB
20313     thisMBB->addSuccessor(offsetMBB);
20314     thisMBB->addSuccessor(overflowMBB);
20315
20316     // endMBB is a successor of both offsetMBB and overflowMBB
20317     offsetMBB->addSuccessor(endMBB);
20318     overflowMBB->addSuccessor(endMBB);
20319
20320     // Load the offset value into a register
20321     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20322     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20323       .addOperand(Base)
20324       .addOperand(Scale)
20325       .addOperand(Index)
20326       .addDisp(Disp, UseFPOffset ? 4 : 0)
20327       .addOperand(Segment)
20328       .setMemRefs(MMOBegin, MMOEnd);
20329
20330     // Check if there is enough room left to pull this argument.
20331     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20332       .addReg(OffsetReg)
20333       .addImm(MaxOffset + 8 - ArgSizeA8);
20334
20335     // Branch to "overflowMBB" if offset >= max
20336     // Fall through to "offsetMBB" otherwise
20337     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20338       .addMBB(overflowMBB);
20339   }
20340
20341   // In offsetMBB, emit code to use the reg_save_area.
20342   if (offsetMBB) {
20343     assert(OffsetReg != 0);
20344
20345     // Read the reg_save_area address.
20346     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20347     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20348       .addOperand(Base)
20349       .addOperand(Scale)
20350       .addOperand(Index)
20351       .addDisp(Disp, 16)
20352       .addOperand(Segment)
20353       .setMemRefs(MMOBegin, MMOEnd);
20354
20355     // Zero-extend the offset
20356     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20357       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20358         .addImm(0)
20359         .addReg(OffsetReg)
20360         .addImm(X86::sub_32bit);
20361
20362     // Add the offset to the reg_save_area to get the final address.
20363     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20364       .addReg(OffsetReg64)
20365       .addReg(RegSaveReg);
20366
20367     // Compute the offset for the next argument
20368     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20369     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20370       .addReg(OffsetReg)
20371       .addImm(UseFPOffset ? 16 : 8);
20372
20373     // Store it back into the va_list.
20374     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20375       .addOperand(Base)
20376       .addOperand(Scale)
20377       .addOperand(Index)
20378       .addDisp(Disp, UseFPOffset ? 4 : 0)
20379       .addOperand(Segment)
20380       .addReg(NextOffsetReg)
20381       .setMemRefs(MMOBegin, MMOEnd);
20382
20383     // Jump to endMBB
20384     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
20385       .addMBB(endMBB);
20386   }
20387
20388   //
20389   // Emit code to use overflow area
20390   //
20391
20392   // Load the overflow_area address into a register.
20393   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20394   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20395     .addOperand(Base)
20396     .addOperand(Scale)
20397     .addOperand(Index)
20398     .addDisp(Disp, 8)
20399     .addOperand(Segment)
20400     .setMemRefs(MMOBegin, MMOEnd);
20401
20402   // If we need to align it, do so. Otherwise, just copy the address
20403   // to OverflowDestReg.
20404   if (NeedsAlign) {
20405     // Align the overflow address
20406     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20407     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20408
20409     // aligned_addr = (addr + (align-1)) & ~(align-1)
20410     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20411       .addReg(OverflowAddrReg)
20412       .addImm(Align-1);
20413
20414     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20415       .addReg(TmpReg)
20416       .addImm(~(uint64_t)(Align-1));
20417   } else {
20418     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20419       .addReg(OverflowAddrReg);
20420   }
20421
20422   // Compute the next overflow address after this argument.
20423   // (the overflow address should be kept 8-byte aligned)
20424   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20425   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20426     .addReg(OverflowDestReg)
20427     .addImm(ArgSizeA8);
20428
20429   // Store the new overflow address.
20430   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20431     .addOperand(Base)
20432     .addOperand(Scale)
20433     .addOperand(Index)
20434     .addDisp(Disp, 8)
20435     .addOperand(Segment)
20436     .addReg(NextAddrReg)
20437     .setMemRefs(MMOBegin, MMOEnd);
20438
20439   // If we branched, emit the PHI to the front of endMBB.
20440   if (offsetMBB) {
20441     BuildMI(*endMBB, endMBB->begin(), DL,
20442             TII->get(X86::PHI), DestReg)
20443       .addReg(OffsetDestReg).addMBB(offsetMBB)
20444       .addReg(OverflowDestReg).addMBB(overflowMBB);
20445   }
20446
20447   // Erase the pseudo instruction
20448   MI->eraseFromParent();
20449
20450   return endMBB;
20451 }
20452
20453 MachineBasicBlock *
20454 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20455                                                  MachineInstr *MI,
20456                                                  MachineBasicBlock *MBB) const {
20457   // Emit code to save XMM registers to the stack. The ABI says that the
20458   // number of registers to save is given in %al, so it's theoretically
20459   // possible to do an indirect jump trick to avoid saving all of them,
20460   // however this code takes a simpler approach and just executes all
20461   // of the stores if %al is non-zero. It's less code, and it's probably
20462   // easier on the hardware branch predictor, and stores aren't all that
20463   // expensive anyway.
20464
20465   // Create the new basic blocks. One block contains all the XMM stores,
20466   // and one block is the final destination regardless of whether any
20467   // stores were performed.
20468   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20469   MachineFunction *F = MBB->getParent();
20470   MachineFunction::iterator MBBIter = MBB;
20471   ++MBBIter;
20472   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20473   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20474   F->insert(MBBIter, XMMSaveMBB);
20475   F->insert(MBBIter, EndMBB);
20476
20477   // Transfer the remainder of MBB and its successor edges to EndMBB.
20478   EndMBB->splice(EndMBB->begin(), MBB,
20479                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20480   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20481
20482   // The original block will now fall through to the XMM save block.
20483   MBB->addSuccessor(XMMSaveMBB);
20484   // The XMMSaveMBB will fall through to the end block.
20485   XMMSaveMBB->addSuccessor(EndMBB);
20486
20487   // Now add the instructions.
20488   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
20489   DebugLoc DL = MI->getDebugLoc();
20490
20491   unsigned CountReg = MI->getOperand(0).getReg();
20492   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20493   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20494
20495   if (!Subtarget->isTargetWin64()) {
20496     // If %al is 0, branch around the XMM save block.
20497     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20498     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
20499     MBB->addSuccessor(EndMBB);
20500   }
20501
20502   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20503   // that was just emitted, but clearly shouldn't be "saved".
20504   assert((MI->getNumOperands() <= 3 ||
20505           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20506           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20507          && "Expected last argument to be EFLAGS");
20508   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20509   // In the XMM save block, save all the XMM argument registers.
20510   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20511     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20512     MachineMemOperand *MMO =
20513       F->getMachineMemOperand(
20514           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
20515         MachineMemOperand::MOStore,
20516         /*Size=*/16, /*Align=*/16);
20517     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20518       .addFrameIndex(RegSaveFrameIndex)
20519       .addImm(/*Scale=*/1)
20520       .addReg(/*IndexReg=*/0)
20521       .addImm(/*Disp=*/Offset)
20522       .addReg(/*Segment=*/0)
20523       .addReg(MI->getOperand(i).getReg())
20524       .addMemOperand(MMO);
20525   }
20526
20527   MI->eraseFromParent();   // The pseudo instruction is gone now.
20528
20529   return EndMBB;
20530 }
20531
20532 // The EFLAGS operand of SelectItr might be missing a kill marker
20533 // because there were multiple uses of EFLAGS, and ISel didn't know
20534 // which to mark. Figure out whether SelectItr should have had a
20535 // kill marker, and set it if it should. Returns the correct kill
20536 // marker value.
20537 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20538                                      MachineBasicBlock* BB,
20539                                      const TargetRegisterInfo* TRI) {
20540   // Scan forward through BB for a use/def of EFLAGS.
20541   MachineBasicBlock::iterator miI(std::next(SelectItr));
20542   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20543     const MachineInstr& mi = *miI;
20544     if (mi.readsRegister(X86::EFLAGS))
20545       return false;
20546     if (mi.definesRegister(X86::EFLAGS))
20547       break; // Should have kill-flag - update below.
20548   }
20549
20550   // If we hit the end of the block, check whether EFLAGS is live into a
20551   // successor.
20552   if (miI == BB->end()) {
20553     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20554                                           sEnd = BB->succ_end();
20555          sItr != sEnd; ++sItr) {
20556       MachineBasicBlock* succ = *sItr;
20557       if (succ->isLiveIn(X86::EFLAGS))
20558         return false;
20559     }
20560   }
20561
20562   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20563   // out. SelectMI should have a kill flag on EFLAGS.
20564   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20565   return true;
20566 }
20567
20568 MachineBasicBlock *
20569 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20570                                      MachineBasicBlock *BB) const {
20571   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20572   DebugLoc DL = MI->getDebugLoc();
20573
20574   // To "insert" a SELECT_CC instruction, we actually have to insert the
20575   // diamond control-flow pattern.  The incoming instruction knows the
20576   // destination vreg to set, the condition code register to branch on, the
20577   // true/false values to select between, and a branch opcode to use.
20578   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20579   MachineFunction::iterator It = BB;
20580   ++It;
20581
20582   //  thisMBB:
20583   //  ...
20584   //   TrueVal = ...
20585   //   cmpTY ccX, r1, r2
20586   //   bCC copy1MBB
20587   //   fallthrough --> copy0MBB
20588   MachineBasicBlock *thisMBB = BB;
20589   MachineFunction *F = BB->getParent();
20590   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20591   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20592   F->insert(It, copy0MBB);
20593   F->insert(It, sinkMBB);
20594
20595   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20596   // live into the sink and copy blocks.
20597   const TargetRegisterInfo *TRI =
20598       BB->getParent()->getSubtarget().getRegisterInfo();
20599   if (!MI->killsRegister(X86::EFLAGS) &&
20600       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
20601     copy0MBB->addLiveIn(X86::EFLAGS);
20602     sinkMBB->addLiveIn(X86::EFLAGS);
20603   }
20604
20605   // Transfer the remainder of BB and its successor edges to sinkMBB.
20606   sinkMBB->splice(sinkMBB->begin(), BB,
20607                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20608   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20609
20610   // Add the true and fallthrough blocks as its successors.
20611   BB->addSuccessor(copy0MBB);
20612   BB->addSuccessor(sinkMBB);
20613
20614   // Create the conditional branch instruction.
20615   unsigned Opc =
20616     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20617   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20618
20619   //  copy0MBB:
20620   //   %FalseValue = ...
20621   //   # fallthrough to sinkMBB
20622   copy0MBB->addSuccessor(sinkMBB);
20623
20624   //  sinkMBB:
20625   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20626   //  ...
20627   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20628           TII->get(X86::PHI), MI->getOperand(0).getReg())
20629     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20630     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20631
20632   MI->eraseFromParent();   // The pseudo instruction is gone now.
20633   return sinkMBB;
20634 }
20635
20636 MachineBasicBlock *
20637 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20638                                         MachineBasicBlock *BB) const {
20639   MachineFunction *MF = BB->getParent();
20640   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20641   DebugLoc DL = MI->getDebugLoc();
20642   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20643
20644   assert(MF->shouldSplitStack());
20645
20646   const bool Is64Bit = Subtarget->is64Bit();
20647   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20648
20649   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20650   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20651
20652   // BB:
20653   //  ... [Till the alloca]
20654   // If stacklet is not large enough, jump to mallocMBB
20655   //
20656   // bumpMBB:
20657   //  Allocate by subtracting from RSP
20658   //  Jump to continueMBB
20659   //
20660   // mallocMBB:
20661   //  Allocate by call to runtime
20662   //
20663   // continueMBB:
20664   //  ...
20665   //  [rest of original BB]
20666   //
20667
20668   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20669   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20670   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20671
20672   MachineRegisterInfo &MRI = MF->getRegInfo();
20673   const TargetRegisterClass *AddrRegClass =
20674     getRegClassFor(getPointerTy());
20675
20676   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20677     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20678     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20679     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20680     sizeVReg = MI->getOperand(1).getReg(),
20681     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20682
20683   MachineFunction::iterator MBBIter = BB;
20684   ++MBBIter;
20685
20686   MF->insert(MBBIter, bumpMBB);
20687   MF->insert(MBBIter, mallocMBB);
20688   MF->insert(MBBIter, continueMBB);
20689
20690   continueMBB->splice(continueMBB->begin(), BB,
20691                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20692   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20693
20694   // Add code to the main basic block to check if the stack limit has been hit,
20695   // and if so, jump to mallocMBB otherwise to bumpMBB.
20696   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20697   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20698     .addReg(tmpSPVReg).addReg(sizeVReg);
20699   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20700     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20701     .addReg(SPLimitVReg);
20702   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
20703
20704   // bumpMBB simply decreases the stack pointer, since we know the current
20705   // stacklet has enough space.
20706   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20707     .addReg(SPLimitVReg);
20708   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20709     .addReg(SPLimitVReg);
20710   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20711
20712   // Calls into a routine in libgcc to allocate more space from the heap.
20713   const uint32_t *RegMask = MF->getTarget()
20714                                 .getSubtargetImpl()
20715                                 ->getRegisterInfo()
20716                                 ->getCallPreservedMask(CallingConv::C);
20717   if (IsLP64) {
20718     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20719       .addReg(sizeVReg);
20720     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20721       .addExternalSymbol("__morestack_allocate_stack_space")
20722       .addRegMask(RegMask)
20723       .addReg(X86::RDI, RegState::Implicit)
20724       .addReg(X86::RAX, RegState::ImplicitDefine);
20725   } else if (Is64Bit) {
20726     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20727       .addReg(sizeVReg);
20728     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20729       .addExternalSymbol("__morestack_allocate_stack_space")
20730       .addRegMask(RegMask)
20731       .addReg(X86::EDI, RegState::Implicit)
20732       .addReg(X86::EAX, RegState::ImplicitDefine);
20733   } else {
20734     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20735       .addImm(12);
20736     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20737     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20738       .addExternalSymbol("__morestack_allocate_stack_space")
20739       .addRegMask(RegMask)
20740       .addReg(X86::EAX, RegState::ImplicitDefine);
20741   }
20742
20743   if (!Is64Bit)
20744     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20745       .addImm(16);
20746
20747   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20748     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20749   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
20750
20751   // Set up the CFG correctly.
20752   BB->addSuccessor(bumpMBB);
20753   BB->addSuccessor(mallocMBB);
20754   mallocMBB->addSuccessor(continueMBB);
20755   bumpMBB->addSuccessor(continueMBB);
20756
20757   // Take care of the PHI nodes.
20758   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20759           MI->getOperand(0).getReg())
20760     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20761     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20762
20763   // Delete the original pseudo instruction.
20764   MI->eraseFromParent();
20765
20766   // And we're done.
20767   return continueMBB;
20768 }
20769
20770 MachineBasicBlock *
20771 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20772                                         MachineBasicBlock *BB) const {
20773   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
20774   DebugLoc DL = MI->getDebugLoc();
20775
20776   assert(!Subtarget->isTargetMacho());
20777
20778   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
20779   // non-trivial part is impdef of ESP.
20780
20781   if (Subtarget->isTargetWin64()) {
20782     if (Subtarget->isTargetCygMing()) {
20783       // ___chkstk(Mingw64):
20784       // Clobbers R10, R11, RAX and EFLAGS.
20785       // Updates RSP.
20786       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20787         .addExternalSymbol("___chkstk")
20788         .addReg(X86::RAX, RegState::Implicit)
20789         .addReg(X86::RSP, RegState::Implicit)
20790         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
20791         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
20792         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20793     } else {
20794       // __chkstk(MSVCRT): does not update stack pointer.
20795       // Clobbers R10, R11 and EFLAGS.
20796       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
20797         .addExternalSymbol("__chkstk")
20798         .addReg(X86::RAX, RegState::Implicit)
20799         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20800       // RAX has the offset to be subtracted from RSP.
20801       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
20802         .addReg(X86::RSP)
20803         .addReg(X86::RAX);
20804     }
20805   } else {
20806     const char *StackProbeSymbol = (Subtarget->isTargetKnownWindowsMSVC() ||
20807                                     Subtarget->isTargetWindowsItanium())
20808                                        ? "_chkstk"
20809                                        : "_alloca";
20810
20811     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
20812       .addExternalSymbol(StackProbeSymbol)
20813       .addReg(X86::EAX, RegState::Implicit)
20814       .addReg(X86::ESP, RegState::Implicit)
20815       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
20816       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
20817       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
20818   }
20819
20820   MI->eraseFromParent();   // The pseudo instruction is gone now.
20821   return BB;
20822 }
20823
20824 MachineBasicBlock *
20825 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20826                                       MachineBasicBlock *BB) const {
20827   // This is pretty easy.  We're taking the value that we received from
20828   // our load from the relocation, sticking it in either RDI (x86-64)
20829   // or EAX and doing an indirect call.  The return value will then
20830   // be in the normal return register.
20831   MachineFunction *F = BB->getParent();
20832   const X86InstrInfo *TII =
20833       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
20834   DebugLoc DL = MI->getDebugLoc();
20835
20836   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20837   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20838
20839   // Get a register mask for the lowered call.
20840   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20841   // proper register mask.
20842   const uint32_t *RegMask = F->getTarget()
20843                                 .getSubtargetImpl()
20844                                 ->getRegisterInfo()
20845                                 ->getCallPreservedMask(CallingConv::C);
20846   if (Subtarget->is64Bit()) {
20847     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20848                                       TII->get(X86::MOV64rm), X86::RDI)
20849     .addReg(X86::RIP)
20850     .addImm(0).addReg(0)
20851     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20852                       MI->getOperand(3).getTargetFlags())
20853     .addReg(0);
20854     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20855     addDirectMem(MIB, X86::RDI);
20856     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20857   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20858     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20859                                       TII->get(X86::MOV32rm), X86::EAX)
20860     .addReg(0)
20861     .addImm(0).addReg(0)
20862     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20863                       MI->getOperand(3).getTargetFlags())
20864     .addReg(0);
20865     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20866     addDirectMem(MIB, X86::EAX);
20867     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20868   } else {
20869     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20870                                       TII->get(X86::MOV32rm), X86::EAX)
20871     .addReg(TII->getGlobalBaseReg(F))
20872     .addImm(0).addReg(0)
20873     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20874                       MI->getOperand(3).getTargetFlags())
20875     .addReg(0);
20876     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20877     addDirectMem(MIB, X86::EAX);
20878     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20879   }
20880
20881   MI->eraseFromParent(); // The pseudo instruction is gone now.
20882   return BB;
20883 }
20884
20885 MachineBasicBlock *
20886 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20887                                     MachineBasicBlock *MBB) const {
20888   DebugLoc DL = MI->getDebugLoc();
20889   MachineFunction *MF = MBB->getParent();
20890   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
20891   MachineRegisterInfo &MRI = MF->getRegInfo();
20892
20893   const BasicBlock *BB = MBB->getBasicBlock();
20894   MachineFunction::iterator I = MBB;
20895   ++I;
20896
20897   // Memory Reference
20898   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20899   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20900
20901   unsigned DstReg;
20902   unsigned MemOpndSlot = 0;
20903
20904   unsigned CurOp = 0;
20905
20906   DstReg = MI->getOperand(CurOp++).getReg();
20907   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20908   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20909   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20910   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20911
20912   MemOpndSlot = CurOp;
20913
20914   MVT PVT = getPointerTy();
20915   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20916          "Invalid Pointer Size!");
20917
20918   // For v = setjmp(buf), we generate
20919   //
20920   // thisMBB:
20921   //  buf[LabelOffset] = restoreMBB
20922   //  SjLjSetup restoreMBB
20923   //
20924   // mainMBB:
20925   //  v_main = 0
20926   //
20927   // sinkMBB:
20928   //  v = phi(main, restore)
20929   //
20930   // restoreMBB:
20931   //  v_restore = 1
20932
20933   MachineBasicBlock *thisMBB = MBB;
20934   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20935   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20936   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20937   MF->insert(I, mainMBB);
20938   MF->insert(I, sinkMBB);
20939   MF->push_back(restoreMBB);
20940
20941   MachineInstrBuilder MIB;
20942
20943   // Transfer the remainder of BB and its successor edges to sinkMBB.
20944   sinkMBB->splice(sinkMBB->begin(), MBB,
20945                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20946   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20947
20948   // thisMBB:
20949   unsigned PtrStoreOpc = 0;
20950   unsigned LabelReg = 0;
20951   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20952   Reloc::Model RM = MF->getTarget().getRelocationModel();
20953   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20954                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20955
20956   // Prepare IP either in reg or imm.
20957   if (!UseImmLabel) {
20958     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20959     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20960     LabelReg = MRI.createVirtualRegister(PtrRC);
20961     if (Subtarget->is64Bit()) {
20962       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20963               .addReg(X86::RIP)
20964               .addImm(0)
20965               .addReg(0)
20966               .addMBB(restoreMBB)
20967               .addReg(0);
20968     } else {
20969       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20970       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20971               .addReg(XII->getGlobalBaseReg(MF))
20972               .addImm(0)
20973               .addReg(0)
20974               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20975               .addReg(0);
20976     }
20977   } else
20978     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20979   // Store IP
20980   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20981   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20982     if (i == X86::AddrDisp)
20983       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20984     else
20985       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20986   }
20987   if (!UseImmLabel)
20988     MIB.addReg(LabelReg);
20989   else
20990     MIB.addMBB(restoreMBB);
20991   MIB.setMemRefs(MMOBegin, MMOEnd);
20992   // Setup
20993   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20994           .addMBB(restoreMBB);
20995
20996   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
20997       MF->getSubtarget().getRegisterInfo());
20998   MIB.addRegMask(RegInfo->getNoPreservedMask());
20999   thisMBB->addSuccessor(mainMBB);
21000   thisMBB->addSuccessor(restoreMBB);
21001
21002   // mainMBB:
21003   //  EAX = 0
21004   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21005   mainMBB->addSuccessor(sinkMBB);
21006
21007   // sinkMBB:
21008   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21009           TII->get(X86::PHI), DstReg)
21010     .addReg(mainDstReg).addMBB(mainMBB)
21011     .addReg(restoreDstReg).addMBB(restoreMBB);
21012
21013   // restoreMBB:
21014   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21015   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
21016   restoreMBB->addSuccessor(sinkMBB);
21017
21018   MI->eraseFromParent();
21019   return sinkMBB;
21020 }
21021
21022 MachineBasicBlock *
21023 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21024                                      MachineBasicBlock *MBB) const {
21025   DebugLoc DL = MI->getDebugLoc();
21026   MachineFunction *MF = MBB->getParent();
21027   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
21028   MachineRegisterInfo &MRI = MF->getRegInfo();
21029
21030   // Memory Reference
21031   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21032   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21033
21034   MVT PVT = getPointerTy();
21035   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21036          "Invalid Pointer Size!");
21037
21038   const TargetRegisterClass *RC =
21039     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21040   unsigned Tmp = MRI.createVirtualRegister(RC);
21041   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21042   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
21043       MF->getSubtarget().getRegisterInfo());
21044   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21045   unsigned SP = RegInfo->getStackRegister();
21046
21047   MachineInstrBuilder MIB;
21048
21049   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21050   const int64_t SPOffset = 2 * PVT.getStoreSize();
21051
21052   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21053   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21054
21055   // Reload FP
21056   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21057   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21058     MIB.addOperand(MI->getOperand(i));
21059   MIB.setMemRefs(MMOBegin, MMOEnd);
21060   // Reload IP
21061   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21062   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21063     if (i == X86::AddrDisp)
21064       MIB.addDisp(MI->getOperand(i), LabelOffset);
21065     else
21066       MIB.addOperand(MI->getOperand(i));
21067   }
21068   MIB.setMemRefs(MMOBegin, MMOEnd);
21069   // Reload SP
21070   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21071   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21072     if (i == X86::AddrDisp)
21073       MIB.addDisp(MI->getOperand(i), SPOffset);
21074     else
21075       MIB.addOperand(MI->getOperand(i));
21076   }
21077   MIB.setMemRefs(MMOBegin, MMOEnd);
21078   // Jump
21079   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21080
21081   MI->eraseFromParent();
21082   return MBB;
21083 }
21084
21085 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21086 // accumulator loops. Writing back to the accumulator allows the coalescer
21087 // to remove extra copies in the loop.   
21088 MachineBasicBlock *
21089 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21090                                  MachineBasicBlock *MBB) const {
21091   MachineOperand &AddendOp = MI->getOperand(3);
21092
21093   // Bail out early if the addend isn't a register - we can't switch these.
21094   if (!AddendOp.isReg())
21095     return MBB;
21096
21097   MachineFunction &MF = *MBB->getParent();
21098   MachineRegisterInfo &MRI = MF.getRegInfo();
21099
21100   // Check whether the addend is defined by a PHI:
21101   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21102   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21103   if (!AddendDef.isPHI())
21104     return MBB;
21105
21106   // Look for the following pattern:
21107   // loop:
21108   //   %addend = phi [%entry, 0], [%loop, %result]
21109   //   ...
21110   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21111
21112   // Replace with:
21113   //   loop:
21114   //   %addend = phi [%entry, 0], [%loop, %result]
21115   //   ...
21116   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21117
21118   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21119     assert(AddendDef.getOperand(i).isReg());
21120     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21121     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21122     if (&PHISrcInst == MI) {
21123       // Found a matching instruction.
21124       unsigned NewFMAOpc = 0;
21125       switch (MI->getOpcode()) {
21126         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21127         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21128         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21129         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21130         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21131         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21132         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21133         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21134         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21135         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21136         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21137         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21138         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21139         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21140         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21141         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21142         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21143         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21144         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21145         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21146
21147         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21148         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21149         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21150         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21151         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21152         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21153         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21154         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21155         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21156         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21157         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21158         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21159         default: llvm_unreachable("Unrecognized FMA variant.");
21160       }
21161
21162       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
21163       MachineInstrBuilder MIB =
21164         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21165         .addOperand(MI->getOperand(0))
21166         .addOperand(MI->getOperand(3))
21167         .addOperand(MI->getOperand(2))
21168         .addOperand(MI->getOperand(1));
21169       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21170       MI->eraseFromParent();
21171     }
21172   }
21173
21174   return MBB;
21175 }
21176
21177 MachineBasicBlock *
21178 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21179                                                MachineBasicBlock *BB) const {
21180   switch (MI->getOpcode()) {
21181   default: llvm_unreachable("Unexpected instr type to insert");
21182   case X86::TAILJMPd64:
21183   case X86::TAILJMPr64:
21184   case X86::TAILJMPm64:
21185     llvm_unreachable("TAILJMP64 would not be touched here.");
21186   case X86::TCRETURNdi64:
21187   case X86::TCRETURNri64:
21188   case X86::TCRETURNmi64:
21189     return BB;
21190   case X86::WIN_ALLOCA:
21191     return EmitLoweredWinAlloca(MI, BB);
21192   case X86::SEG_ALLOCA_32:
21193   case X86::SEG_ALLOCA_64:
21194     return EmitLoweredSegAlloca(MI, BB);
21195   case X86::TLSCall_32:
21196   case X86::TLSCall_64:
21197     return EmitLoweredTLSCall(MI, BB);
21198   case X86::CMOV_GR8:
21199   case X86::CMOV_FR32:
21200   case X86::CMOV_FR64:
21201   case X86::CMOV_V4F32:
21202   case X86::CMOV_V2F64:
21203   case X86::CMOV_V2I64:
21204   case X86::CMOV_V8F32:
21205   case X86::CMOV_V4F64:
21206   case X86::CMOV_V4I64:
21207   case X86::CMOV_V16F32:
21208   case X86::CMOV_V8F64:
21209   case X86::CMOV_V8I64:
21210   case X86::CMOV_GR16:
21211   case X86::CMOV_GR32:
21212   case X86::CMOV_RFP32:
21213   case X86::CMOV_RFP64:
21214   case X86::CMOV_RFP80:
21215     return EmitLoweredSelect(MI, BB);
21216
21217   case X86::FP32_TO_INT16_IN_MEM:
21218   case X86::FP32_TO_INT32_IN_MEM:
21219   case X86::FP32_TO_INT64_IN_MEM:
21220   case X86::FP64_TO_INT16_IN_MEM:
21221   case X86::FP64_TO_INT32_IN_MEM:
21222   case X86::FP64_TO_INT64_IN_MEM:
21223   case X86::FP80_TO_INT16_IN_MEM:
21224   case X86::FP80_TO_INT32_IN_MEM:
21225   case X86::FP80_TO_INT64_IN_MEM: {
21226     MachineFunction *F = BB->getParent();
21227     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
21228     DebugLoc DL = MI->getDebugLoc();
21229
21230     // Change the floating point control register to use "round towards zero"
21231     // mode when truncating to an integer value.
21232     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21233     addFrameReference(BuildMI(*BB, MI, DL,
21234                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21235
21236     // Load the old value of the high byte of the control word...
21237     unsigned OldCW =
21238       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21239     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21240                       CWFrameIdx);
21241
21242     // Set the high part to be round to zero...
21243     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21244       .addImm(0xC7F);
21245
21246     // Reload the modified control word now...
21247     addFrameReference(BuildMI(*BB, MI, DL,
21248                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21249
21250     // Restore the memory image of control word to original value
21251     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21252       .addReg(OldCW);
21253
21254     // Get the X86 opcode to use.
21255     unsigned Opc;
21256     switch (MI->getOpcode()) {
21257     default: llvm_unreachable("illegal opcode!");
21258     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21259     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21260     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21261     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21262     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21263     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21264     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21265     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21266     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21267     }
21268
21269     X86AddressMode AM;
21270     MachineOperand &Op = MI->getOperand(0);
21271     if (Op.isReg()) {
21272       AM.BaseType = X86AddressMode::RegBase;
21273       AM.Base.Reg = Op.getReg();
21274     } else {
21275       AM.BaseType = X86AddressMode::FrameIndexBase;
21276       AM.Base.FrameIndex = Op.getIndex();
21277     }
21278     Op = MI->getOperand(1);
21279     if (Op.isImm())
21280       AM.Scale = Op.getImm();
21281     Op = MI->getOperand(2);
21282     if (Op.isImm())
21283       AM.IndexReg = Op.getImm();
21284     Op = MI->getOperand(3);
21285     if (Op.isGlobal()) {
21286       AM.GV = Op.getGlobal();
21287     } else {
21288       AM.Disp = Op.getImm();
21289     }
21290     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21291                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21292
21293     // Reload the original control word now.
21294     addFrameReference(BuildMI(*BB, MI, DL,
21295                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21296
21297     MI->eraseFromParent();   // The pseudo instruction is gone now.
21298     return BB;
21299   }
21300     // String/text processing lowering.
21301   case X86::PCMPISTRM128REG:
21302   case X86::VPCMPISTRM128REG:
21303   case X86::PCMPISTRM128MEM:
21304   case X86::VPCMPISTRM128MEM:
21305   case X86::PCMPESTRM128REG:
21306   case X86::VPCMPESTRM128REG:
21307   case X86::PCMPESTRM128MEM:
21308   case X86::VPCMPESTRM128MEM:
21309     assert(Subtarget->hasSSE42() &&
21310            "Target must have SSE4.2 or AVX features enabled");
21311     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21312
21313   // String/text processing lowering.
21314   case X86::PCMPISTRIREG:
21315   case X86::VPCMPISTRIREG:
21316   case X86::PCMPISTRIMEM:
21317   case X86::VPCMPISTRIMEM:
21318   case X86::PCMPESTRIREG:
21319   case X86::VPCMPESTRIREG:
21320   case X86::PCMPESTRIMEM:
21321   case X86::VPCMPESTRIMEM:
21322     assert(Subtarget->hasSSE42() &&
21323            "Target must have SSE4.2 or AVX features enabled");
21324     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21325
21326   // Thread synchronization.
21327   case X86::MONITOR:
21328     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
21329                        Subtarget);
21330
21331   // xbegin
21332   case X86::XBEGIN:
21333     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
21334
21335   case X86::VASTART_SAVE_XMM_REGS:
21336     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21337
21338   case X86::VAARG_64:
21339     return EmitVAARG64WithCustomInserter(MI, BB);
21340
21341   case X86::EH_SjLj_SetJmp32:
21342   case X86::EH_SjLj_SetJmp64:
21343     return emitEHSjLjSetJmp(MI, BB);
21344
21345   case X86::EH_SjLj_LongJmp32:
21346   case X86::EH_SjLj_LongJmp64:
21347     return emitEHSjLjLongJmp(MI, BB);
21348
21349   case TargetOpcode::STATEPOINT:
21350     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21351     // this point in the process.  We diverge later.
21352     return emitPatchPoint(MI, BB);
21353
21354   case TargetOpcode::STACKMAP:
21355   case TargetOpcode::PATCHPOINT:
21356     return emitPatchPoint(MI, BB);
21357
21358   case X86::VFMADDPDr213r:
21359   case X86::VFMADDPSr213r:
21360   case X86::VFMADDSDr213r:
21361   case X86::VFMADDSSr213r:
21362   case X86::VFMSUBPDr213r:
21363   case X86::VFMSUBPSr213r:
21364   case X86::VFMSUBSDr213r:
21365   case X86::VFMSUBSSr213r:
21366   case X86::VFNMADDPDr213r:
21367   case X86::VFNMADDPSr213r:
21368   case X86::VFNMADDSDr213r:
21369   case X86::VFNMADDSSr213r:
21370   case X86::VFNMSUBPDr213r:
21371   case X86::VFNMSUBPSr213r:
21372   case X86::VFNMSUBSDr213r:
21373   case X86::VFNMSUBSSr213r:
21374   case X86::VFMADDSUBPDr213r:
21375   case X86::VFMADDSUBPSr213r:
21376   case X86::VFMSUBADDPDr213r:
21377   case X86::VFMSUBADDPSr213r:
21378   case X86::VFMADDPDr213rY:
21379   case X86::VFMADDPSr213rY:
21380   case X86::VFMSUBPDr213rY:
21381   case X86::VFMSUBPSr213rY:
21382   case X86::VFNMADDPDr213rY:
21383   case X86::VFNMADDPSr213rY:
21384   case X86::VFNMSUBPDr213rY:
21385   case X86::VFNMSUBPSr213rY:
21386   case X86::VFMADDSUBPDr213rY:
21387   case X86::VFMADDSUBPSr213rY:
21388   case X86::VFMSUBADDPDr213rY:
21389   case X86::VFMSUBADDPSr213rY:
21390     return emitFMA3Instr(MI, BB);
21391   }
21392 }
21393
21394 //===----------------------------------------------------------------------===//
21395 //                           X86 Optimization Hooks
21396 //===----------------------------------------------------------------------===//
21397
21398 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21399                                                       APInt &KnownZero,
21400                                                       APInt &KnownOne,
21401                                                       const SelectionDAG &DAG,
21402                                                       unsigned Depth) const {
21403   unsigned BitWidth = KnownZero.getBitWidth();
21404   unsigned Opc = Op.getOpcode();
21405   assert((Opc >= ISD::BUILTIN_OP_END ||
21406           Opc == ISD::INTRINSIC_WO_CHAIN ||
21407           Opc == ISD::INTRINSIC_W_CHAIN ||
21408           Opc == ISD::INTRINSIC_VOID) &&
21409          "Should use MaskedValueIsZero if you don't know whether Op"
21410          " is a target node!");
21411
21412   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21413   switch (Opc) {
21414   default: break;
21415   case X86ISD::ADD:
21416   case X86ISD::SUB:
21417   case X86ISD::ADC:
21418   case X86ISD::SBB:
21419   case X86ISD::SMUL:
21420   case X86ISD::UMUL:
21421   case X86ISD::INC:
21422   case X86ISD::DEC:
21423   case X86ISD::OR:
21424   case X86ISD::XOR:
21425   case X86ISD::AND:
21426     // These nodes' second result is a boolean.
21427     if (Op.getResNo() == 0)
21428       break;
21429     // Fallthrough
21430   case X86ISD::SETCC:
21431     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21432     break;
21433   case ISD::INTRINSIC_WO_CHAIN: {
21434     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21435     unsigned NumLoBits = 0;
21436     switch (IntId) {
21437     default: break;
21438     case Intrinsic::x86_sse_movmsk_ps:
21439     case Intrinsic::x86_avx_movmsk_ps_256:
21440     case Intrinsic::x86_sse2_movmsk_pd:
21441     case Intrinsic::x86_avx_movmsk_pd_256:
21442     case Intrinsic::x86_mmx_pmovmskb:
21443     case Intrinsic::x86_sse2_pmovmskb_128:
21444     case Intrinsic::x86_avx2_pmovmskb: {
21445       // High bits of movmskp{s|d}, pmovmskb are known zero.
21446       switch (IntId) {
21447         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21448         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21449         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21450         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21451         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21452         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21453         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21454         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21455       }
21456       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21457       break;
21458     }
21459     }
21460     break;
21461   }
21462   }
21463 }
21464
21465 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21466   SDValue Op,
21467   const SelectionDAG &,
21468   unsigned Depth) const {
21469   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21470   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21471     return Op.getValueType().getScalarType().getSizeInBits();
21472
21473   // Fallback case.
21474   return 1;
21475 }
21476
21477 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21478 /// node is a GlobalAddress + offset.
21479 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21480                                        const GlobalValue* &GA,
21481                                        int64_t &Offset) const {
21482   if (N->getOpcode() == X86ISD::Wrapper) {
21483     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21484       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21485       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21486       return true;
21487     }
21488   }
21489   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21490 }
21491
21492 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21493 /// same as extracting the high 128-bit part of 256-bit vector and then
21494 /// inserting the result into the low part of a new 256-bit vector
21495 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21496   EVT VT = SVOp->getValueType(0);
21497   unsigned NumElems = VT.getVectorNumElements();
21498
21499   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21500   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21501     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21502         SVOp->getMaskElt(j) >= 0)
21503       return false;
21504
21505   return true;
21506 }
21507
21508 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21509 /// same as extracting the low 128-bit part of 256-bit vector and then
21510 /// inserting the result into the high part of a new 256-bit vector
21511 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21512   EVT VT = SVOp->getValueType(0);
21513   unsigned NumElems = VT.getVectorNumElements();
21514
21515   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21516   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21517     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21518         SVOp->getMaskElt(j) >= 0)
21519       return false;
21520
21521   return true;
21522 }
21523
21524 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21525 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21526                                         TargetLowering::DAGCombinerInfo &DCI,
21527                                         const X86Subtarget* Subtarget) {
21528   SDLoc dl(N);
21529   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21530   SDValue V1 = SVOp->getOperand(0);
21531   SDValue V2 = SVOp->getOperand(1);
21532   EVT VT = SVOp->getValueType(0);
21533   unsigned NumElems = VT.getVectorNumElements();
21534
21535   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21536       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21537     //
21538     //                   0,0,0,...
21539     //                      |
21540     //    V      UNDEF    BUILD_VECTOR    UNDEF
21541     //     \      /           \           /
21542     //  CONCAT_VECTOR         CONCAT_VECTOR
21543     //         \                  /
21544     //          \                /
21545     //          RESULT: V + zero extended
21546     //
21547     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21548         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21549         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21550       return SDValue();
21551
21552     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21553       return SDValue();
21554
21555     // To match the shuffle mask, the first half of the mask should
21556     // be exactly the first vector, and all the rest a splat with the
21557     // first element of the second one.
21558     for (unsigned i = 0; i != NumElems/2; ++i)
21559       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21560           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21561         return SDValue();
21562
21563     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21564     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21565       if (Ld->hasNUsesOfValue(1, 0)) {
21566         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21567         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21568         SDValue ResNode =
21569           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21570                                   Ld->getMemoryVT(),
21571                                   Ld->getPointerInfo(),
21572                                   Ld->getAlignment(),
21573                                   false/*isVolatile*/, true/*ReadMem*/,
21574                                   false/*WriteMem*/);
21575
21576         // Make sure the newly-created LOAD is in the same position as Ld in
21577         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21578         // and update uses of Ld's output chain to use the TokenFactor.
21579         if (Ld->hasAnyUseOfValue(1)) {
21580           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21581                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21582           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21583           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21584                                  SDValue(ResNode.getNode(), 1));
21585         }
21586
21587         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
21588       }
21589     }
21590
21591     // Emit a zeroed vector and insert the desired subvector on its
21592     // first half.
21593     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21594     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21595     return DCI.CombineTo(N, InsV);
21596   }
21597
21598   //===--------------------------------------------------------------------===//
21599   // Combine some shuffles into subvector extracts and inserts:
21600   //
21601
21602   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21603   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21604     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21605     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21606     return DCI.CombineTo(N, InsV);
21607   }
21608
21609   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21610   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21611     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21612     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21613     return DCI.CombineTo(N, InsV);
21614   }
21615
21616   return SDValue();
21617 }
21618
21619 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21620 /// possible.
21621 ///
21622 /// This is the leaf of the recursive combinine below. When we have found some
21623 /// chain of single-use x86 shuffle instructions and accumulated the combined
21624 /// shuffle mask represented by them, this will try to pattern match that mask
21625 /// into either a single instruction if there is a special purpose instruction
21626 /// for this operation, or into a PSHUFB instruction which is a fully general
21627 /// instruction but should only be used to replace chains over a certain depth.
21628 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21629                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21630                                    TargetLowering::DAGCombinerInfo &DCI,
21631                                    const X86Subtarget *Subtarget) {
21632   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21633
21634   // Find the operand that enters the chain. Note that multiple uses are OK
21635   // here, we're not going to remove the operand we find.
21636   SDValue Input = Op.getOperand(0);
21637   while (Input.getOpcode() == ISD::BITCAST)
21638     Input = Input.getOperand(0);
21639
21640   MVT VT = Input.getSimpleValueType();
21641   MVT RootVT = Root.getSimpleValueType();
21642   SDLoc DL(Root);
21643
21644   // Just remove no-op shuffle masks.
21645   if (Mask.size() == 1) {
21646     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
21647                   /*AddTo*/ true);
21648     return true;
21649   }
21650
21651   // Use the float domain if the operand type is a floating point type.
21652   bool FloatDomain = VT.isFloatingPoint();
21653
21654   // For floating point shuffles, we don't have free copies in the shuffle
21655   // instructions or the ability to load as part of the instruction, so
21656   // canonicalize their shuffles to UNPCK or MOV variants.
21657   //
21658   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21659   // vectors because it can have a load folded into it that UNPCK cannot. This
21660   // doesn't preclude something switching to the shorter encoding post-RA.
21661   if (FloatDomain) {
21662     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
21663       bool Lo = Mask.equals(0, 0);
21664       unsigned Shuffle;
21665       MVT ShuffleVT;
21666       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21667       // is no slower than UNPCKLPD but has the option to fold the input operand
21668       // into even an unaligned memory load.
21669       if (Lo && Subtarget->hasSSE3()) {
21670         Shuffle = X86ISD::MOVDDUP;
21671         ShuffleVT = MVT::v2f64;
21672       } else {
21673         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21674         // than the UNPCK variants.
21675         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21676         ShuffleVT = MVT::v4f32;
21677       }
21678       if (Depth == 1 && Root->getOpcode() == Shuffle)
21679         return false; // Nothing to do!
21680       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21681       DCI.AddToWorklist(Op.getNode());
21682       if (Shuffle == X86ISD::MOVDDUP)
21683         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21684       else
21685         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21686       DCI.AddToWorklist(Op.getNode());
21687       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21688                     /*AddTo*/ true);
21689       return true;
21690     }
21691     if (Subtarget->hasSSE3() &&
21692         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
21693       bool Lo = Mask.equals(0, 0, 2, 2);
21694       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21695       MVT ShuffleVT = MVT::v4f32;
21696       if (Depth == 1 && Root->getOpcode() == Shuffle)
21697         return false; // Nothing to do!
21698       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21699       DCI.AddToWorklist(Op.getNode());
21700       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21701       DCI.AddToWorklist(Op.getNode());
21702       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21703                     /*AddTo*/ true);
21704       return true;
21705     }
21706     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
21707       bool Lo = Mask.equals(0, 0, 1, 1);
21708       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21709       MVT ShuffleVT = MVT::v4f32;
21710       if (Depth == 1 && Root->getOpcode() == Shuffle)
21711         return false; // Nothing to do!
21712       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21713       DCI.AddToWorklist(Op.getNode());
21714       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21715       DCI.AddToWorklist(Op.getNode());
21716       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21717                     /*AddTo*/ true);
21718       return true;
21719     }
21720   }
21721
21722   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21723   // variants as none of these have single-instruction variants that are
21724   // superior to the UNPCK formulation.
21725   if (!FloatDomain &&
21726       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
21727        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
21728        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
21729        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
21730                    15))) {
21731     bool Lo = Mask[0] == 0;
21732     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21733     if (Depth == 1 && Root->getOpcode() == Shuffle)
21734       return false; // Nothing to do!
21735     MVT ShuffleVT;
21736     switch (Mask.size()) {
21737     case 8:
21738       ShuffleVT = MVT::v8i16;
21739       break;
21740     case 16:
21741       ShuffleVT = MVT::v16i8;
21742       break;
21743     default:
21744       llvm_unreachable("Impossible mask size!");
21745     };
21746     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
21747     DCI.AddToWorklist(Op.getNode());
21748     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21749     DCI.AddToWorklist(Op.getNode());
21750     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21751                   /*AddTo*/ true);
21752     return true;
21753   }
21754
21755   // Don't try to re-form single instruction chains under any circumstances now
21756   // that we've done encoding canonicalization for them.
21757   if (Depth < 2)
21758     return false;
21759
21760   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21761   // can replace them with a single PSHUFB instruction profitably. Intel's
21762   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21763   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21764   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21765     SmallVector<SDValue, 16> PSHUFBMask;
21766     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
21767     int Ratio = 16 / Mask.size();
21768     for (unsigned i = 0; i < 16; ++i) {
21769       if (Mask[i / Ratio] == SM_SentinelUndef) {
21770         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21771         continue;
21772       }
21773       int M = Mask[i / Ratio] != SM_SentinelZero
21774                   ? Ratio * Mask[i / Ratio] + i % Ratio
21775                   : 255;
21776       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
21777     }
21778     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
21779     DCI.AddToWorklist(Op.getNode());
21780     SDValue PSHUFBMaskOp =
21781         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
21782     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21783     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
21784     DCI.AddToWorklist(Op.getNode());
21785     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
21786                   /*AddTo*/ true);
21787     return true;
21788   }
21789
21790   // Failed to find any combines.
21791   return false;
21792 }
21793
21794 /// \brief Fully generic combining of x86 shuffle instructions.
21795 ///
21796 /// This should be the last combine run over the x86 shuffle instructions. Once
21797 /// they have been fully optimized, this will recursively consider all chains
21798 /// of single-use shuffle instructions, build a generic model of the cumulative
21799 /// shuffle operation, and check for simpler instructions which implement this
21800 /// operation. We use this primarily for two purposes:
21801 ///
21802 /// 1) Collapse generic shuffles to specialized single instructions when
21803 ///    equivalent. In most cases, this is just an encoding size win, but
21804 ///    sometimes we will collapse multiple generic shuffles into a single
21805 ///    special-purpose shuffle.
21806 /// 2) Look for sequences of shuffle instructions with 3 or more total
21807 ///    instructions, and replace them with the slightly more expensive SSSE3
21808 ///    PSHUFB instruction if available. We do this as the last combining step
21809 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21810 ///    a suitable short sequence of other instructions. The PHUFB will either
21811 ///    use a register or have to read from memory and so is slightly (but only
21812 ///    slightly) more expensive than the other shuffle instructions.
21813 ///
21814 /// Because this is inherently a quadratic operation (for each shuffle in
21815 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21816 /// This should never be an issue in practice as the shuffle lowering doesn't
21817 /// produce sequences of more than 8 instructions.
21818 ///
21819 /// FIXME: We will currently miss some cases where the redundant shuffling
21820 /// would simplify under the threshold for PSHUFB formation because of
21821 /// combine-ordering. To fix this, we should do the redundant instruction
21822 /// combining in this recursive walk.
21823 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21824                                           ArrayRef<int> RootMask,
21825                                           int Depth, bool HasPSHUFB,
21826                                           SelectionDAG &DAG,
21827                                           TargetLowering::DAGCombinerInfo &DCI,
21828                                           const X86Subtarget *Subtarget) {
21829   // Bound the depth of our recursive combine because this is ultimately
21830   // quadratic in nature.
21831   if (Depth > 8)
21832     return false;
21833
21834   // Directly rip through bitcasts to find the underlying operand.
21835   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21836     Op = Op.getOperand(0);
21837
21838   MVT VT = Op.getSimpleValueType();
21839   if (!VT.isVector())
21840     return false; // Bail if we hit a non-vector.
21841   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
21842   // version should be added.
21843   if (VT.getSizeInBits() != 128)
21844     return false;
21845
21846   assert(Root.getSimpleValueType().isVector() &&
21847          "Shuffles operate on vector types!");
21848   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21849          "Can only combine shuffles of the same vector register size.");
21850
21851   if (!isTargetShuffle(Op.getOpcode()))
21852     return false;
21853   SmallVector<int, 16> OpMask;
21854   bool IsUnary;
21855   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21856   // We only can combine unary shuffles which we can decode the mask for.
21857   if (!HaveMask || !IsUnary)
21858     return false;
21859
21860   assert(VT.getVectorNumElements() == OpMask.size() &&
21861          "Different mask size from vector size!");
21862   assert(((RootMask.size() > OpMask.size() &&
21863            RootMask.size() % OpMask.size() == 0) ||
21864           (OpMask.size() > RootMask.size() &&
21865            OpMask.size() % RootMask.size() == 0) ||
21866           OpMask.size() == RootMask.size()) &&
21867          "The smaller number of elements must divide the larger.");
21868   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21869   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21870   assert(((RootRatio == 1 && OpRatio == 1) ||
21871           (RootRatio == 1) != (OpRatio == 1)) &&
21872          "Must not have a ratio for both incoming and op masks!");
21873
21874   SmallVector<int, 16> Mask;
21875   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21876
21877   // Merge this shuffle operation's mask into our accumulated mask. Note that
21878   // this shuffle's mask will be the first applied to the input, followed by the
21879   // root mask to get us all the way to the root value arrangement. The reason
21880   // for this order is that we are recursing up the operation chain.
21881   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21882     int RootIdx = i / RootRatio;
21883     if (RootMask[RootIdx] < 0) {
21884       // This is a zero or undef lane, we're done.
21885       Mask.push_back(RootMask[RootIdx]);
21886       continue;
21887     }
21888
21889     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21890     int OpIdx = RootMaskedIdx / OpRatio;
21891     if (OpMask[OpIdx] < 0) {
21892       // The incoming lanes are zero or undef, it doesn't matter which ones we
21893       // are using.
21894       Mask.push_back(OpMask[OpIdx]);
21895       continue;
21896     }
21897
21898     // Ok, we have non-zero lanes, map them through.
21899     Mask.push_back(OpMask[OpIdx] * OpRatio +
21900                    RootMaskedIdx % OpRatio);
21901   }
21902
21903   // See if we can recurse into the operand to combine more things.
21904   switch (Op.getOpcode()) {
21905     case X86ISD::PSHUFB:
21906       HasPSHUFB = true;
21907     case X86ISD::PSHUFD:
21908     case X86ISD::PSHUFHW:
21909     case X86ISD::PSHUFLW:
21910       if (Op.getOperand(0).hasOneUse() &&
21911           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21912                                         HasPSHUFB, DAG, DCI, Subtarget))
21913         return true;
21914       break;
21915
21916     case X86ISD::UNPCKL:
21917     case X86ISD::UNPCKH:
21918       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21919       // We can't check for single use, we have to check that this shuffle is the only user.
21920       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21921           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21922                                         HasPSHUFB, DAG, DCI, Subtarget))
21923           return true;
21924       break;
21925   }
21926
21927   // Minor canonicalization of the accumulated shuffle mask to make it easier
21928   // to match below. All this does is detect masks with squential pairs of
21929   // elements, and shrink them to the half-width mask. It does this in a loop
21930   // so it will reduce the size of the mask to the minimal width mask which
21931   // performs an equivalent shuffle.
21932   SmallVector<int, 16> WidenedMask;
21933   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21934     Mask = std::move(WidenedMask);
21935     WidenedMask.clear();
21936   }
21937
21938   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21939                                 Subtarget);
21940 }
21941
21942 /// \brief Get the PSHUF-style mask from PSHUF node.
21943 ///
21944 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21945 /// PSHUF-style masks that can be reused with such instructions.
21946 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21947   SmallVector<int, 4> Mask;
21948   bool IsUnary;
21949   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
21950   (void)HaveMask;
21951   assert(HaveMask);
21952
21953   switch (N.getOpcode()) {
21954   case X86ISD::PSHUFD:
21955     return Mask;
21956   case X86ISD::PSHUFLW:
21957     Mask.resize(4);
21958     return Mask;
21959   case X86ISD::PSHUFHW:
21960     Mask.erase(Mask.begin(), Mask.begin() + 4);
21961     for (int &M : Mask)
21962       M -= 4;
21963     return Mask;
21964   default:
21965     llvm_unreachable("No valid shuffle instruction found!");
21966   }
21967 }
21968
21969 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21970 ///
21971 /// We walk up the chain and look for a combinable shuffle, skipping over
21972 /// shuffles that we could hoist this shuffle's transformation past without
21973 /// altering anything.
21974 static SDValue
21975 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21976                              SelectionDAG &DAG,
21977                              TargetLowering::DAGCombinerInfo &DCI) {
21978   assert(N.getOpcode() == X86ISD::PSHUFD &&
21979          "Called with something other than an x86 128-bit half shuffle!");
21980   SDLoc DL(N);
21981
21982   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21983   // of the shuffles in the chain so that we can form a fresh chain to replace
21984   // this one.
21985   SmallVector<SDValue, 8> Chain;
21986   SDValue V = N.getOperand(0);
21987   for (; V.hasOneUse(); V = V.getOperand(0)) {
21988     switch (V.getOpcode()) {
21989     default:
21990       return SDValue(); // Nothing combined!
21991
21992     case ISD::BITCAST:
21993       // Skip bitcasts as we always know the type for the target specific
21994       // instructions.
21995       continue;
21996
21997     case X86ISD::PSHUFD:
21998       // Found another dword shuffle.
21999       break;
22000
22001     case X86ISD::PSHUFLW:
22002       // Check that the low words (being shuffled) are the identity in the
22003       // dword shuffle, and the high words are self-contained.
22004       if (Mask[0] != 0 || Mask[1] != 1 ||
22005           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22006         return SDValue();
22007
22008       Chain.push_back(V);
22009       continue;
22010
22011     case X86ISD::PSHUFHW:
22012       // Check that the high words (being shuffled) are the identity in the
22013       // dword shuffle, and the low words are self-contained.
22014       if (Mask[2] != 2 || Mask[3] != 3 ||
22015           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22016         return SDValue();
22017
22018       Chain.push_back(V);
22019       continue;
22020
22021     case X86ISD::UNPCKL:
22022     case X86ISD::UNPCKH:
22023       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22024       // shuffle into a preceding word shuffle.
22025       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
22026         return SDValue();
22027
22028       // Search for a half-shuffle which we can combine with.
22029       unsigned CombineOp =
22030           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22031       if (V.getOperand(0) != V.getOperand(1) ||
22032           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22033         return SDValue();
22034       Chain.push_back(V);
22035       V = V.getOperand(0);
22036       do {
22037         switch (V.getOpcode()) {
22038         default:
22039           return SDValue(); // Nothing to combine.
22040
22041         case X86ISD::PSHUFLW:
22042         case X86ISD::PSHUFHW:
22043           if (V.getOpcode() == CombineOp)
22044             break;
22045
22046           Chain.push_back(V);
22047
22048           // Fallthrough!
22049         case ISD::BITCAST:
22050           V = V.getOperand(0);
22051           continue;
22052         }
22053         break;
22054       } while (V.hasOneUse());
22055       break;
22056     }
22057     // Break out of the loop if we break out of the switch.
22058     break;
22059   }
22060
22061   if (!V.hasOneUse())
22062     // We fell out of the loop without finding a viable combining instruction.
22063     return SDValue();
22064
22065   // Merge this node's mask and our incoming mask.
22066   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22067   for (int &M : Mask)
22068     M = VMask[M];
22069   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22070                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22071
22072   // Rebuild the chain around this new shuffle.
22073   while (!Chain.empty()) {
22074     SDValue W = Chain.pop_back_val();
22075
22076     if (V.getValueType() != W.getOperand(0).getValueType())
22077       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
22078
22079     switch (W.getOpcode()) {
22080     default:
22081       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22082
22083     case X86ISD::UNPCKL:
22084     case X86ISD::UNPCKH:
22085       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22086       break;
22087
22088     case X86ISD::PSHUFD:
22089     case X86ISD::PSHUFLW:
22090     case X86ISD::PSHUFHW:
22091       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22092       break;
22093     }
22094   }
22095   if (V.getValueType() != N.getValueType())
22096     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
22097
22098   // Return the new chain to replace N.
22099   return V;
22100 }
22101
22102 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22103 ///
22104 /// We walk up the chain, skipping shuffles of the other half and looking
22105 /// through shuffles which switch halves trying to find a shuffle of the same
22106 /// pair of dwords.
22107 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22108                                         SelectionDAG &DAG,
22109                                         TargetLowering::DAGCombinerInfo &DCI) {
22110   assert(
22111       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22112       "Called with something other than an x86 128-bit half shuffle!");
22113   SDLoc DL(N);
22114   unsigned CombineOpcode = N.getOpcode();
22115
22116   // Walk up a single-use chain looking for a combinable shuffle.
22117   SDValue V = N.getOperand(0);
22118   for (; V.hasOneUse(); V = V.getOperand(0)) {
22119     switch (V.getOpcode()) {
22120     default:
22121       return false; // Nothing combined!
22122
22123     case ISD::BITCAST:
22124       // Skip bitcasts as we always know the type for the target specific
22125       // instructions.
22126       continue;
22127
22128     case X86ISD::PSHUFLW:
22129     case X86ISD::PSHUFHW:
22130       if (V.getOpcode() == CombineOpcode)
22131         break;
22132
22133       // Other-half shuffles are no-ops.
22134       continue;
22135     }
22136     // Break out of the loop if we break out of the switch.
22137     break;
22138   }
22139
22140   if (!V.hasOneUse())
22141     // We fell out of the loop without finding a viable combining instruction.
22142     return false;
22143
22144   // Combine away the bottom node as its shuffle will be accumulated into
22145   // a preceding shuffle.
22146   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22147
22148   // Record the old value.
22149   SDValue Old = V;
22150
22151   // Merge this node's mask and our incoming mask (adjusted to account for all
22152   // the pshufd instructions encountered).
22153   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22154   for (int &M : Mask)
22155     M = VMask[M];
22156   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22157                   getV4X86ShuffleImm8ForMask(Mask, DAG));
22158
22159   // Check that the shuffles didn't cancel each other out. If not, we need to
22160   // combine to the new one.
22161   if (Old != V)
22162     // Replace the combinable shuffle with the combined one, updating all users
22163     // so that we re-evaluate the chain here.
22164     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22165
22166   return true;
22167 }
22168
22169 /// \brief Try to combine x86 target specific shuffles.
22170 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22171                                            TargetLowering::DAGCombinerInfo &DCI,
22172                                            const X86Subtarget *Subtarget) {
22173   SDLoc DL(N);
22174   MVT VT = N.getSimpleValueType();
22175   SmallVector<int, 4> Mask;
22176
22177   switch (N.getOpcode()) {
22178   case X86ISD::PSHUFD:
22179   case X86ISD::PSHUFLW:
22180   case X86ISD::PSHUFHW:
22181     Mask = getPSHUFShuffleMask(N);
22182     assert(Mask.size() == 4);
22183     break;
22184   default:
22185     return SDValue();
22186   }
22187
22188   // Nuke no-op shuffles that show up after combining.
22189   if (isNoopShuffleMask(Mask))
22190     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22191
22192   // Look for simplifications involving one or two shuffle instructions.
22193   SDValue V = N.getOperand(0);
22194   switch (N.getOpcode()) {
22195   default:
22196     break;
22197   case X86ISD::PSHUFLW:
22198   case X86ISD::PSHUFHW:
22199     assert(VT == MVT::v8i16);
22200     (void)VT;
22201
22202     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22203       return SDValue(); // We combined away this shuffle, so we're done.
22204
22205     // See if this reduces to a PSHUFD which is no more expensive and can
22206     // combine with more operations. Note that it has to at least flip the
22207     // dwords as otherwise it would have been removed as a no-op.
22208     if (Mask[0] == 2 && Mask[1] == 3 && Mask[2] == 0 && Mask[3] == 1) {
22209       int DMask[] = {0, 1, 2, 3};
22210       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22211       DMask[DOffset + 0] = DOffset + 1;
22212       DMask[DOffset + 1] = DOffset + 0;
22213       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
22214       DCI.AddToWorklist(V.getNode());
22215       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
22216                       getV4X86ShuffleImm8ForMask(DMask, DAG));
22217       DCI.AddToWorklist(V.getNode());
22218       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
22219     }
22220
22221     // Look for shuffle patterns which can be implemented as a single unpack.
22222     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22223     // only works when we have a PSHUFD followed by two half-shuffles.
22224     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22225         (V.getOpcode() == X86ISD::PSHUFLW ||
22226          V.getOpcode() == X86ISD::PSHUFHW) &&
22227         V.getOpcode() != N.getOpcode() &&
22228         V.hasOneUse()) {
22229       SDValue D = V.getOperand(0);
22230       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22231         D = D.getOperand(0);
22232       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22233         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22234         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22235         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22236         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22237         int WordMask[8];
22238         for (int i = 0; i < 4; ++i) {
22239           WordMask[i + NOffset] = Mask[i] + NOffset;
22240           WordMask[i + VOffset] = VMask[i] + VOffset;
22241         }
22242         // Map the word mask through the DWord mask.
22243         int MappedMask[8];
22244         for (int i = 0; i < 8; ++i)
22245           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22246         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
22247         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
22248         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
22249                        std::begin(UnpackLoMask)) ||
22250             std::equal(std::begin(MappedMask), std::end(MappedMask),
22251                        std::begin(UnpackHiMask))) {
22252           // We can replace all three shuffles with an unpack.
22253           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
22254           DCI.AddToWorklist(V.getNode());
22255           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22256                                                 : X86ISD::UNPCKH,
22257                              DL, MVT::v8i16, V, V);
22258         }
22259       }
22260     }
22261
22262     break;
22263
22264   case X86ISD::PSHUFD:
22265     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22266       return NewN;
22267
22268     break;
22269   }
22270
22271   return SDValue();
22272 }
22273
22274 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22275 ///
22276 /// We combine this directly on the abstract vector shuffle nodes so it is
22277 /// easier to generically match. We also insert dummy vector shuffle nodes for
22278 /// the operands which explicitly discard the lanes which are unused by this
22279 /// operation to try to flow through the rest of the combiner the fact that
22280 /// they're unused.
22281 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22282   SDLoc DL(N);
22283   EVT VT = N->getValueType(0);
22284
22285   // We only handle target-independent shuffles.
22286   // FIXME: It would be easy and harmless to use the target shuffle mask
22287   // extraction tool to support more.
22288   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22289     return SDValue();
22290
22291   auto *SVN = cast<ShuffleVectorSDNode>(N);
22292   ArrayRef<int> Mask = SVN->getMask();
22293   SDValue V1 = N->getOperand(0);
22294   SDValue V2 = N->getOperand(1);
22295
22296   // We require the first shuffle operand to be the SUB node, and the second to
22297   // be the ADD node.
22298   // FIXME: We should support the commuted patterns.
22299   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22300     return SDValue();
22301
22302   // If there are other uses of these operations we can't fold them.
22303   if (!V1->hasOneUse() || !V2->hasOneUse())
22304     return SDValue();
22305
22306   // Ensure that both operations have the same operands. Note that we can
22307   // commute the FADD operands.
22308   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22309   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22310       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22311     return SDValue();
22312
22313   // We're looking for blends between FADD and FSUB nodes. We insist on these
22314   // nodes being lined up in a specific expected pattern.
22315   if (!(isShuffleEquivalent(Mask, 0, 3) ||
22316         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
22317         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
22318     return SDValue();
22319
22320   // Only specific types are legal at this point, assert so we notice if and
22321   // when these change.
22322   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22323           VT == MVT::v4f64) &&
22324          "Unknown vector type encountered!");
22325
22326   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22327 }
22328
22329 /// PerformShuffleCombine - Performs several different shuffle combines.
22330 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22331                                      TargetLowering::DAGCombinerInfo &DCI,
22332                                      const X86Subtarget *Subtarget) {
22333   SDLoc dl(N);
22334   SDValue N0 = N->getOperand(0);
22335   SDValue N1 = N->getOperand(1);
22336   EVT VT = N->getValueType(0);
22337
22338   // Don't create instructions with illegal types after legalize types has run.
22339   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22340   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22341     return SDValue();
22342
22343   // If we have legalized the vector types, look for blends of FADD and FSUB
22344   // nodes that we can fuse into an ADDSUB node.
22345   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22346     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22347       return AddSub;
22348
22349   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22350   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22351       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22352     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22353
22354   // During Type Legalization, when promoting illegal vector types,
22355   // the backend might introduce new shuffle dag nodes and bitcasts.
22356   //
22357   // This code performs the following transformation:
22358   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22359   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22360   //
22361   // We do this only if both the bitcast and the BINOP dag nodes have
22362   // one use. Also, perform this transformation only if the new binary
22363   // operation is legal. This is to avoid introducing dag nodes that
22364   // potentially need to be further expanded (or custom lowered) into a
22365   // less optimal sequence of dag nodes.
22366   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22367       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22368       N0.getOpcode() == ISD::BITCAST) {
22369     SDValue BC0 = N0.getOperand(0);
22370     EVT SVT = BC0.getValueType();
22371     unsigned Opcode = BC0.getOpcode();
22372     unsigned NumElts = VT.getVectorNumElements();
22373     
22374     if (BC0.hasOneUse() && SVT.isVector() &&
22375         SVT.getVectorNumElements() * 2 == NumElts &&
22376         TLI.isOperationLegal(Opcode, VT)) {
22377       bool CanFold = false;
22378       switch (Opcode) {
22379       default : break;
22380       case ISD::ADD :
22381       case ISD::FADD :
22382       case ISD::SUB :
22383       case ISD::FSUB :
22384       case ISD::MUL :
22385       case ISD::FMUL :
22386         CanFold = true;
22387       }
22388
22389       unsigned SVTNumElts = SVT.getVectorNumElements();
22390       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22391       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22392         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22393       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22394         CanFold = SVOp->getMaskElt(i) < 0;
22395
22396       if (CanFold) {
22397         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
22398         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
22399         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22400         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22401       }
22402     }
22403   }
22404
22405   // Only handle 128 wide vector from here on.
22406   if (!VT.is128BitVector())
22407     return SDValue();
22408
22409   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22410   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22411   // consecutive, non-overlapping, and in the right order.
22412   SmallVector<SDValue, 16> Elts;
22413   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22414     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22415
22416   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
22417   if (LD.getNode())
22418     return LD;
22419
22420   if (isTargetShuffle(N->getOpcode())) {
22421     SDValue Shuffle =
22422         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22423     if (Shuffle.getNode())
22424       return Shuffle;
22425
22426     // Try recursively combining arbitrary sequences of x86 shuffle
22427     // instructions into higher-order shuffles. We do this after combining
22428     // specific PSHUF instruction sequences into their minimal form so that we
22429     // can evaluate how many specialized shuffle instructions are involved in
22430     // a particular chain.
22431     SmallVector<int, 1> NonceMask; // Just a placeholder.
22432     NonceMask.push_back(0);
22433     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22434                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22435                                       DCI, Subtarget))
22436       return SDValue(); // This routine will use CombineTo to replace N.
22437   }
22438
22439   return SDValue();
22440 }
22441
22442 /// PerformTruncateCombine - Converts truncate operation to
22443 /// a sequence of vector shuffle operations.
22444 /// It is possible when we truncate 256-bit vector to 128-bit vector
22445 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
22446                                       TargetLowering::DAGCombinerInfo &DCI,
22447                                       const X86Subtarget *Subtarget)  {
22448   return SDValue();
22449 }
22450
22451 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22452 /// specific shuffle of a load can be folded into a single element load.
22453 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22454 /// shuffles have been custom lowered so we need to handle those here.
22455 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22456                                          TargetLowering::DAGCombinerInfo &DCI) {
22457   if (DCI.isBeforeLegalizeOps())
22458     return SDValue();
22459
22460   SDValue InVec = N->getOperand(0);
22461   SDValue EltNo = N->getOperand(1);
22462
22463   if (!isa<ConstantSDNode>(EltNo))
22464     return SDValue();
22465
22466   EVT OriginalVT = InVec.getValueType();
22467
22468   if (InVec.getOpcode() == ISD::BITCAST) {
22469     // Don't duplicate a load with other uses.
22470     if (!InVec.hasOneUse())
22471       return SDValue();
22472     EVT BCVT = InVec.getOperand(0).getValueType();
22473     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22474       return SDValue();
22475     InVec = InVec.getOperand(0);
22476   }
22477
22478   EVT CurrentVT = InVec.getValueType();
22479
22480   if (!isTargetShuffle(InVec.getOpcode()))
22481     return SDValue();
22482
22483   // Don't duplicate a load with other uses.
22484   if (!InVec.hasOneUse())
22485     return SDValue();
22486
22487   SmallVector<int, 16> ShuffleMask;
22488   bool UnaryShuffle;
22489   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22490                             ShuffleMask, UnaryShuffle))
22491     return SDValue();
22492
22493   // Select the input vector, guarding against out of range extract vector.
22494   unsigned NumElems = CurrentVT.getVectorNumElements();
22495   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22496   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22497   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22498                                          : InVec.getOperand(1);
22499
22500   // If inputs to shuffle are the same for both ops, then allow 2 uses
22501   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22502
22503   if (LdNode.getOpcode() == ISD::BITCAST) {
22504     // Don't duplicate a load with other uses.
22505     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22506       return SDValue();
22507
22508     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22509     LdNode = LdNode.getOperand(0);
22510   }
22511
22512   if (!ISD::isNormalLoad(LdNode.getNode()))
22513     return SDValue();
22514
22515   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22516
22517   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22518     return SDValue();
22519
22520   EVT EltVT = N->getValueType(0);
22521   // If there's a bitcast before the shuffle, check if the load type and
22522   // alignment is valid.
22523   unsigned Align = LN0->getAlignment();
22524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22525   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
22526       EltVT.getTypeForEVT(*DAG.getContext()));
22527
22528   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22529     return SDValue();
22530
22531   // All checks match so transform back to vector_shuffle so that DAG combiner
22532   // can finish the job
22533   SDLoc dl(N);
22534
22535   // Create shuffle node taking into account the case that its a unary shuffle
22536   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22537                                    : InVec.getOperand(1);
22538   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22539                                  InVec.getOperand(0), Shuffle,
22540                                  &ShuffleMask[0]);
22541   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
22542   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22543                      EltNo);
22544 }
22545
22546 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22547 /// generation and convert it from being a bunch of shuffles and extracts
22548 /// to a simple store and scalar loads to extract the elements.
22549 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22550                                          TargetLowering::DAGCombinerInfo &DCI) {
22551   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
22552   if (NewOp.getNode())
22553     return NewOp;
22554
22555   SDValue InputVector = N->getOperand(0);
22556
22557   // Detect whether we are trying to convert from mmx to i32 and the bitcast
22558   // from mmx to v2i32 has a single usage.
22559   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
22560       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
22561       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
22562     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22563                        N->getValueType(0),
22564                        InputVector.getNode()->getOperand(0));
22565
22566   // Only operate on vectors of 4 elements, where the alternative shuffling
22567   // gets to be more expensive.
22568   if (InputVector.getValueType() != MVT::v4i32)
22569     return SDValue();
22570
22571   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22572   // single use which is a sign-extend or zero-extend, and all elements are
22573   // used.
22574   SmallVector<SDNode *, 4> Uses;
22575   unsigned ExtractedElements = 0;
22576   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22577        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22578     if (UI.getUse().getResNo() != InputVector.getResNo())
22579       return SDValue();
22580
22581     SDNode *Extract = *UI;
22582     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22583       return SDValue();
22584
22585     if (Extract->getValueType(0) != MVT::i32)
22586       return SDValue();
22587     if (!Extract->hasOneUse())
22588       return SDValue();
22589     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22590         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22591       return SDValue();
22592     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22593       return SDValue();
22594
22595     // Record which element was extracted.
22596     ExtractedElements |=
22597       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22598
22599     Uses.push_back(Extract);
22600   }
22601
22602   // If not all the elements were used, this may not be worthwhile.
22603   if (ExtractedElements != 15)
22604     return SDValue();
22605
22606   // Ok, we've now decided to do the transformation.
22607   SDLoc dl(InputVector);
22608
22609   // Store the value to a temporary stack slot.
22610   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22611   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22612                             MachinePointerInfo(), false, false, 0);
22613
22614   // Replace each use (extract) with a load of the appropriate element.
22615   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22616        UE = Uses.end(); UI != UE; ++UI) {
22617     SDNode *Extract = *UI;
22618
22619     // cOMpute the element's address.
22620     SDValue Idx = Extract->getOperand(1);
22621     unsigned EltSize =
22622         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
22623     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
22624     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22625     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
22626
22627     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
22628                                      StackPtr, OffsetVal);
22629
22630     // Load the scalar.
22631     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
22632                                      ScalarAddr, MachinePointerInfo(),
22633                                      false, false, false, 0);
22634
22635     // Replace the exact with the load.
22636     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
22637   }
22638
22639   // The replacement was made in place; don't return anything.
22640   return SDValue();
22641 }
22642
22643 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22644 static std::pair<unsigned, bool>
22645 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22646                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22647   if (!VT.isVector())
22648     return std::make_pair(0, false);
22649
22650   bool NeedSplit = false;
22651   switch (VT.getSimpleVT().SimpleTy) {
22652   default: return std::make_pair(0, false);
22653   case MVT::v32i8:
22654   case MVT::v16i16:
22655   case MVT::v8i32:
22656     if (!Subtarget->hasAVX2())
22657       NeedSplit = true;
22658     if (!Subtarget->hasAVX())
22659       return std::make_pair(0, false);
22660     break;
22661   case MVT::v16i8:
22662   case MVT::v8i16:
22663   case MVT::v4i32:
22664     if (!Subtarget->hasSSE2())
22665       return std::make_pair(0, false);
22666   }
22667
22668   // SSE2 has only a small subset of the operations.
22669   bool hasUnsigned = Subtarget->hasSSE41() ||
22670                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22671   bool hasSigned = Subtarget->hasSSE41() ||
22672                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22673
22674   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22675
22676   unsigned Opc = 0;
22677   // Check for x CC y ? x : y.
22678   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22679       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22680     switch (CC) {
22681     default: break;
22682     case ISD::SETULT:
22683     case ISD::SETULE:
22684       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22685     case ISD::SETUGT:
22686     case ISD::SETUGE:
22687       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22688     case ISD::SETLT:
22689     case ISD::SETLE:
22690       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22691     case ISD::SETGT:
22692     case ISD::SETGE:
22693       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22694     }
22695   // Check for x CC y ? y : x -- a min/max with reversed arms.
22696   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22697              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22698     switch (CC) {
22699     default: break;
22700     case ISD::SETULT:
22701     case ISD::SETULE:
22702       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
22703     case ISD::SETUGT:
22704     case ISD::SETUGE:
22705       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
22706     case ISD::SETLT:
22707     case ISD::SETLE:
22708       Opc = hasSigned ? X86ISD::SMAX : 0; break;
22709     case ISD::SETGT:
22710     case ISD::SETGE:
22711       Opc = hasSigned ? X86ISD::SMIN : 0; break;
22712     }
22713   }
22714
22715   return std::make_pair(Opc, NeedSplit);
22716 }
22717
22718 static SDValue
22719 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22720                                       const X86Subtarget *Subtarget) {
22721   SDLoc dl(N);
22722   SDValue Cond = N->getOperand(0);
22723   SDValue LHS = N->getOperand(1);
22724   SDValue RHS = N->getOperand(2);
22725
22726   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22727     SDValue CondSrc = Cond->getOperand(0);
22728     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22729       Cond = CondSrc->getOperand(0);
22730   }
22731
22732   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22733     return SDValue();
22734
22735   // A vselect where all conditions and data are constants can be optimized into
22736   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22737   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22738       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22739     return SDValue();
22740
22741   unsigned MaskValue = 0;
22742   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22743     return SDValue();
22744
22745   MVT VT = N->getSimpleValueType(0);
22746   unsigned NumElems = VT.getVectorNumElements();
22747   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22748   for (unsigned i = 0; i < NumElems; ++i) {
22749     // Be sure we emit undef where we can.
22750     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22751       ShuffleMask[i] = -1;
22752     else
22753       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22754   }
22755
22756   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22757   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22758     return SDValue();
22759   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22760 }
22761
22762 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22763 /// nodes.
22764 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22765                                     TargetLowering::DAGCombinerInfo &DCI,
22766                                     const X86Subtarget *Subtarget) {
22767   SDLoc DL(N);
22768   SDValue Cond = N->getOperand(0);
22769   // Get the LHS/RHS of the select.
22770   SDValue LHS = N->getOperand(1);
22771   SDValue RHS = N->getOperand(2);
22772   EVT VT = LHS.getValueType();
22773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22774
22775   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22776   // instructions match the semantics of the common C idiom x<y?x:y but not
22777   // x<=y?x:y, because of how they handle negative zero (which can be
22778   // ignored in unsafe-math mode).
22779   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22780       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
22781       (Subtarget->hasSSE2() ||
22782        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22783     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22784
22785     unsigned Opcode = 0;
22786     // Check for x CC y ? x : y.
22787     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22788         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22789       switch (CC) {
22790       default: break;
22791       case ISD::SETULT:
22792         // Converting this to a min would handle NaNs incorrectly, and swapping
22793         // the operands would cause it to handle comparisons between positive
22794         // and negative zero incorrectly.
22795         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22796           if (!DAG.getTarget().Options.UnsafeFPMath &&
22797               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22798             break;
22799           std::swap(LHS, RHS);
22800         }
22801         Opcode = X86ISD::FMIN;
22802         break;
22803       case ISD::SETOLE:
22804         // Converting this to a min would handle comparisons between positive
22805         // and negative zero incorrectly.
22806         if (!DAG.getTarget().Options.UnsafeFPMath &&
22807             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22808           break;
22809         Opcode = X86ISD::FMIN;
22810         break;
22811       case ISD::SETULE:
22812         // Converting this to a min would handle both negative zeros and NaNs
22813         // incorrectly, but we can swap the operands to fix both.
22814         std::swap(LHS, RHS);
22815       case ISD::SETOLT:
22816       case ISD::SETLT:
22817       case ISD::SETLE:
22818         Opcode = X86ISD::FMIN;
22819         break;
22820
22821       case ISD::SETOGE:
22822         // Converting this to a max would handle comparisons between positive
22823         // and negative zero incorrectly.
22824         if (!DAG.getTarget().Options.UnsafeFPMath &&
22825             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22826           break;
22827         Opcode = X86ISD::FMAX;
22828         break;
22829       case ISD::SETUGT:
22830         // Converting this to a max would handle NaNs incorrectly, and swapping
22831         // the operands would cause it to handle comparisons between positive
22832         // and negative zero incorrectly.
22833         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22834           if (!DAG.getTarget().Options.UnsafeFPMath &&
22835               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22836             break;
22837           std::swap(LHS, RHS);
22838         }
22839         Opcode = X86ISD::FMAX;
22840         break;
22841       case ISD::SETUGE:
22842         // Converting this to a max would handle both negative zeros and NaNs
22843         // incorrectly, but we can swap the operands to fix both.
22844         std::swap(LHS, RHS);
22845       case ISD::SETOGT:
22846       case ISD::SETGT:
22847       case ISD::SETGE:
22848         Opcode = X86ISD::FMAX;
22849         break;
22850       }
22851     // Check for x CC y ? y : x -- a min/max with reversed arms.
22852     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22853                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22854       switch (CC) {
22855       default: break;
22856       case ISD::SETOGE:
22857         // Converting this to a min would handle comparisons between positive
22858         // and negative zero incorrectly, and swapping the operands would
22859         // cause it to handle NaNs incorrectly.
22860         if (!DAG.getTarget().Options.UnsafeFPMath &&
22861             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22862           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22863             break;
22864           std::swap(LHS, RHS);
22865         }
22866         Opcode = X86ISD::FMIN;
22867         break;
22868       case ISD::SETUGT:
22869         // Converting this to a min would handle NaNs incorrectly.
22870         if (!DAG.getTarget().Options.UnsafeFPMath &&
22871             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22872           break;
22873         Opcode = X86ISD::FMIN;
22874         break;
22875       case ISD::SETUGE:
22876         // Converting this to a min would handle both negative zeros and NaNs
22877         // incorrectly, but we can swap the operands to fix both.
22878         std::swap(LHS, RHS);
22879       case ISD::SETOGT:
22880       case ISD::SETGT:
22881       case ISD::SETGE:
22882         Opcode = X86ISD::FMIN;
22883         break;
22884
22885       case ISD::SETULT:
22886         // Converting this to a max would handle NaNs incorrectly.
22887         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22888           break;
22889         Opcode = X86ISD::FMAX;
22890         break;
22891       case ISD::SETOLE:
22892         // Converting this to a max would handle comparisons between positive
22893         // and negative zero incorrectly, and swapping the operands would
22894         // cause it to handle NaNs incorrectly.
22895         if (!DAG.getTarget().Options.UnsafeFPMath &&
22896             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22897           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22898             break;
22899           std::swap(LHS, RHS);
22900         }
22901         Opcode = X86ISD::FMAX;
22902         break;
22903       case ISD::SETULE:
22904         // Converting this to a max would handle both negative zeros and NaNs
22905         // incorrectly, but we can swap the operands to fix both.
22906         std::swap(LHS, RHS);
22907       case ISD::SETOLT:
22908       case ISD::SETLT:
22909       case ISD::SETLE:
22910         Opcode = X86ISD::FMAX;
22911         break;
22912       }
22913     }
22914
22915     if (Opcode)
22916       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22917   }
22918
22919   EVT CondVT = Cond.getValueType();
22920   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22921       CondVT.getVectorElementType() == MVT::i1) {
22922     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22923     // lowering on KNL. In this case we convert it to
22924     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22925     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22926     // Since SKX these selects have a proper lowering.
22927     EVT OpVT = LHS.getValueType();
22928     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22929         (OpVT.getVectorElementType() == MVT::i8 ||
22930          OpVT.getVectorElementType() == MVT::i16) &&
22931         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22932       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22933       DCI.AddToWorklist(Cond.getNode());
22934       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22935     }
22936   }
22937   // If this is a select between two integer constants, try to do some
22938   // optimizations.
22939   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22940     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22941       // Don't do this for crazy integer types.
22942       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22943         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22944         // so that TrueC (the true value) is larger than FalseC.
22945         bool NeedsCondInvert = false;
22946
22947         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22948             // Efficiently invertible.
22949             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22950              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22951               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22952           NeedsCondInvert = true;
22953           std::swap(TrueC, FalseC);
22954         }
22955
22956         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22957         if (FalseC->getAPIntValue() == 0 &&
22958             TrueC->getAPIntValue().isPowerOf2()) {
22959           if (NeedsCondInvert) // Invert the condition if needed.
22960             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22961                                DAG.getConstant(1, Cond.getValueType()));
22962
22963           // Zero extend the condition if needed.
22964           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22965
22966           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22967           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22968                              DAG.getConstant(ShAmt, MVT::i8));
22969         }
22970
22971         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22972         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22973           if (NeedsCondInvert) // Invert the condition if needed.
22974             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22975                                DAG.getConstant(1, Cond.getValueType()));
22976
22977           // Zero extend the condition if needed.
22978           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22979                              FalseC->getValueType(0), Cond);
22980           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22981                              SDValue(FalseC, 0));
22982         }
22983
22984         // Optimize cases that will turn into an LEA instruction.  This requires
22985         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22986         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22987           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22988           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22989
22990           bool isFastMultiplier = false;
22991           if (Diff < 10) {
22992             switch ((unsigned char)Diff) {
22993               default: break;
22994               case 1:  // result = add base, cond
22995               case 2:  // result = lea base(    , cond*2)
22996               case 3:  // result = lea base(cond, cond*2)
22997               case 4:  // result = lea base(    , cond*4)
22998               case 5:  // result = lea base(cond, cond*4)
22999               case 8:  // result = lea base(    , cond*8)
23000               case 9:  // result = lea base(cond, cond*8)
23001                 isFastMultiplier = true;
23002                 break;
23003             }
23004           }
23005
23006           if (isFastMultiplier) {
23007             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23008             if (NeedsCondInvert) // Invert the condition if needed.
23009               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23010                                  DAG.getConstant(1, Cond.getValueType()));
23011
23012             // Zero extend the condition if needed.
23013             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23014                                Cond);
23015             // Scale the condition by the difference.
23016             if (Diff != 1)
23017               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23018                                  DAG.getConstant(Diff, Cond.getValueType()));
23019
23020             // Add the base if non-zero.
23021             if (FalseC->getAPIntValue() != 0)
23022               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23023                                  SDValue(FalseC, 0));
23024             return Cond;
23025           }
23026         }
23027       }
23028   }
23029
23030   // Canonicalize max and min:
23031   // (x > y) ? x : y -> (x >= y) ? x : y
23032   // (x < y) ? x : y -> (x <= y) ? x : y
23033   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23034   // the need for an extra compare
23035   // against zero. e.g.
23036   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23037   // subl   %esi, %edi
23038   // testl  %edi, %edi
23039   // movl   $0, %eax
23040   // cmovgl %edi, %eax
23041   // =>
23042   // xorl   %eax, %eax
23043   // subl   %esi, $edi
23044   // cmovsl %eax, %edi
23045   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23046       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23047       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23048     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23049     switch (CC) {
23050     default: break;
23051     case ISD::SETLT:
23052     case ISD::SETGT: {
23053       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23054       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23055                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23056       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23057     }
23058     }
23059   }
23060
23061   // Early exit check
23062   if (!TLI.isTypeLegal(VT))
23063     return SDValue();
23064
23065   // Match VSELECTs into subs with unsigned saturation.
23066   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23067       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23068       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23069        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23070     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23071
23072     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23073     // left side invert the predicate to simplify logic below.
23074     SDValue Other;
23075     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23076       Other = RHS;
23077       CC = ISD::getSetCCInverse(CC, true);
23078     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23079       Other = LHS;
23080     }
23081
23082     if (Other.getNode() && Other->getNumOperands() == 2 &&
23083         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23084       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23085       SDValue CondRHS = Cond->getOperand(1);
23086
23087       // Look for a general sub with unsigned saturation first.
23088       // x >= y ? x-y : 0 --> subus x, y
23089       // x >  y ? x-y : 0 --> subus x, y
23090       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23091           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23092         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23093
23094       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23095         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23096           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23097             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23098               // If the RHS is a constant we have to reverse the const
23099               // canonicalization.
23100               // x > C-1 ? x+-C : 0 --> subus x, C
23101               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23102                   CondRHSConst->getAPIntValue() ==
23103                       (-OpRHSConst->getAPIntValue() - 1))
23104                 return DAG.getNode(
23105                     X86ISD::SUBUS, DL, VT, OpLHS,
23106                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
23107
23108           // Another special case: If C was a sign bit, the sub has been
23109           // canonicalized into a xor.
23110           // FIXME: Would it be better to use computeKnownBits to determine
23111           //        whether it's safe to decanonicalize the xor?
23112           // x s< 0 ? x^C : 0 --> subus x, C
23113           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23114               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23115               OpRHSConst->getAPIntValue().isSignBit())
23116             // Note that we have to rebuild the RHS constant here to ensure we
23117             // don't rely on particular values of undef lanes.
23118             return DAG.getNode(
23119                 X86ISD::SUBUS, DL, VT, OpLHS,
23120                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
23121         }
23122     }
23123   }
23124
23125   // Try to match a min/max vector operation.
23126   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
23127     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
23128     unsigned Opc = ret.first;
23129     bool NeedSplit = ret.second;
23130
23131     if (Opc && NeedSplit) {
23132       unsigned NumElems = VT.getVectorNumElements();
23133       // Extract the LHS vectors
23134       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
23135       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
23136
23137       // Extract the RHS vectors
23138       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
23139       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
23140
23141       // Create min/max for each subvector
23142       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
23143       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
23144
23145       // Merge the result
23146       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
23147     } else if (Opc)
23148       return DAG.getNode(Opc, DL, VT, LHS, RHS);
23149   }
23150
23151   // Simplify vector selection if condition value type matches vselect
23152   // operand type
23153   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23154     assert(Cond.getValueType().isVector() &&
23155            "vector select expects a vector selector!");
23156
23157     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23158     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23159
23160     // Try invert the condition if true value is not all 1s and false value
23161     // is not all 0s.
23162     if (!TValIsAllOnes && !FValIsAllZeros &&
23163         // Check if the selector will be produced by CMPP*/PCMP*
23164         Cond.getOpcode() == ISD::SETCC &&
23165         // Check if SETCC has already been promoted
23166         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
23167       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23168       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23169
23170       if (TValIsAllZeros || FValIsAllOnes) {
23171         SDValue CC = Cond.getOperand(2);
23172         ISD::CondCode NewCC =
23173           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23174                                Cond.getOperand(0).getValueType().isInteger());
23175         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23176         std::swap(LHS, RHS);
23177         TValIsAllOnes = FValIsAllOnes;
23178         FValIsAllZeros = TValIsAllZeros;
23179       }
23180     }
23181
23182     if (TValIsAllOnes || FValIsAllZeros) {
23183       SDValue Ret;
23184
23185       if (TValIsAllOnes && FValIsAllZeros)
23186         Ret = Cond;
23187       else if (TValIsAllOnes)
23188         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
23189                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
23190       else if (FValIsAllZeros)
23191         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23192                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
23193
23194       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
23195     }
23196   }
23197
23198   // If we know that this node is legal then we know that it is going to be
23199   // matched by one of the SSE/AVX BLEND instructions. These instructions only
23200   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
23201   // to simplify previous instructions.
23202   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23203       !DCI.isBeforeLegalize() &&
23204       // We explicitly check against v8i16 and v16i16 because, although
23205       // they're marked as Custom, they might only be legal when Cond is a
23206       // build_vector of constants. This will be taken care in a later
23207       // condition.
23208       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
23209        VT != MVT::v8i16) &&
23210       // Don't optimize vector of constants. Those are handled by
23211       // the generic code and all the bits must be properly set for
23212       // the generic optimizer.
23213       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23214     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23215
23216     // Don't optimize vector selects that map to mask-registers.
23217     if (BitWidth == 1)
23218       return SDValue();
23219
23220     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23221     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23222
23223     APInt KnownZero, KnownOne;
23224     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23225                                           DCI.isBeforeLegalizeOps());
23226     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23227         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23228                                  TLO)) {
23229       // If we changed the computation somewhere in the DAG, this change
23230       // will affect all users of Cond.
23231       // Make sure it is fine and update all the nodes so that we do not
23232       // use the generic VSELECT anymore. Otherwise, we may perform
23233       // wrong optimizations as we messed up with the actual expectation
23234       // for the vector boolean values.
23235       if (Cond != TLO.Old) {
23236         // Check all uses of that condition operand to check whether it will be
23237         // consumed by non-BLEND instructions, which may depend on all bits are
23238         // set properly.
23239         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23240              I != E; ++I)
23241           if (I->getOpcode() != ISD::VSELECT)
23242             // TODO: Add other opcodes eventually lowered into BLEND.
23243             return SDValue();
23244
23245         // Update all the users of the condition, before committing the change,
23246         // so that the VSELECT optimizations that expect the correct vector
23247         // boolean value will not be triggered.
23248         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23249              I != E; ++I)
23250           DAG.ReplaceAllUsesOfValueWith(
23251               SDValue(*I, 0),
23252               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23253                           Cond, I->getOperand(1), I->getOperand(2)));
23254         DCI.CommitTargetLoweringOpt(TLO);
23255         return SDValue();
23256       }
23257       // At this point, only Cond is changed. Change the condition
23258       // just for N to keep the opportunity to optimize all other
23259       // users their own way.
23260       DAG.ReplaceAllUsesOfValueWith(
23261           SDValue(N, 0),
23262           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23263                       TLO.New, N->getOperand(1), N->getOperand(2)));
23264       return SDValue();
23265     }
23266   }
23267
23268   // We should generate an X86ISD::BLENDI from a vselect if its argument
23269   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23270   // constants. This specific pattern gets generated when we split a
23271   // selector for a 512 bit vector in a machine without AVX512 (but with
23272   // 256-bit vectors), during legalization:
23273   //
23274   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23275   //
23276   // Iff we find this pattern and the build_vectors are built from
23277   // constants, we translate the vselect into a shuffle_vector that we
23278   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23279   if ((N->getOpcode() == ISD::VSELECT ||
23280        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23281       !DCI.isBeforeLegalize()) {
23282     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23283     if (Shuffle.getNode())
23284       return Shuffle;
23285   }
23286
23287   return SDValue();
23288 }
23289
23290 // Check whether a boolean test is testing a boolean value generated by
23291 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23292 // code.
23293 //
23294 // Simplify the following patterns:
23295 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23296 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23297 // to (Op EFLAGS Cond)
23298 //
23299 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23300 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23301 // to (Op EFLAGS !Cond)
23302 //
23303 // where Op could be BRCOND or CMOV.
23304 //
23305 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23306   // Quit if not CMP and SUB with its value result used.
23307   if (Cmp.getOpcode() != X86ISD::CMP &&
23308       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23309       return SDValue();
23310
23311   // Quit if not used as a boolean value.
23312   if (CC != X86::COND_E && CC != X86::COND_NE)
23313     return SDValue();
23314
23315   // Check CMP operands. One of them should be 0 or 1 and the other should be
23316   // an SetCC or extended from it.
23317   SDValue Op1 = Cmp.getOperand(0);
23318   SDValue Op2 = Cmp.getOperand(1);
23319
23320   SDValue SetCC;
23321   const ConstantSDNode* C = nullptr;
23322   bool needOppositeCond = (CC == X86::COND_E);
23323   bool checkAgainstTrue = false; // Is it a comparison against 1?
23324
23325   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23326     SetCC = Op2;
23327   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23328     SetCC = Op1;
23329   else // Quit if all operands are not constants.
23330     return SDValue();
23331
23332   if (C->getZExtValue() == 1) {
23333     needOppositeCond = !needOppositeCond;
23334     checkAgainstTrue = true;
23335   } else if (C->getZExtValue() != 0)
23336     // Quit if the constant is neither 0 or 1.
23337     return SDValue();
23338
23339   bool truncatedToBoolWithAnd = false;
23340   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23341   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23342          SetCC.getOpcode() == ISD::TRUNCATE ||
23343          SetCC.getOpcode() == ISD::AND) {
23344     if (SetCC.getOpcode() == ISD::AND) {
23345       int OpIdx = -1;
23346       ConstantSDNode *CS;
23347       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23348           CS->getZExtValue() == 1)
23349         OpIdx = 1;
23350       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23351           CS->getZExtValue() == 1)
23352         OpIdx = 0;
23353       if (OpIdx == -1)
23354         break;
23355       SetCC = SetCC.getOperand(OpIdx);
23356       truncatedToBoolWithAnd = true;
23357     } else
23358       SetCC = SetCC.getOperand(0);
23359   }
23360
23361   switch (SetCC.getOpcode()) {
23362   case X86ISD::SETCC_CARRY:
23363     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23364     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23365     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23366     // truncated to i1 using 'and'.
23367     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23368       break;
23369     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23370            "Invalid use of SETCC_CARRY!");
23371     // FALL THROUGH
23372   case X86ISD::SETCC:
23373     // Set the condition code or opposite one if necessary.
23374     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23375     if (needOppositeCond)
23376       CC = X86::GetOppositeBranchCondition(CC);
23377     return SetCC.getOperand(1);
23378   case X86ISD::CMOV: {
23379     // Check whether false/true value has canonical one, i.e. 0 or 1.
23380     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23381     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23382     // Quit if true value is not a constant.
23383     if (!TVal)
23384       return SDValue();
23385     // Quit if false value is not a constant.
23386     if (!FVal) {
23387       SDValue Op = SetCC.getOperand(0);
23388       // Skip 'zext' or 'trunc' node.
23389       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23390           Op.getOpcode() == ISD::TRUNCATE)
23391         Op = Op.getOperand(0);
23392       // A special case for rdrand/rdseed, where 0 is set if false cond is
23393       // found.
23394       if ((Op.getOpcode() != X86ISD::RDRAND &&
23395            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23396         return SDValue();
23397     }
23398     // Quit if false value is not the constant 0 or 1.
23399     bool FValIsFalse = true;
23400     if (FVal && FVal->getZExtValue() != 0) {
23401       if (FVal->getZExtValue() != 1)
23402         return SDValue();
23403       // If FVal is 1, opposite cond is needed.
23404       needOppositeCond = !needOppositeCond;
23405       FValIsFalse = false;
23406     }
23407     // Quit if TVal is not the constant opposite of FVal.
23408     if (FValIsFalse && TVal->getZExtValue() != 1)
23409       return SDValue();
23410     if (!FValIsFalse && TVal->getZExtValue() != 0)
23411       return SDValue();
23412     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23413     if (needOppositeCond)
23414       CC = X86::GetOppositeBranchCondition(CC);
23415     return SetCC.getOperand(3);
23416   }
23417   }
23418
23419   return SDValue();
23420 }
23421
23422 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23423 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23424                                   TargetLowering::DAGCombinerInfo &DCI,
23425                                   const X86Subtarget *Subtarget) {
23426   SDLoc DL(N);
23427
23428   // If the flag operand isn't dead, don't touch this CMOV.
23429   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23430     return SDValue();
23431
23432   SDValue FalseOp = N->getOperand(0);
23433   SDValue TrueOp = N->getOperand(1);
23434   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23435   SDValue Cond = N->getOperand(3);
23436
23437   if (CC == X86::COND_E || CC == X86::COND_NE) {
23438     switch (Cond.getOpcode()) {
23439     default: break;
23440     case X86ISD::BSR:
23441     case X86ISD::BSF:
23442       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23443       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23444         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23445     }
23446   }
23447
23448   SDValue Flags;
23449
23450   Flags = checkBoolTestSetCCCombine(Cond, CC);
23451   if (Flags.getNode() &&
23452       // Extra check as FCMOV only supports a subset of X86 cond.
23453       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23454     SDValue Ops[] = { FalseOp, TrueOp,
23455                       DAG.getConstant(CC, MVT::i8), Flags };
23456     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23457   }
23458
23459   // If this is a select between two integer constants, try to do some
23460   // optimizations.  Note that the operands are ordered the opposite of SELECT
23461   // operands.
23462   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23463     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23464       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23465       // larger than FalseC (the false value).
23466       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23467         CC = X86::GetOppositeBranchCondition(CC);
23468         std::swap(TrueC, FalseC);
23469         std::swap(TrueOp, FalseOp);
23470       }
23471
23472       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23473       // This is efficient for any integer data type (including i8/i16) and
23474       // shift amount.
23475       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23476         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23477                            DAG.getConstant(CC, MVT::i8), Cond);
23478
23479         // Zero extend the condition if needed.
23480         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23481
23482         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23483         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23484                            DAG.getConstant(ShAmt, MVT::i8));
23485         if (N->getNumValues() == 2)  // Dead flag value?
23486           return DCI.CombineTo(N, Cond, SDValue());
23487         return Cond;
23488       }
23489
23490       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23491       // for any integer data type, including i8/i16.
23492       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23493         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23494                            DAG.getConstant(CC, MVT::i8), Cond);
23495
23496         // Zero extend the condition if needed.
23497         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23498                            FalseC->getValueType(0), Cond);
23499         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23500                            SDValue(FalseC, 0));
23501
23502         if (N->getNumValues() == 2)  // Dead flag value?
23503           return DCI.CombineTo(N, Cond, SDValue());
23504         return Cond;
23505       }
23506
23507       // Optimize cases that will turn into an LEA instruction.  This requires
23508       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23509       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23510         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23511         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23512
23513         bool isFastMultiplier = false;
23514         if (Diff < 10) {
23515           switch ((unsigned char)Diff) {
23516           default: break;
23517           case 1:  // result = add base, cond
23518           case 2:  // result = lea base(    , cond*2)
23519           case 3:  // result = lea base(cond, cond*2)
23520           case 4:  // result = lea base(    , cond*4)
23521           case 5:  // result = lea base(cond, cond*4)
23522           case 8:  // result = lea base(    , cond*8)
23523           case 9:  // result = lea base(cond, cond*8)
23524             isFastMultiplier = true;
23525             break;
23526           }
23527         }
23528
23529         if (isFastMultiplier) {
23530           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23531           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23532                              DAG.getConstant(CC, MVT::i8), Cond);
23533           // Zero extend the condition if needed.
23534           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23535                              Cond);
23536           // Scale the condition by the difference.
23537           if (Diff != 1)
23538             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23539                                DAG.getConstant(Diff, Cond.getValueType()));
23540
23541           // Add the base if non-zero.
23542           if (FalseC->getAPIntValue() != 0)
23543             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23544                                SDValue(FalseC, 0));
23545           if (N->getNumValues() == 2)  // Dead flag value?
23546             return DCI.CombineTo(N, Cond, SDValue());
23547           return Cond;
23548         }
23549       }
23550     }
23551   }
23552
23553   // Handle these cases:
23554   //   (select (x != c), e, c) -> select (x != c), e, x),
23555   //   (select (x == c), c, e) -> select (x == c), x, e)
23556   // where the c is an integer constant, and the "select" is the combination
23557   // of CMOV and CMP.
23558   //
23559   // The rationale for this change is that the conditional-move from a constant
23560   // needs two instructions, however, conditional-move from a register needs
23561   // only one instruction.
23562   //
23563   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23564   //  some instruction-combining opportunities. This opt needs to be
23565   //  postponed as late as possible.
23566   //
23567   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23568     // the DCI.xxxx conditions are provided to postpone the optimization as
23569     // late as possible.
23570
23571     ConstantSDNode *CmpAgainst = nullptr;
23572     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23573         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23574         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23575
23576       if (CC == X86::COND_NE &&
23577           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23578         CC = X86::GetOppositeBranchCondition(CC);
23579         std::swap(TrueOp, FalseOp);
23580       }
23581
23582       if (CC == X86::COND_E &&
23583           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23584         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23585                           DAG.getConstant(CC, MVT::i8), Cond };
23586         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23587       }
23588     }
23589   }
23590
23591   return SDValue();
23592 }
23593
23594 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23595                                                 const X86Subtarget *Subtarget) {
23596   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23597   switch (IntNo) {
23598   default: return SDValue();
23599   // SSE/AVX/AVX2 blend intrinsics.
23600   case Intrinsic::x86_avx2_pblendvb:
23601   case Intrinsic::x86_avx2_pblendw:
23602   case Intrinsic::x86_avx2_pblendd_128:
23603   case Intrinsic::x86_avx2_pblendd_256:
23604     // Don't try to simplify this intrinsic if we don't have AVX2.
23605     if (!Subtarget->hasAVX2())
23606       return SDValue();
23607     // FALL-THROUGH
23608   case Intrinsic::x86_avx_blend_pd_256:
23609   case Intrinsic::x86_avx_blend_ps_256:
23610   case Intrinsic::x86_avx_blendv_pd_256:
23611   case Intrinsic::x86_avx_blendv_ps_256:
23612     // Don't try to simplify this intrinsic if we don't have AVX.
23613     if (!Subtarget->hasAVX())
23614       return SDValue();
23615     // FALL-THROUGH
23616   case Intrinsic::x86_sse41_pblendw:
23617   case Intrinsic::x86_sse41_blendpd:
23618   case Intrinsic::x86_sse41_blendps:
23619   case Intrinsic::x86_sse41_blendvps:
23620   case Intrinsic::x86_sse41_blendvpd:
23621   case Intrinsic::x86_sse41_pblendvb: {
23622     SDValue Op0 = N->getOperand(1);
23623     SDValue Op1 = N->getOperand(2);
23624     SDValue Mask = N->getOperand(3);
23625
23626     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23627     if (!Subtarget->hasSSE41())
23628       return SDValue();
23629
23630     // fold (blend A, A, Mask) -> A
23631     if (Op0 == Op1)
23632       return Op0;
23633     // fold (blend A, B, allZeros) -> A
23634     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23635       return Op0;
23636     // fold (blend A, B, allOnes) -> B
23637     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23638       return Op1;
23639     
23640     // Simplify the case where the mask is a constant i32 value.
23641     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23642       if (C->isNullValue())
23643         return Op0;
23644       if (C->isAllOnesValue())
23645         return Op1;
23646     }
23647
23648     return SDValue();
23649   }
23650
23651   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23652   case Intrinsic::x86_sse2_psrai_w:
23653   case Intrinsic::x86_sse2_psrai_d:
23654   case Intrinsic::x86_avx2_psrai_w:
23655   case Intrinsic::x86_avx2_psrai_d:
23656   case Intrinsic::x86_sse2_psra_w:
23657   case Intrinsic::x86_sse2_psra_d:
23658   case Intrinsic::x86_avx2_psra_w:
23659   case Intrinsic::x86_avx2_psra_d: {
23660     SDValue Op0 = N->getOperand(1);
23661     SDValue Op1 = N->getOperand(2);
23662     EVT VT = Op0.getValueType();
23663     assert(VT.isVector() && "Expected a vector type!");
23664
23665     if (isa<BuildVectorSDNode>(Op1))
23666       Op1 = Op1.getOperand(0);
23667
23668     if (!isa<ConstantSDNode>(Op1))
23669       return SDValue();
23670
23671     EVT SVT = VT.getVectorElementType();
23672     unsigned SVTBits = SVT.getSizeInBits();
23673
23674     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23675     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23676     uint64_t ShAmt = C.getZExtValue();
23677
23678     // Don't try to convert this shift into a ISD::SRA if the shift
23679     // count is bigger than or equal to the element size.
23680     if (ShAmt >= SVTBits)
23681       return SDValue();
23682
23683     // Trivial case: if the shift count is zero, then fold this
23684     // into the first operand.
23685     if (ShAmt == 0)
23686       return Op0;
23687
23688     // Replace this packed shift intrinsic with a target independent
23689     // shift dag node.
23690     SDValue Splat = DAG.getConstant(C, VT);
23691     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
23692   }
23693   }
23694 }
23695
23696 /// PerformMulCombine - Optimize a single multiply with constant into two
23697 /// in order to implement it with two cheaper instructions, e.g.
23698 /// LEA + SHL, LEA + LEA.
23699 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23700                                  TargetLowering::DAGCombinerInfo &DCI) {
23701   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23702     return SDValue();
23703
23704   EVT VT = N->getValueType(0);
23705   if (VT != MVT::i64)
23706     return SDValue();
23707
23708   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23709   if (!C)
23710     return SDValue();
23711   uint64_t MulAmt = C->getZExtValue();
23712   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23713     return SDValue();
23714
23715   uint64_t MulAmt1 = 0;
23716   uint64_t MulAmt2 = 0;
23717   if ((MulAmt % 9) == 0) {
23718     MulAmt1 = 9;
23719     MulAmt2 = MulAmt / 9;
23720   } else if ((MulAmt % 5) == 0) {
23721     MulAmt1 = 5;
23722     MulAmt2 = MulAmt / 5;
23723   } else if ((MulAmt % 3) == 0) {
23724     MulAmt1 = 3;
23725     MulAmt2 = MulAmt / 3;
23726   }
23727   if (MulAmt2 &&
23728       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23729     SDLoc DL(N);
23730
23731     if (isPowerOf2_64(MulAmt2) &&
23732         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23733       // If second multiplifer is pow2, issue it first. We want the multiply by
23734       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23735       // is an add.
23736       std::swap(MulAmt1, MulAmt2);
23737
23738     SDValue NewMul;
23739     if (isPowerOf2_64(MulAmt1))
23740       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23741                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
23742     else
23743       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23744                            DAG.getConstant(MulAmt1, VT));
23745
23746     if (isPowerOf2_64(MulAmt2))
23747       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23748                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
23749     else
23750       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23751                            DAG.getConstant(MulAmt2, VT));
23752
23753     // Do not add new nodes to DAG combiner worklist.
23754     DCI.CombineTo(N, NewMul, false);
23755   }
23756   return SDValue();
23757 }
23758
23759 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23760   SDValue N0 = N->getOperand(0);
23761   SDValue N1 = N->getOperand(1);
23762   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23763   EVT VT = N0.getValueType();
23764
23765   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23766   // since the result of setcc_c is all zero's or all ones.
23767   if (VT.isInteger() && !VT.isVector() &&
23768       N1C && N0.getOpcode() == ISD::AND &&
23769       N0.getOperand(1).getOpcode() == ISD::Constant) {
23770     SDValue N00 = N0.getOperand(0);
23771     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23772         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23773           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23774          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23775       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23776       APInt ShAmt = N1C->getAPIntValue();
23777       Mask = Mask.shl(ShAmt);
23778       if (Mask != 0)
23779         return DAG.getNode(ISD::AND, SDLoc(N), VT,
23780                            N00, DAG.getConstant(Mask, VT));
23781     }
23782   }
23783
23784   // Hardware support for vector shifts is sparse which makes us scalarize the
23785   // vector operations in many cases. Also, on sandybridge ADD is faster than
23786   // shl.
23787   // (shl V, 1) -> add V,V
23788   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23789     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23790       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23791       // We shift all of the values by one. In many cases we do not have
23792       // hardware support for this operation. This is better expressed as an ADD
23793       // of two values.
23794       if (N1SplatC->getZExtValue() == 1)
23795         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23796     }
23797
23798   return SDValue();
23799 }
23800
23801 /// \brief Returns a vector of 0s if the node in input is a vector logical
23802 /// shift by a constant amount which is known to be bigger than or equal
23803 /// to the vector element size in bits.
23804 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23805                                       const X86Subtarget *Subtarget) {
23806   EVT VT = N->getValueType(0);
23807
23808   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23809       (!Subtarget->hasInt256() ||
23810        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23811     return SDValue();
23812
23813   SDValue Amt = N->getOperand(1);
23814   SDLoc DL(N);
23815   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23816     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23817       APInt ShiftAmt = AmtSplat->getAPIntValue();
23818       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23819
23820       // SSE2/AVX2 logical shifts always return a vector of 0s
23821       // if the shift amount is bigger than or equal to
23822       // the element size. The constant shift amount will be
23823       // encoded as a 8-bit immediate.
23824       if (ShiftAmt.trunc(8).uge(MaxAmount))
23825         return getZeroVector(VT, Subtarget, DAG, DL);
23826     }
23827
23828   return SDValue();
23829 }
23830
23831 /// PerformShiftCombine - Combine shifts.
23832 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23833                                    TargetLowering::DAGCombinerInfo &DCI,
23834                                    const X86Subtarget *Subtarget) {
23835   if (N->getOpcode() == ISD::SHL) {
23836     SDValue V = PerformSHLCombine(N, DAG);
23837     if (V.getNode()) return V;
23838   }
23839
23840   if (N->getOpcode() != ISD::SRA) {
23841     // Try to fold this logical shift into a zero vector.
23842     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
23843     if (V.getNode()) return V;
23844   }
23845
23846   return SDValue();
23847 }
23848
23849 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23850 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23851 // and friends.  Likewise for OR -> CMPNEQSS.
23852 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23853                             TargetLowering::DAGCombinerInfo &DCI,
23854                             const X86Subtarget *Subtarget) {
23855   unsigned opcode;
23856
23857   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23858   // we're requiring SSE2 for both.
23859   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23860     SDValue N0 = N->getOperand(0);
23861     SDValue N1 = N->getOperand(1);
23862     SDValue CMP0 = N0->getOperand(1);
23863     SDValue CMP1 = N1->getOperand(1);
23864     SDLoc DL(N);
23865
23866     // The SETCCs should both refer to the same CMP.
23867     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23868       return SDValue();
23869
23870     SDValue CMP00 = CMP0->getOperand(0);
23871     SDValue CMP01 = CMP0->getOperand(1);
23872     EVT     VT    = CMP00.getValueType();
23873
23874     if (VT == MVT::f32 || VT == MVT::f64) {
23875       bool ExpectingFlags = false;
23876       // Check for any users that want flags:
23877       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23878            !ExpectingFlags && UI != UE; ++UI)
23879         switch (UI->getOpcode()) {
23880         default:
23881         case ISD::BR_CC:
23882         case ISD::BRCOND:
23883         case ISD::SELECT:
23884           ExpectingFlags = true;
23885           break;
23886         case ISD::CopyToReg:
23887         case ISD::SIGN_EXTEND:
23888         case ISD::ZERO_EXTEND:
23889         case ISD::ANY_EXTEND:
23890           break;
23891         }
23892
23893       if (!ExpectingFlags) {
23894         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23895         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23896
23897         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23898           X86::CondCode tmp = cc0;
23899           cc0 = cc1;
23900           cc1 = tmp;
23901         }
23902
23903         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23904             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23905           // FIXME: need symbolic constants for these magic numbers.
23906           // See X86ATTInstPrinter.cpp:printSSECC().
23907           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23908           if (Subtarget->hasAVX512()) {
23909             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23910                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
23911             if (N->getValueType(0) != MVT::i1)
23912               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23913                                  FSetCC);
23914             return FSetCC;
23915           }
23916           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23917                                               CMP00.getValueType(), CMP00, CMP01,
23918                                               DAG.getConstant(x86cc, MVT::i8));
23919
23920           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23921           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23922
23923           if (is64BitFP && !Subtarget->is64Bit()) {
23924             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23925             // 64-bit integer, since that's not a legal type. Since
23926             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23927             // bits, but can do this little dance to extract the lowest 32 bits
23928             // and work with those going forward.
23929             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23930                                            OnesOrZeroesF);
23931             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
23932                                            Vector64);
23933             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23934                                         Vector32, DAG.getIntPtrConstant(0));
23935             IntVT = MVT::i32;
23936           }
23937
23938           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
23939           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23940                                       DAG.getConstant(1, IntVT));
23941           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
23942           return OneBitOfTruth;
23943         }
23944       }
23945     }
23946   }
23947   return SDValue();
23948 }
23949
23950 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23951 /// so it can be folded inside ANDNP.
23952 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23953   EVT VT = N->getValueType(0);
23954
23955   // Match direct AllOnes for 128 and 256-bit vectors
23956   if (ISD::isBuildVectorAllOnes(N))
23957     return true;
23958
23959   // Look through a bit convert.
23960   if (N->getOpcode() == ISD::BITCAST)
23961     N = N->getOperand(0).getNode();
23962
23963   // Sometimes the operand may come from a insert_subvector building a 256-bit
23964   // allones vector
23965   if (VT.is256BitVector() &&
23966       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23967     SDValue V1 = N->getOperand(0);
23968     SDValue V2 = N->getOperand(1);
23969
23970     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23971         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23972         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23973         ISD::isBuildVectorAllOnes(V2.getNode()))
23974       return true;
23975   }
23976
23977   return false;
23978 }
23979
23980 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23981 // register. In most cases we actually compare or select YMM-sized registers
23982 // and mixing the two types creates horrible code. This method optimizes
23983 // some of the transition sequences.
23984 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23985                                  TargetLowering::DAGCombinerInfo &DCI,
23986                                  const X86Subtarget *Subtarget) {
23987   EVT VT = N->getValueType(0);
23988   if (!VT.is256BitVector())
23989     return SDValue();
23990
23991   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23992           N->getOpcode() == ISD::ZERO_EXTEND ||
23993           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23994
23995   SDValue Narrow = N->getOperand(0);
23996   EVT NarrowVT = Narrow->getValueType(0);
23997   if (!NarrowVT.is128BitVector())
23998     return SDValue();
23999
24000   if (Narrow->getOpcode() != ISD::XOR &&
24001       Narrow->getOpcode() != ISD::AND &&
24002       Narrow->getOpcode() != ISD::OR)
24003     return SDValue();
24004
24005   SDValue N0  = Narrow->getOperand(0);
24006   SDValue N1  = Narrow->getOperand(1);
24007   SDLoc DL(Narrow);
24008
24009   // The Left side has to be a trunc.
24010   if (N0.getOpcode() != ISD::TRUNCATE)
24011     return SDValue();
24012
24013   // The type of the truncated inputs.
24014   EVT WideVT = N0->getOperand(0)->getValueType(0);
24015   if (WideVT != VT)
24016     return SDValue();
24017
24018   // The right side has to be a 'trunc' or a constant vector.
24019   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24020   ConstantSDNode *RHSConstSplat = nullptr;
24021   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24022     RHSConstSplat = RHSBV->getConstantSplatNode();
24023   if (!RHSTrunc && !RHSConstSplat)
24024     return SDValue();
24025
24026   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24027
24028   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24029     return SDValue();
24030
24031   // Set N0 and N1 to hold the inputs to the new wide operation.
24032   N0 = N0->getOperand(0);
24033   if (RHSConstSplat) {
24034     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24035                      SDValue(RHSConstSplat, 0));
24036     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24037     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24038   } else if (RHSTrunc) {
24039     N1 = N1->getOperand(0);
24040   }
24041
24042   // Generate the wide operation.
24043   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24044   unsigned Opcode = N->getOpcode();
24045   switch (Opcode) {
24046   case ISD::ANY_EXTEND:
24047     return Op;
24048   case ISD::ZERO_EXTEND: {
24049     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24050     APInt Mask = APInt::getAllOnesValue(InBits);
24051     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24052     return DAG.getNode(ISD::AND, DL, VT,
24053                        Op, DAG.getConstant(Mask, VT));
24054   }
24055   case ISD::SIGN_EXTEND:
24056     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24057                        Op, DAG.getValueType(NarrowVT));
24058   default:
24059     llvm_unreachable("Unexpected opcode");
24060   }
24061 }
24062
24063 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24064                                  TargetLowering::DAGCombinerInfo &DCI,
24065                                  const X86Subtarget *Subtarget) {
24066   EVT VT = N->getValueType(0);
24067   if (DCI.isBeforeLegalizeOps())
24068     return SDValue();
24069
24070   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24071   if (R.getNode())
24072     return R;
24073
24074   // Create BEXTR instructions
24075   // BEXTR is ((X >> imm) & (2**size-1))
24076   if (VT == MVT::i32 || VT == MVT::i64) {
24077     SDValue N0 = N->getOperand(0);
24078     SDValue N1 = N->getOperand(1);
24079     SDLoc DL(N);
24080
24081     // Check for BEXTR.
24082     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24083         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24084       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24085       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24086       if (MaskNode && ShiftNode) {
24087         uint64_t Mask = MaskNode->getZExtValue();
24088         uint64_t Shift = ShiftNode->getZExtValue();
24089         if (isMask_64(Mask)) {
24090           uint64_t MaskSize = CountPopulation_64(Mask);
24091           if (Shift + MaskSize <= VT.getSizeInBits())
24092             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24093                                DAG.getConstant(Shift | (MaskSize << 8), VT));
24094         }
24095       }
24096     } // BEXTR
24097
24098     return SDValue();
24099   }
24100
24101   // Want to form ANDNP nodes:
24102   // 1) In the hopes of then easily combining them with OR and AND nodes
24103   //    to form PBLEND/PSIGN.
24104   // 2) To match ANDN packed intrinsics
24105   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24106     return SDValue();
24107
24108   SDValue N0 = N->getOperand(0);
24109   SDValue N1 = N->getOperand(1);
24110   SDLoc DL(N);
24111
24112   // Check LHS for vnot
24113   if (N0.getOpcode() == ISD::XOR &&
24114       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24115       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24116     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24117
24118   // Check RHS for vnot
24119   if (N1.getOpcode() == ISD::XOR &&
24120       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24121       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24122     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24123
24124   return SDValue();
24125 }
24126
24127 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24128                                 TargetLowering::DAGCombinerInfo &DCI,
24129                                 const X86Subtarget *Subtarget) {
24130   if (DCI.isBeforeLegalizeOps())
24131     return SDValue();
24132
24133   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
24134   if (R.getNode())
24135     return R;
24136
24137   SDValue N0 = N->getOperand(0);
24138   SDValue N1 = N->getOperand(1);
24139   EVT VT = N->getValueType(0);
24140
24141   // look for psign/blend
24142   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24143     if (!Subtarget->hasSSSE3() ||
24144         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24145       return SDValue();
24146
24147     // Canonicalize pandn to RHS
24148     if (N0.getOpcode() == X86ISD::ANDNP)
24149       std::swap(N0, N1);
24150     // or (and (m, y), (pandn m, x))
24151     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24152       SDValue Mask = N1.getOperand(0);
24153       SDValue X    = N1.getOperand(1);
24154       SDValue Y;
24155       if (N0.getOperand(0) == Mask)
24156         Y = N0.getOperand(1);
24157       if (N0.getOperand(1) == Mask)
24158         Y = N0.getOperand(0);
24159
24160       // Check to see if the mask appeared in both the AND and ANDNP and
24161       if (!Y.getNode())
24162         return SDValue();
24163
24164       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24165       // Look through mask bitcast.
24166       if (Mask.getOpcode() == ISD::BITCAST)
24167         Mask = Mask.getOperand(0);
24168       if (X.getOpcode() == ISD::BITCAST)
24169         X = X.getOperand(0);
24170       if (Y.getOpcode() == ISD::BITCAST)
24171         Y = Y.getOperand(0);
24172
24173       EVT MaskVT = Mask.getValueType();
24174
24175       // Validate that the Mask operand is a vector sra node.
24176       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24177       // there is no psrai.b
24178       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24179       unsigned SraAmt = ~0;
24180       if (Mask.getOpcode() == ISD::SRA) {
24181         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24182           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24183             SraAmt = AmtConst->getZExtValue();
24184       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24185         SDValue SraC = Mask.getOperand(1);
24186         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24187       }
24188       if ((SraAmt + 1) != EltBits)
24189         return SDValue();
24190
24191       SDLoc DL(N);
24192
24193       // Now we know we at least have a plendvb with the mask val.  See if
24194       // we can form a psignb/w/d.
24195       // psign = x.type == y.type == mask.type && y = sub(0, x);
24196       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24197           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24198           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24199         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24200                "Unsupported VT for PSIGN");
24201         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24202         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24203       }
24204       // PBLENDVB only available on SSE 4.1
24205       if (!Subtarget->hasSSE41())
24206         return SDValue();
24207
24208       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24209
24210       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
24211       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
24212       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
24213       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24214       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
24215     }
24216   }
24217
24218   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24219     return SDValue();
24220
24221   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24222   MachineFunction &MF = DAG.getMachineFunction();
24223   bool OptForSize = MF.getFunction()->getAttributes().
24224     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
24225
24226   // SHLD/SHRD instructions have lower register pressure, but on some
24227   // platforms they have higher latency than the equivalent
24228   // series of shifts/or that would otherwise be generated.
24229   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24230   // have higher latencies and we are not optimizing for size.
24231   if (!OptForSize && Subtarget->isSHLDSlow())
24232     return SDValue();
24233
24234   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24235     std::swap(N0, N1);
24236   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24237     return SDValue();
24238   if (!N0.hasOneUse() || !N1.hasOneUse())
24239     return SDValue();
24240
24241   SDValue ShAmt0 = N0.getOperand(1);
24242   if (ShAmt0.getValueType() != MVT::i8)
24243     return SDValue();
24244   SDValue ShAmt1 = N1.getOperand(1);
24245   if (ShAmt1.getValueType() != MVT::i8)
24246     return SDValue();
24247   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24248     ShAmt0 = ShAmt0.getOperand(0);
24249   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24250     ShAmt1 = ShAmt1.getOperand(0);
24251
24252   SDLoc DL(N);
24253   unsigned Opc = X86ISD::SHLD;
24254   SDValue Op0 = N0.getOperand(0);
24255   SDValue Op1 = N1.getOperand(0);
24256   if (ShAmt0.getOpcode() == ISD::SUB) {
24257     Opc = X86ISD::SHRD;
24258     std::swap(Op0, Op1);
24259     std::swap(ShAmt0, ShAmt1);
24260   }
24261
24262   unsigned Bits = VT.getSizeInBits();
24263   if (ShAmt1.getOpcode() == ISD::SUB) {
24264     SDValue Sum = ShAmt1.getOperand(0);
24265     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24266       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24267       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24268         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24269       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24270         return DAG.getNode(Opc, DL, VT,
24271                            Op0, Op1,
24272                            DAG.getNode(ISD::TRUNCATE, DL,
24273                                        MVT::i8, ShAmt0));
24274     }
24275   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24276     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24277     if (ShAmt0C &&
24278         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24279       return DAG.getNode(Opc, DL, VT,
24280                          N0.getOperand(0), N1.getOperand(0),
24281                          DAG.getNode(ISD::TRUNCATE, DL,
24282                                        MVT::i8, ShAmt0));
24283   }
24284
24285   return SDValue();
24286 }
24287
24288 // Generate NEG and CMOV for integer abs.
24289 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24290   EVT VT = N->getValueType(0);
24291
24292   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24293   // 8-bit integer abs to NEG and CMOV.
24294   if (VT.isInteger() && VT.getSizeInBits() == 8)
24295     return SDValue();
24296
24297   SDValue N0 = N->getOperand(0);
24298   SDValue N1 = N->getOperand(1);
24299   SDLoc DL(N);
24300
24301   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24302   // and change it to SUB and CMOV.
24303   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24304       N0.getOpcode() == ISD::ADD &&
24305       N0.getOperand(1) == N1 &&
24306       N1.getOpcode() == ISD::SRA &&
24307       N1.getOperand(0) == N0.getOperand(0))
24308     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24309       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24310         // Generate SUB & CMOV.
24311         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24312                                   DAG.getConstant(0, VT), N0.getOperand(0));
24313
24314         SDValue Ops[] = { N0.getOperand(0), Neg,
24315                           DAG.getConstant(X86::COND_GE, MVT::i8),
24316                           SDValue(Neg.getNode(), 1) };
24317         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24318       }
24319   return SDValue();
24320 }
24321
24322 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24323 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24324                                  TargetLowering::DAGCombinerInfo &DCI,
24325                                  const X86Subtarget *Subtarget) {
24326   if (DCI.isBeforeLegalizeOps())
24327     return SDValue();
24328
24329   if (Subtarget->hasCMov()) {
24330     SDValue RV = performIntegerAbsCombine(N, DAG);
24331     if (RV.getNode())
24332       return RV;
24333   }
24334
24335   return SDValue();
24336 }
24337
24338 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24339 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24340                                   TargetLowering::DAGCombinerInfo &DCI,
24341                                   const X86Subtarget *Subtarget) {
24342   LoadSDNode *Ld = cast<LoadSDNode>(N);
24343   EVT RegVT = Ld->getValueType(0);
24344   EVT MemVT = Ld->getMemoryVT();
24345   SDLoc dl(Ld);
24346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24347
24348   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24349   // into two 16-byte operations.
24350   ISD::LoadExtType Ext = Ld->getExtensionType();
24351   unsigned Alignment = Ld->getAlignment();
24352   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24353   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24354       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24355     unsigned NumElems = RegVT.getVectorNumElements();
24356     if (NumElems < 2)
24357       return SDValue();
24358
24359     SDValue Ptr = Ld->getBasePtr();
24360     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
24361
24362     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24363                                   NumElems/2);
24364     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24365                                 Ld->getPointerInfo(), Ld->isVolatile(),
24366                                 Ld->isNonTemporal(), Ld->isInvariant(),
24367                                 Alignment);
24368     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24369     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24370                                 Ld->getPointerInfo(), Ld->isVolatile(),
24371                                 Ld->isNonTemporal(), Ld->isInvariant(),
24372                                 std::min(16U, Alignment));
24373     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24374                              Load1.getValue(1),
24375                              Load2.getValue(1));
24376
24377     SDValue NewVec = DAG.getUNDEF(RegVT);
24378     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24379     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24380     return DCI.CombineTo(N, NewVec, TF, true);
24381   }
24382
24383   return SDValue();
24384 }
24385
24386 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24387 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24388                                    const X86Subtarget *Subtarget) {
24389   StoreSDNode *St = cast<StoreSDNode>(N);
24390   EVT VT = St->getValue().getValueType();
24391   EVT StVT = St->getMemoryVT();
24392   SDLoc dl(St);
24393   SDValue StoredVal = St->getOperand(1);
24394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24395
24396   // If we are saving a concatenation of two XMM registers and 32-byte stores
24397   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24398   unsigned Alignment = St->getAlignment();
24399   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24400   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24401       StVT == VT && !IsAligned) {
24402     unsigned NumElems = VT.getVectorNumElements();
24403     if (NumElems < 2)
24404       return SDValue();
24405
24406     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24407     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24408
24409     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
24410     SDValue Ptr0 = St->getBasePtr();
24411     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24412
24413     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24414                                 St->getPointerInfo(), St->isVolatile(),
24415                                 St->isNonTemporal(), Alignment);
24416     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24417                                 St->getPointerInfo(), St->isVolatile(),
24418                                 St->isNonTemporal(),
24419                                 std::min(16U, Alignment));
24420     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24421   }
24422
24423   // Optimize trunc store (of multiple scalars) to shuffle and store.
24424   // First, pack all of the elements in one place. Next, store to memory
24425   // in fewer chunks.
24426   if (St->isTruncatingStore() && VT.isVector()) {
24427     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24428     unsigned NumElems = VT.getVectorNumElements();
24429     assert(StVT != VT && "Cannot truncate to the same type");
24430     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24431     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24432
24433     // From, To sizes and ElemCount must be pow of two
24434     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24435     // We are going to use the original vector elt for storing.
24436     // Accumulated smaller vector elements must be a multiple of the store size.
24437     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24438
24439     unsigned SizeRatio  = FromSz / ToSz;
24440
24441     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24442
24443     // Create a type on which we perform the shuffle
24444     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24445             StVT.getScalarType(), NumElems*SizeRatio);
24446
24447     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24448
24449     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
24450     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24451     for (unsigned i = 0; i != NumElems; ++i)
24452       ShuffleVec[i] = i * SizeRatio;
24453
24454     // Can't shuffle using an illegal type.
24455     if (!TLI.isTypeLegal(WideVecVT))
24456       return SDValue();
24457
24458     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24459                                          DAG.getUNDEF(WideVecVT),
24460                                          &ShuffleVec[0]);
24461     // At this point all of the data is stored at the bottom of the
24462     // register. We now need to save it to mem.
24463
24464     // Find the largest store unit
24465     MVT StoreType = MVT::i8;
24466     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
24467          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
24468       MVT Tp = (MVT::SimpleValueType)tp;
24469       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24470         StoreType = Tp;
24471     }
24472
24473     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24474     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24475         (64 <= NumElems * ToSz))
24476       StoreType = MVT::f64;
24477
24478     // Bitcast the original vector into a vector of store-size units
24479     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24480             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24481     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24482     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
24483     SmallVector<SDValue, 8> Chains;
24484     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
24485                                         TLI.getPointerTy());
24486     SDValue Ptr = St->getBasePtr();
24487
24488     // Perform one or more big stores into memory.
24489     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24490       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24491                                    StoreType, ShuffWide,
24492                                    DAG.getIntPtrConstant(i));
24493       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24494                                 St->getPointerInfo(), St->isVolatile(),
24495                                 St->isNonTemporal(), St->getAlignment());
24496       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24497       Chains.push_back(Ch);
24498     }
24499
24500     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24501   }
24502
24503   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24504   // the FP state in cases where an emms may be missing.
24505   // A preferable solution to the general problem is to figure out the right
24506   // places to insert EMMS.  This qualifies as a quick hack.
24507
24508   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24509   if (VT.getSizeInBits() != 64)
24510     return SDValue();
24511
24512   const Function *F = DAG.getMachineFunction().getFunction();
24513   bool NoImplicitFloatOps = F->getAttributes().
24514     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
24515   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
24516                      && Subtarget->hasSSE2();
24517   if ((VT.isVector() ||
24518        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24519       isa<LoadSDNode>(St->getValue()) &&
24520       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24521       St->getChain().hasOneUse() && !St->isVolatile()) {
24522     SDNode* LdVal = St->getValue().getNode();
24523     LoadSDNode *Ld = nullptr;
24524     int TokenFactorIndex = -1;
24525     SmallVector<SDValue, 8> Ops;
24526     SDNode* ChainVal = St->getChain().getNode();
24527     // Must be a store of a load.  We currently handle two cases:  the load
24528     // is a direct child, and it's under an intervening TokenFactor.  It is
24529     // possible to dig deeper under nested TokenFactors.
24530     if (ChainVal == LdVal)
24531       Ld = cast<LoadSDNode>(St->getChain());
24532     else if (St->getValue().hasOneUse() &&
24533              ChainVal->getOpcode() == ISD::TokenFactor) {
24534       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24535         if (ChainVal->getOperand(i).getNode() == LdVal) {
24536           TokenFactorIndex = i;
24537           Ld = cast<LoadSDNode>(St->getValue());
24538         } else
24539           Ops.push_back(ChainVal->getOperand(i));
24540       }
24541     }
24542
24543     if (!Ld || !ISD::isNormalLoad(Ld))
24544       return SDValue();
24545
24546     // If this is not the MMX case, i.e. we are just turning i64 load/store
24547     // into f64 load/store, avoid the transformation if there are multiple
24548     // uses of the loaded value.
24549     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24550       return SDValue();
24551
24552     SDLoc LdDL(Ld);
24553     SDLoc StDL(N);
24554     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24555     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24556     // pair instead.
24557     if (Subtarget->is64Bit() || F64IsLegal) {
24558       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24559       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24560                                   Ld->getPointerInfo(), Ld->isVolatile(),
24561                                   Ld->isNonTemporal(), Ld->isInvariant(),
24562                                   Ld->getAlignment());
24563       SDValue NewChain = NewLd.getValue(1);
24564       if (TokenFactorIndex != -1) {
24565         Ops.push_back(NewChain);
24566         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24567       }
24568       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24569                           St->getPointerInfo(),
24570                           St->isVolatile(), St->isNonTemporal(),
24571                           St->getAlignment());
24572     }
24573
24574     // Otherwise, lower to two pairs of 32-bit loads / stores.
24575     SDValue LoAddr = Ld->getBasePtr();
24576     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24577                                  DAG.getConstant(4, MVT::i32));
24578
24579     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24580                                Ld->getPointerInfo(),
24581                                Ld->isVolatile(), Ld->isNonTemporal(),
24582                                Ld->isInvariant(), Ld->getAlignment());
24583     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24584                                Ld->getPointerInfo().getWithOffset(4),
24585                                Ld->isVolatile(), Ld->isNonTemporal(),
24586                                Ld->isInvariant(),
24587                                MinAlign(Ld->getAlignment(), 4));
24588
24589     SDValue NewChain = LoLd.getValue(1);
24590     if (TokenFactorIndex != -1) {
24591       Ops.push_back(LoLd);
24592       Ops.push_back(HiLd);
24593       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24594     }
24595
24596     LoAddr = St->getBasePtr();
24597     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24598                          DAG.getConstant(4, MVT::i32));
24599
24600     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24601                                 St->getPointerInfo(),
24602                                 St->isVolatile(), St->isNonTemporal(),
24603                                 St->getAlignment());
24604     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24605                                 St->getPointerInfo().getWithOffset(4),
24606                                 St->isVolatile(),
24607                                 St->isNonTemporal(),
24608                                 MinAlign(St->getAlignment(), 4));
24609     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24610   }
24611   return SDValue();
24612 }
24613
24614 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
24615 /// and return the operands for the horizontal operation in LHS and RHS.  A
24616 /// horizontal operation performs the binary operation on successive elements
24617 /// of its first operand, then on successive elements of its second operand,
24618 /// returning the resulting values in a vector.  For example, if
24619 ///   A = < float a0, float a1, float a2, float a3 >
24620 /// and
24621 ///   B = < float b0, float b1, float b2, float b3 >
24622 /// then the result of doing a horizontal operation on A and B is
24623 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24624 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24625 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24626 /// set to A, RHS to B, and the routine returns 'true'.
24627 /// Note that the binary operation should have the property that if one of the
24628 /// operands is UNDEF then the result is UNDEF.
24629 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24630   // Look for the following pattern: if
24631   //   A = < float a0, float a1, float a2, float a3 >
24632   //   B = < float b0, float b1, float b2, float b3 >
24633   // and
24634   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24635   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24636   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24637   // which is A horizontal-op B.
24638
24639   // At least one of the operands should be a vector shuffle.
24640   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24641       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24642     return false;
24643
24644   MVT VT = LHS.getSimpleValueType();
24645
24646   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24647          "Unsupported vector type for horizontal add/sub");
24648
24649   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24650   // operate independently on 128-bit lanes.
24651   unsigned NumElts = VT.getVectorNumElements();
24652   unsigned NumLanes = VT.getSizeInBits()/128;
24653   unsigned NumLaneElts = NumElts / NumLanes;
24654   assert((NumLaneElts % 2 == 0) &&
24655          "Vector type should have an even number of elements in each lane");
24656   unsigned HalfLaneElts = NumLaneElts/2;
24657
24658   // View LHS in the form
24659   //   LHS = VECTOR_SHUFFLE A, B, LMask
24660   // If LHS is not a shuffle then pretend it is the shuffle
24661   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24662   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24663   // type VT.
24664   SDValue A, B;
24665   SmallVector<int, 16> LMask(NumElts);
24666   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24667     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24668       A = LHS.getOperand(0);
24669     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24670       B = LHS.getOperand(1);
24671     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24672     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24673   } else {
24674     if (LHS.getOpcode() != ISD::UNDEF)
24675       A = LHS;
24676     for (unsigned i = 0; i != NumElts; ++i)
24677       LMask[i] = i;
24678   }
24679
24680   // Likewise, view RHS in the form
24681   //   RHS = VECTOR_SHUFFLE C, D, RMask
24682   SDValue C, D;
24683   SmallVector<int, 16> RMask(NumElts);
24684   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24685     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24686       C = RHS.getOperand(0);
24687     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24688       D = RHS.getOperand(1);
24689     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24690     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24691   } else {
24692     if (RHS.getOpcode() != ISD::UNDEF)
24693       C = RHS;
24694     for (unsigned i = 0; i != NumElts; ++i)
24695       RMask[i] = i;
24696   }
24697
24698   // Check that the shuffles are both shuffling the same vectors.
24699   if (!(A == C && B == D) && !(A == D && B == C))
24700     return false;
24701
24702   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24703   if (!A.getNode() && !B.getNode())
24704     return false;
24705
24706   // If A and B occur in reverse order in RHS, then "swap" them (which means
24707   // rewriting the mask).
24708   if (A != C)
24709     CommuteVectorShuffleMask(RMask, NumElts);
24710
24711   // At this point LHS and RHS are equivalent to
24712   //   LHS = VECTOR_SHUFFLE A, B, LMask
24713   //   RHS = VECTOR_SHUFFLE A, B, RMask
24714   // Check that the masks correspond to performing a horizontal operation.
24715   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24716     for (unsigned i = 0; i != NumLaneElts; ++i) {
24717       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24718
24719       // Ignore any UNDEF components.
24720       if (LIdx < 0 || RIdx < 0 ||
24721           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24722           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24723         continue;
24724
24725       // Check that successive elements are being operated on.  If not, this is
24726       // not a horizontal operation.
24727       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24728       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24729       if (!(LIdx == Index && RIdx == Index + 1) &&
24730           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24731         return false;
24732     }
24733   }
24734
24735   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24736   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24737   return true;
24738 }
24739
24740 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
24741 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24742                                   const X86Subtarget *Subtarget) {
24743   EVT VT = N->getValueType(0);
24744   SDValue LHS = N->getOperand(0);
24745   SDValue RHS = N->getOperand(1);
24746
24747   // Try to synthesize horizontal adds from adds of shuffles.
24748   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24749        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24750       isHorizontalBinOp(LHS, RHS, true))
24751     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24752   return SDValue();
24753 }
24754
24755 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
24756 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24757                                   const X86Subtarget *Subtarget) {
24758   EVT VT = N->getValueType(0);
24759   SDValue LHS = N->getOperand(0);
24760   SDValue RHS = N->getOperand(1);
24761
24762   // Try to synthesize horizontal subs from subs of shuffles.
24763   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24764        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24765       isHorizontalBinOp(LHS, RHS, false))
24766     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24767   return SDValue();
24768 }
24769
24770 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
24771 /// X86ISD::FXOR nodes.
24772 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24773   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24774   // F[X]OR(0.0, x) -> x
24775   // F[X]OR(x, 0.0) -> x
24776   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24777     if (C->getValueAPF().isPosZero())
24778       return N->getOperand(1);
24779   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24780     if (C->getValueAPF().isPosZero())
24781       return N->getOperand(0);
24782   return SDValue();
24783 }
24784
24785 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
24786 /// X86ISD::FMAX nodes.
24787 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24788   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24789
24790   // Only perform optimizations if UnsafeMath is used.
24791   if (!DAG.getTarget().Options.UnsafeFPMath)
24792     return SDValue();
24793
24794   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24795   // into FMINC and FMAXC, which are Commutative operations.
24796   unsigned NewOp = 0;
24797   switch (N->getOpcode()) {
24798     default: llvm_unreachable("unknown opcode");
24799     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24800     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24801   }
24802
24803   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24804                      N->getOperand(0), N->getOperand(1));
24805 }
24806
24807 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
24808 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24809   // FAND(0.0, x) -> 0.0
24810   // FAND(x, 0.0) -> 0.0
24811   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24812     if (C->getValueAPF().isPosZero())
24813       return N->getOperand(0);
24814   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24815     if (C->getValueAPF().isPosZero())
24816       return N->getOperand(1);
24817   return SDValue();
24818 }
24819
24820 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
24821 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24822   // FANDN(x, 0.0) -> 0.0
24823   // FANDN(0.0, x) -> x
24824   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24825     if (C->getValueAPF().isPosZero())
24826       return N->getOperand(1);
24827   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24828     if (C->getValueAPF().isPosZero())
24829       return N->getOperand(1);
24830   return SDValue();
24831 }
24832
24833 static SDValue PerformBTCombine(SDNode *N,
24834                                 SelectionDAG &DAG,
24835                                 TargetLowering::DAGCombinerInfo &DCI) {
24836   // BT ignores high bits in the bit index operand.
24837   SDValue Op1 = N->getOperand(1);
24838   if (Op1.hasOneUse()) {
24839     unsigned BitWidth = Op1.getValueSizeInBits();
24840     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24841     APInt KnownZero, KnownOne;
24842     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24843                                           !DCI.isBeforeLegalizeOps());
24844     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24845     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24846         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24847       DCI.CommitTargetLoweringOpt(TLO);
24848   }
24849   return SDValue();
24850 }
24851
24852 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24853   SDValue Op = N->getOperand(0);
24854   if (Op.getOpcode() == ISD::BITCAST)
24855     Op = Op.getOperand(0);
24856   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24857   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24858       VT.getVectorElementType().getSizeInBits() ==
24859       OpVT.getVectorElementType().getSizeInBits()) {
24860     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24861   }
24862   return SDValue();
24863 }
24864
24865 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24866                                                const X86Subtarget *Subtarget) {
24867   EVT VT = N->getValueType(0);
24868   if (!VT.isVector())
24869     return SDValue();
24870
24871   SDValue N0 = N->getOperand(0);
24872   SDValue N1 = N->getOperand(1);
24873   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24874   SDLoc dl(N);
24875
24876   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24877   // both SSE and AVX2 since there is no sign-extended shift right
24878   // operation on a vector with 64-bit elements.
24879   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24880   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24881   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24882       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24883     SDValue N00 = N0.getOperand(0);
24884
24885     // EXTLOAD has a better solution on AVX2,
24886     // it may be replaced with X86ISD::VSEXT node.
24887     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24888       if (!ISD::isNormalLoad(N00.getNode()))
24889         return SDValue();
24890
24891     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24892         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24893                                   N00, N1);
24894       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24895     }
24896   }
24897   return SDValue();
24898 }
24899
24900 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24901                                   TargetLowering::DAGCombinerInfo &DCI,
24902                                   const X86Subtarget *Subtarget) {
24903   SDValue N0 = N->getOperand(0);
24904   EVT VT = N->getValueType(0);
24905
24906   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24907   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24908   // This exposes the sext to the sdivrem lowering, so that it directly extends
24909   // from AH (which we otherwise need to do contortions to access).
24910   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24911       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
24912     SDLoc dl(N);
24913     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24914     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
24915                             N0.getOperand(0), N0.getOperand(1));
24916     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24917     return R.getValue(1);
24918   }
24919
24920   if (!DCI.isBeforeLegalizeOps())
24921     return SDValue();
24922
24923   if (!Subtarget->hasFp256())
24924     return SDValue();
24925
24926   if (VT.isVector() && VT.getSizeInBits() == 256) {
24927     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
24928     if (R.getNode())
24929       return R;
24930   }
24931
24932   return SDValue();
24933 }
24934
24935 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24936                                  const X86Subtarget* Subtarget) {
24937   SDLoc dl(N);
24938   EVT VT = N->getValueType(0);
24939
24940   // Let legalize expand this if it isn't a legal type yet.
24941   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24942     return SDValue();
24943
24944   EVT ScalarVT = VT.getScalarType();
24945   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24946       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
24947     return SDValue();
24948
24949   SDValue A = N->getOperand(0);
24950   SDValue B = N->getOperand(1);
24951   SDValue C = N->getOperand(2);
24952
24953   bool NegA = (A.getOpcode() == ISD::FNEG);
24954   bool NegB = (B.getOpcode() == ISD::FNEG);
24955   bool NegC = (C.getOpcode() == ISD::FNEG);
24956
24957   // Negative multiplication when NegA xor NegB
24958   bool NegMul = (NegA != NegB);
24959   if (NegA)
24960     A = A.getOperand(0);
24961   if (NegB)
24962     B = B.getOperand(0);
24963   if (NegC)
24964     C = C.getOperand(0);
24965
24966   unsigned Opcode;
24967   if (!NegMul)
24968     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24969   else
24970     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24971
24972   return DAG.getNode(Opcode, dl, VT, A, B, C);
24973 }
24974
24975 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24976                                   TargetLowering::DAGCombinerInfo &DCI,
24977                                   const X86Subtarget *Subtarget) {
24978   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24979   //           (and (i32 x86isd::setcc_carry), 1)
24980   // This eliminates the zext. This transformation is necessary because
24981   // ISD::SETCC is always legalized to i8.
24982   SDLoc dl(N);
24983   SDValue N0 = N->getOperand(0);
24984   EVT VT = N->getValueType(0);
24985
24986   if (N0.getOpcode() == ISD::AND &&
24987       N0.hasOneUse() &&
24988       N0.getOperand(0).hasOneUse()) {
24989     SDValue N00 = N0.getOperand(0);
24990     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24991       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24992       if (!C || C->getZExtValue() != 1)
24993         return SDValue();
24994       return DAG.getNode(ISD::AND, dl, VT,
24995                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24996                                      N00.getOperand(0), N00.getOperand(1)),
24997                          DAG.getConstant(1, VT));
24998     }
24999   }
25000
25001   if (N0.getOpcode() == ISD::TRUNCATE &&
25002       N0.hasOneUse() &&
25003       N0.getOperand(0).hasOneUse()) {
25004     SDValue N00 = N0.getOperand(0);
25005     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25006       return DAG.getNode(ISD::AND, dl, VT,
25007                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25008                                      N00.getOperand(0), N00.getOperand(1)),
25009                          DAG.getConstant(1, VT));
25010     }
25011   }
25012   if (VT.is256BitVector()) {
25013     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
25014     if (R.getNode())
25015       return R;
25016   }
25017
25018   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25019   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25020   // This exposes the zext to the udivrem lowering, so that it directly extends
25021   // from AH (which we otherwise need to do contortions to access).
25022   if (N0.getOpcode() == ISD::UDIVREM &&
25023       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25024       (VT == MVT::i32 || VT == MVT::i64)) {
25025     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25026     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25027                             N0.getOperand(0), N0.getOperand(1));
25028     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25029     return R.getValue(1);
25030   }
25031
25032   return SDValue();
25033 }
25034
25035 // Optimize x == -y --> x+y == 0
25036 //          x != -y --> x+y != 0
25037 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25038                                       const X86Subtarget* Subtarget) {
25039   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25040   SDValue LHS = N->getOperand(0);
25041   SDValue RHS = N->getOperand(1);
25042   EVT VT = N->getValueType(0);
25043   SDLoc DL(N);
25044
25045   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25046     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25047       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25048         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25049                                    LHS.getValueType(), RHS, LHS.getOperand(1));
25050         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25051                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25052       }
25053   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25054     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25055       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25056         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
25057                                    RHS.getValueType(), LHS, RHS.getOperand(1));
25058         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
25059                             addV, DAG.getConstant(0, addV.getValueType()), CC);
25060       }
25061
25062   if (VT.getScalarType() == MVT::i1) {
25063     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25064       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25065     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
25066     if (!IsSEXT0 && !IsVZero0)
25067       return SDValue();
25068     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
25069       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
25070     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25071
25072     if (!IsSEXT1 && !IsVZero1)
25073       return SDValue();
25074
25075     if (IsSEXT0 && IsVZero1) {
25076       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
25077       if (CC == ISD::SETEQ)
25078         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25079       return LHS.getOperand(0);
25080     }
25081     if (IsSEXT1 && IsVZero0) {
25082       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
25083       if (CC == ISD::SETEQ)
25084         return DAG.getNOT(DL, RHS.getOperand(0), VT);
25085       return RHS.getOperand(0);
25086     }
25087   }
25088
25089   return SDValue();
25090 }
25091
25092 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25093                                       const X86Subtarget *Subtarget) {
25094   SDLoc dl(N);
25095   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25096   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25097          "X86insertps is only defined for v4x32");
25098
25099   SDValue Ld = N->getOperand(1);
25100   if (MayFoldLoad(Ld)) {
25101     // Extract the countS bits from the immediate so we can get the proper
25102     // address when narrowing the vector load to a specific element.
25103     // When the second source op is a memory address, interps doesn't use
25104     // countS and just gets an f32 from that address.
25105     unsigned DestIndex =
25106         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25107     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25108   } else
25109     return SDValue();
25110
25111   // Create this as a scalar to vector to match the instruction pattern.
25112   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25113   // countS bits are ignored when loading from memory on insertps, which
25114   // means we don't need to explicitly set them to 0.
25115   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25116                      LoadScalarToVector, N->getOperand(2));
25117 }
25118
25119 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25120 // as "sbb reg,reg", since it can be extended without zext and produces
25121 // an all-ones bit which is more useful than 0/1 in some cases.
25122 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25123                                MVT VT) {
25124   if (VT == MVT::i8)
25125     return DAG.getNode(ISD::AND, DL, VT,
25126                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25127                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
25128                        DAG.getConstant(1, VT));
25129   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25130   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25131                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25132                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
25133 }
25134
25135 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25136 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25137                                    TargetLowering::DAGCombinerInfo &DCI,
25138                                    const X86Subtarget *Subtarget) {
25139   SDLoc DL(N);
25140   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25141   SDValue EFLAGS = N->getOperand(1);
25142
25143   if (CC == X86::COND_A) {
25144     // Try to convert COND_A into COND_B in an attempt to facilitate
25145     // materializing "setb reg".
25146     //
25147     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25148     // cannot take an immediate as its first operand.
25149     //
25150     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25151         EFLAGS.getValueType().isInteger() &&
25152         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25153       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25154                                    EFLAGS.getNode()->getVTList(),
25155                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25156       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25157       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25158     }
25159   }
25160
25161   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25162   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25163   // cases.
25164   if (CC == X86::COND_B)
25165     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25166
25167   SDValue Flags;
25168
25169   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25170   if (Flags.getNode()) {
25171     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25172     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25173   }
25174
25175   return SDValue();
25176 }
25177
25178 // Optimize branch condition evaluation.
25179 //
25180 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25181                                     TargetLowering::DAGCombinerInfo &DCI,
25182                                     const X86Subtarget *Subtarget) {
25183   SDLoc DL(N);
25184   SDValue Chain = N->getOperand(0);
25185   SDValue Dest = N->getOperand(1);
25186   SDValue EFLAGS = N->getOperand(3);
25187   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25188
25189   SDValue Flags;
25190
25191   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
25192   if (Flags.getNode()) {
25193     SDValue Cond = DAG.getConstant(CC, MVT::i8);
25194     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25195                        Flags);
25196   }
25197
25198   return SDValue();
25199 }
25200
25201 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25202                                                          SelectionDAG &DAG) {
25203   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25204   // optimize away operation when it's from a constant.
25205   //
25206   // The general transformation is:
25207   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25208   //       AND(VECTOR_CMP(x,y), constant2)
25209   //    constant2 = UNARYOP(constant)
25210
25211   // Early exit if this isn't a vector operation, the operand of the
25212   // unary operation isn't a bitwise AND, or if the sizes of the operations
25213   // aren't the same.
25214   EVT VT = N->getValueType(0);
25215   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25216       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25217       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25218     return SDValue();
25219
25220   // Now check that the other operand of the AND is a constant. We could
25221   // make the transformation for non-constant splats as well, but it's unclear
25222   // that would be a benefit as it would not eliminate any operations, just
25223   // perform one more step in scalar code before moving to the vector unit.
25224   if (BuildVectorSDNode *BV =
25225           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25226     // Bail out if the vector isn't a constant.
25227     if (!BV->isConstant())
25228       return SDValue();
25229
25230     // Everything checks out. Build up the new and improved node.
25231     SDLoc DL(N);
25232     EVT IntVT = BV->getValueType(0);
25233     // Create a new constant of the appropriate type for the transformed
25234     // DAG.
25235     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25236     // The AND node needs bitcasts to/from an integer vector type around it.
25237     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
25238     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25239                                  N->getOperand(0)->getOperand(0), MaskConst);
25240     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
25241     return Res;
25242   }
25243
25244   return SDValue();
25245 }
25246
25247 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25248                                         const X86TargetLowering *XTLI) {
25249   // First try to optimize away the conversion entirely when it's
25250   // conditionally from a constant. Vectors only.
25251   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
25252   if (Res != SDValue())
25253     return Res;
25254
25255   // Now move on to more general possibilities.
25256   SDValue Op0 = N->getOperand(0);
25257   EVT InVT = Op0->getValueType(0);
25258
25259   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
25260   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
25261     SDLoc dl(N);
25262     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
25263     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25264     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
25265   }
25266
25267   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25268   // a 32-bit target where SSE doesn't support i64->FP operations.
25269   if (Op0.getOpcode() == ISD::LOAD) {
25270     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25271     EVT VT = Ld->getValueType(0);
25272     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
25273         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25274         !XTLI->getSubtarget()->is64Bit() &&
25275         VT == MVT::i64) {
25276       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
25277                                           Ld->getChain(), Op0, DAG);
25278       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25279       return FILDChain;
25280     }
25281   }
25282   return SDValue();
25283 }
25284
25285 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25286 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25287                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25288   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25289   // the result is either zero or one (depending on the input carry bit).
25290   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25291   if (X86::isZeroNode(N->getOperand(0)) &&
25292       X86::isZeroNode(N->getOperand(1)) &&
25293       // We don't have a good way to replace an EFLAGS use, so only do this when
25294       // dead right now.
25295       SDValue(N, 1).use_empty()) {
25296     SDLoc DL(N);
25297     EVT VT = N->getValueType(0);
25298     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
25299     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25300                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25301                                            DAG.getConstant(X86::COND_B,MVT::i8),
25302                                            N->getOperand(2)),
25303                                DAG.getConstant(1, VT));
25304     return DCI.CombineTo(N, Res1, CarryOut);
25305   }
25306
25307   return SDValue();
25308 }
25309
25310 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25311 //      (add Y, (setne X, 0)) -> sbb -1, Y
25312 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25313 //      (sub (setne X, 0), Y) -> adc -1, Y
25314 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25315   SDLoc DL(N);
25316
25317   // Look through ZExts.
25318   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25319   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25320     return SDValue();
25321
25322   SDValue SetCC = Ext.getOperand(0);
25323   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25324     return SDValue();
25325
25326   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25327   if (CC != X86::COND_E && CC != X86::COND_NE)
25328     return SDValue();
25329
25330   SDValue Cmp = SetCC.getOperand(1);
25331   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25332       !X86::isZeroNode(Cmp.getOperand(1)) ||
25333       !Cmp.getOperand(0).getValueType().isInteger())
25334     return SDValue();
25335
25336   SDValue CmpOp0 = Cmp.getOperand(0);
25337   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25338                                DAG.getConstant(1, CmpOp0.getValueType()));
25339
25340   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25341   if (CC == X86::COND_NE)
25342     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25343                        DL, OtherVal.getValueType(), OtherVal,
25344                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
25345   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25346                      DL, OtherVal.getValueType(), OtherVal,
25347                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
25348 }
25349
25350 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25351 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25352                                  const X86Subtarget *Subtarget) {
25353   EVT VT = N->getValueType(0);
25354   SDValue Op0 = N->getOperand(0);
25355   SDValue Op1 = N->getOperand(1);
25356
25357   // Try to synthesize horizontal adds from adds of shuffles.
25358   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25359        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25360       isHorizontalBinOp(Op0, Op1, true))
25361     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25362
25363   return OptimizeConditionalInDecrement(N, DAG);
25364 }
25365
25366 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25367                                  const X86Subtarget *Subtarget) {
25368   SDValue Op0 = N->getOperand(0);
25369   SDValue Op1 = N->getOperand(1);
25370
25371   // X86 can't encode an immediate LHS of a sub. See if we can push the
25372   // negation into a preceding instruction.
25373   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25374     // If the RHS of the sub is a XOR with one use and a constant, invert the
25375     // immediate. Then add one to the LHS of the sub so we can turn
25376     // X-Y -> X+~Y+1, saving one register.
25377     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25378         isa<ConstantSDNode>(Op1.getOperand(1))) {
25379       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25380       EVT VT = Op0.getValueType();
25381       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25382                                    Op1.getOperand(0),
25383                                    DAG.getConstant(~XorC, VT));
25384       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25385                          DAG.getConstant(C->getAPIntValue()+1, VT));
25386     }
25387   }
25388
25389   // Try to synthesize horizontal adds from adds of shuffles.
25390   EVT VT = N->getValueType(0);
25391   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25392        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25393       isHorizontalBinOp(Op0, Op1, true))
25394     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25395
25396   return OptimizeConditionalInDecrement(N, DAG);
25397 }
25398
25399 /// performVZEXTCombine - Performs build vector combines
25400 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25401                                    TargetLowering::DAGCombinerInfo &DCI,
25402                                    const X86Subtarget *Subtarget) {
25403   SDLoc DL(N);
25404   MVT VT = N->getSimpleValueType(0);
25405   SDValue Op = N->getOperand(0);
25406   MVT OpVT = Op.getSimpleValueType();
25407   MVT OpEltVT = OpVT.getVectorElementType();
25408   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25409
25410   // (vzext (bitcast (vzext (x)) -> (vzext x)
25411   SDValue V = Op;
25412   while (V.getOpcode() == ISD::BITCAST)
25413     V = V.getOperand(0);
25414
25415   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25416     MVT InnerVT = V.getSimpleValueType();
25417     MVT InnerEltVT = InnerVT.getVectorElementType();
25418
25419     // If the element sizes match exactly, we can just do one larger vzext. This
25420     // is always an exact type match as vzext operates on integer types.
25421     if (OpEltVT == InnerEltVT) {
25422       assert(OpVT == InnerVT && "Types must match for vzext!");
25423       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25424     }
25425
25426     // The only other way we can combine them is if only a single element of the
25427     // inner vzext is used in the input to the outer vzext.
25428     if (InnerEltVT.getSizeInBits() < InputBits)
25429       return SDValue();
25430
25431     // In this case, the inner vzext is completely dead because we're going to
25432     // only look at bits inside of the low element. Just do the outer vzext on
25433     // a bitcast of the input to the inner.
25434     return DAG.getNode(X86ISD::VZEXT, DL, VT,
25435                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
25436   }
25437
25438   // Check if we can bypass extracting and re-inserting an element of an input
25439   // vector. Essentialy:
25440   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25441   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25442       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25443       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25444     SDValue ExtractedV = V.getOperand(0);
25445     SDValue OrigV = ExtractedV.getOperand(0);
25446     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25447       if (ExtractIdx->getZExtValue() == 0) {
25448         MVT OrigVT = OrigV.getSimpleValueType();
25449         // Extract a subvector if necessary...
25450         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25451           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25452           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25453                                     OrigVT.getVectorNumElements() / Ratio);
25454           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25455                               DAG.getIntPtrConstant(0));
25456         }
25457         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
25458         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25459       }
25460   }
25461
25462   return SDValue();
25463 }
25464
25465 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25466                                              DAGCombinerInfo &DCI) const {
25467   SelectionDAG &DAG = DCI.DAG;
25468   switch (N->getOpcode()) {
25469   default: break;
25470   case ISD::EXTRACT_VECTOR_ELT:
25471     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25472   case ISD::VSELECT:
25473   case ISD::SELECT:
25474   case X86ISD::SHRUNKBLEND:
25475     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25476   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25477   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25478   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25479   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25480   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25481   case ISD::SHL:
25482   case ISD::SRA:
25483   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25484   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25485   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25486   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25487   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25488   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25489   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
25490   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25491   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25492   case X86ISD::FXOR:
25493   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25494   case X86ISD::FMIN:
25495   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25496   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25497   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25498   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25499   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25500   case ISD::ANY_EXTEND:
25501   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25502   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25503   case ISD::SIGN_EXTEND_INREG:
25504     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25505   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
25506   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25507   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25508   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25509   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25510   case X86ISD::SHUFP:       // Handle all target specific shuffles
25511   case X86ISD::PALIGNR:
25512   case X86ISD::UNPCKH:
25513   case X86ISD::UNPCKL:
25514   case X86ISD::MOVHLPS:
25515   case X86ISD::MOVLHPS:
25516   case X86ISD::PSHUFB:
25517   case X86ISD::PSHUFD:
25518   case X86ISD::PSHUFHW:
25519   case X86ISD::PSHUFLW:
25520   case X86ISD::MOVSS:
25521   case X86ISD::MOVSD:
25522   case X86ISD::VPERMILPI:
25523   case X86ISD::VPERM2X128:
25524   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25525   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25526   case ISD::INTRINSIC_WO_CHAIN:
25527     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25528   case X86ISD::INSERTPS:
25529     return PerformINSERTPSCombine(N, DAG, Subtarget);
25530   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
25531   }
25532
25533   return SDValue();
25534 }
25535
25536 /// isTypeDesirableForOp - Return true if the target has native support for
25537 /// the specified value type and it is 'desirable' to use the type for the
25538 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25539 /// instruction encodings are longer and some i16 instructions are slow.
25540 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25541   if (!isTypeLegal(VT))
25542     return false;
25543   if (VT != MVT::i16)
25544     return true;
25545
25546   switch (Opc) {
25547   default:
25548     return true;
25549   case ISD::LOAD:
25550   case ISD::SIGN_EXTEND:
25551   case ISD::ZERO_EXTEND:
25552   case ISD::ANY_EXTEND:
25553   case ISD::SHL:
25554   case ISD::SRL:
25555   case ISD::SUB:
25556   case ISD::ADD:
25557   case ISD::MUL:
25558   case ISD::AND:
25559   case ISD::OR:
25560   case ISD::XOR:
25561     return false;
25562   }
25563 }
25564
25565 /// IsDesirableToPromoteOp - This method query the target whether it is
25566 /// beneficial for dag combiner to promote the specified node. If true, it
25567 /// should return the desired promotion type by reference.
25568 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25569   EVT VT = Op.getValueType();
25570   if (VT != MVT::i16)
25571     return false;
25572
25573   bool Promote = false;
25574   bool Commute = false;
25575   switch (Op.getOpcode()) {
25576   default: break;
25577   case ISD::LOAD: {
25578     LoadSDNode *LD = cast<LoadSDNode>(Op);
25579     // If the non-extending load has a single use and it's not live out, then it
25580     // might be folded.
25581     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25582                                                      Op.hasOneUse()*/) {
25583       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25584              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25585         // The only case where we'd want to promote LOAD (rather then it being
25586         // promoted as an operand is when it's only use is liveout.
25587         if (UI->getOpcode() != ISD::CopyToReg)
25588           return false;
25589       }
25590     }
25591     Promote = true;
25592     break;
25593   }
25594   case ISD::SIGN_EXTEND:
25595   case ISD::ZERO_EXTEND:
25596   case ISD::ANY_EXTEND:
25597     Promote = true;
25598     break;
25599   case ISD::SHL:
25600   case ISD::SRL: {
25601     SDValue N0 = Op.getOperand(0);
25602     // Look out for (store (shl (load), x)).
25603     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25604       return false;
25605     Promote = true;
25606     break;
25607   }
25608   case ISD::ADD:
25609   case ISD::MUL:
25610   case ISD::AND:
25611   case ISD::OR:
25612   case ISD::XOR:
25613     Commute = true;
25614     // fallthrough
25615   case ISD::SUB: {
25616     SDValue N0 = Op.getOperand(0);
25617     SDValue N1 = Op.getOperand(1);
25618     if (!Commute && MayFoldLoad(N1))
25619       return false;
25620     // Avoid disabling potential load folding opportunities.
25621     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25622       return false;
25623     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25624       return false;
25625     Promote = true;
25626   }
25627   }
25628
25629   PVT = MVT::i32;
25630   return Promote;
25631 }
25632
25633 //===----------------------------------------------------------------------===//
25634 //                           X86 Inline Assembly Support
25635 //===----------------------------------------------------------------------===//
25636
25637 namespace {
25638   // Helper to match a string separated by whitespace.
25639   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
25640     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
25641
25642     for (unsigned i = 0, e = args.size(); i != e; ++i) {
25643       StringRef piece(*args[i]);
25644       if (!s.startswith(piece)) // Check if the piece matches.
25645         return false;
25646
25647       s = s.substr(piece.size());
25648       StringRef::size_type pos = s.find_first_not_of(" \t");
25649       if (pos == 0) // We matched a prefix.
25650         return false;
25651
25652       s = s.substr(pos);
25653     }
25654
25655     return s.empty();
25656   }
25657   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
25658 }
25659
25660 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25661
25662   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25663     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25664         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25665         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25666
25667       if (AsmPieces.size() == 3)
25668         return true;
25669       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25670         return true;
25671     }
25672   }
25673   return false;
25674 }
25675
25676 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25677   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25678
25679   std::string AsmStr = IA->getAsmString();
25680
25681   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25682   if (!Ty || Ty->getBitWidth() % 16 != 0)
25683     return false;
25684
25685   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25686   SmallVector<StringRef, 4> AsmPieces;
25687   SplitString(AsmStr, AsmPieces, ";\n");
25688
25689   switch (AsmPieces.size()) {
25690   default: return false;
25691   case 1:
25692     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25693     // we will turn this bswap into something that will be lowered to logical
25694     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25695     // lower so don't worry about this.
25696     // bswap $0
25697     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
25698         matchAsm(AsmPieces[0], "bswapl", "$0") ||
25699         matchAsm(AsmPieces[0], "bswapq", "$0") ||
25700         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
25701         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
25702         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
25703       // No need to check constraints, nothing other than the equivalent of
25704       // "=r,0" would be valid here.
25705       return IntrinsicLowering::LowerToByteSwap(CI);
25706     }
25707
25708     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25709     if (CI->getType()->isIntegerTy(16) &&
25710         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25711         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
25712          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
25713       AsmPieces.clear();
25714       const std::string &ConstraintsStr = IA->getConstraintString();
25715       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25716       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25717       if (clobbersFlagRegisters(AsmPieces))
25718         return IntrinsicLowering::LowerToByteSwap(CI);
25719     }
25720     break;
25721   case 3:
25722     if (CI->getType()->isIntegerTy(32) &&
25723         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25724         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
25725         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
25726         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
25727       AsmPieces.clear();
25728       const std::string &ConstraintsStr = IA->getConstraintString();
25729       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25730       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25731       if (clobbersFlagRegisters(AsmPieces))
25732         return IntrinsicLowering::LowerToByteSwap(CI);
25733     }
25734
25735     if (CI->getType()->isIntegerTy(64)) {
25736       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25737       if (Constraints.size() >= 2 &&
25738           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25739           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25740         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25741         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
25742             matchAsm(AsmPieces[1], "bswap", "%edx") &&
25743             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
25744           return IntrinsicLowering::LowerToByteSwap(CI);
25745       }
25746     }
25747     break;
25748   }
25749   return false;
25750 }
25751
25752 /// getConstraintType - Given a constraint letter, return the type of
25753 /// constraint it is for this target.
25754 X86TargetLowering::ConstraintType
25755 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
25756   if (Constraint.size() == 1) {
25757     switch (Constraint[0]) {
25758     case 'R':
25759     case 'q':
25760     case 'Q':
25761     case 'f':
25762     case 't':
25763     case 'u':
25764     case 'y':
25765     case 'x':
25766     case 'Y':
25767     case 'l':
25768       return C_RegisterClass;
25769     case 'a':
25770     case 'b':
25771     case 'c':
25772     case 'd':
25773     case 'S':
25774     case 'D':
25775     case 'A':
25776       return C_Register;
25777     case 'I':
25778     case 'J':
25779     case 'K':
25780     case 'L':
25781     case 'M':
25782     case 'N':
25783     case 'G':
25784     case 'C':
25785     case 'e':
25786     case 'Z':
25787       return C_Other;
25788     default:
25789       break;
25790     }
25791   }
25792   return TargetLowering::getConstraintType(Constraint);
25793 }
25794
25795 /// Examine constraint type and operand type and determine a weight value.
25796 /// This object must already have been set up with the operand type
25797 /// and the current alternative constraint selected.
25798 TargetLowering::ConstraintWeight
25799   X86TargetLowering::getSingleConstraintMatchWeight(
25800     AsmOperandInfo &info, const char *constraint) const {
25801   ConstraintWeight weight = CW_Invalid;
25802   Value *CallOperandVal = info.CallOperandVal;
25803     // If we don't have a value, we can't do a match,
25804     // but allow it at the lowest weight.
25805   if (!CallOperandVal)
25806     return CW_Default;
25807   Type *type = CallOperandVal->getType();
25808   // Look at the constraint type.
25809   switch (*constraint) {
25810   default:
25811     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25812   case 'R':
25813   case 'q':
25814   case 'Q':
25815   case 'a':
25816   case 'b':
25817   case 'c':
25818   case 'd':
25819   case 'S':
25820   case 'D':
25821   case 'A':
25822     if (CallOperandVal->getType()->isIntegerTy())
25823       weight = CW_SpecificReg;
25824     break;
25825   case 'f':
25826   case 't':
25827   case 'u':
25828     if (type->isFloatingPointTy())
25829       weight = CW_SpecificReg;
25830     break;
25831   case 'y':
25832     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25833       weight = CW_SpecificReg;
25834     break;
25835   case 'x':
25836   case 'Y':
25837     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25838         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25839       weight = CW_Register;
25840     break;
25841   case 'I':
25842     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25843       if (C->getZExtValue() <= 31)
25844         weight = CW_Constant;
25845     }
25846     break;
25847   case 'J':
25848     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25849       if (C->getZExtValue() <= 63)
25850         weight = CW_Constant;
25851     }
25852     break;
25853   case 'K':
25854     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25855       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25856         weight = CW_Constant;
25857     }
25858     break;
25859   case 'L':
25860     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25861       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25862         weight = CW_Constant;
25863     }
25864     break;
25865   case 'M':
25866     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25867       if (C->getZExtValue() <= 3)
25868         weight = CW_Constant;
25869     }
25870     break;
25871   case 'N':
25872     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25873       if (C->getZExtValue() <= 0xff)
25874         weight = CW_Constant;
25875     }
25876     break;
25877   case 'G':
25878   case 'C':
25879     if (dyn_cast<ConstantFP>(CallOperandVal)) {
25880       weight = CW_Constant;
25881     }
25882     break;
25883   case 'e':
25884     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25885       if ((C->getSExtValue() >= -0x80000000LL) &&
25886           (C->getSExtValue() <= 0x7fffffffLL))
25887         weight = CW_Constant;
25888     }
25889     break;
25890   case 'Z':
25891     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25892       if (C->getZExtValue() <= 0xffffffff)
25893         weight = CW_Constant;
25894     }
25895     break;
25896   }
25897   return weight;
25898 }
25899
25900 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25901 /// with another that has more specific requirements based on the type of the
25902 /// corresponding operand.
25903 const char *X86TargetLowering::
25904 LowerXConstraint(EVT ConstraintVT) const {
25905   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25906   // 'f' like normal targets.
25907   if (ConstraintVT.isFloatingPoint()) {
25908     if (Subtarget->hasSSE2())
25909       return "Y";
25910     if (Subtarget->hasSSE1())
25911       return "x";
25912   }
25913
25914   return TargetLowering::LowerXConstraint(ConstraintVT);
25915 }
25916
25917 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25918 /// vector.  If it is invalid, don't add anything to Ops.
25919 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25920                                                      std::string &Constraint,
25921                                                      std::vector<SDValue>&Ops,
25922                                                      SelectionDAG &DAG) const {
25923   SDValue Result;
25924
25925   // Only support length 1 constraints for now.
25926   if (Constraint.length() > 1) return;
25927
25928   char ConstraintLetter = Constraint[0];
25929   switch (ConstraintLetter) {
25930   default: break;
25931   case 'I':
25932     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25933       if (C->getZExtValue() <= 31) {
25934         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25935         break;
25936       }
25937     }
25938     return;
25939   case 'J':
25940     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25941       if (C->getZExtValue() <= 63) {
25942         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25943         break;
25944       }
25945     }
25946     return;
25947   case 'K':
25948     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25949       if (isInt<8>(C->getSExtValue())) {
25950         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25951         break;
25952       }
25953     }
25954     return;
25955   case 'N':
25956     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25957       if (C->getZExtValue() <= 255) {
25958         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25959         break;
25960       }
25961     }
25962     return;
25963   case 'e': {
25964     // 32-bit signed value
25965     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25966       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25967                                            C->getSExtValue())) {
25968         // Widen to 64 bits here to get it sign extended.
25969         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
25970         break;
25971       }
25972     // FIXME gcc accepts some relocatable values here too, but only in certain
25973     // memory models; it's complicated.
25974     }
25975     return;
25976   }
25977   case 'Z': {
25978     // 32-bit unsigned value
25979     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25980       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25981                                            C->getZExtValue())) {
25982         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
25983         break;
25984       }
25985     }
25986     // FIXME gcc accepts some relocatable values here too, but only in certain
25987     // memory models; it's complicated.
25988     return;
25989   }
25990   case 'i': {
25991     // Literal immediates are always ok.
25992     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25993       // Widen to 64 bits here to get it sign extended.
25994       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
25995       break;
25996     }
25997
25998     // In any sort of PIC mode addresses need to be computed at runtime by
25999     // adding in a register or some sort of table lookup.  These can't
26000     // be used as immediates.
26001     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26002       return;
26003
26004     // If we are in non-pic codegen mode, we allow the address of a global (with
26005     // an optional displacement) to be used with 'i'.
26006     GlobalAddressSDNode *GA = nullptr;
26007     int64_t Offset = 0;
26008
26009     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26010     while (1) {
26011       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26012         Offset += GA->getOffset();
26013         break;
26014       } else if (Op.getOpcode() == ISD::ADD) {
26015         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26016           Offset += C->getZExtValue();
26017           Op = Op.getOperand(0);
26018           continue;
26019         }
26020       } else if (Op.getOpcode() == ISD::SUB) {
26021         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26022           Offset += -C->getZExtValue();
26023           Op = Op.getOperand(0);
26024           continue;
26025         }
26026       }
26027
26028       // Otherwise, this isn't something we can handle, reject it.
26029       return;
26030     }
26031
26032     const GlobalValue *GV = GA->getGlobal();
26033     // If we require an extra load to get this address, as in PIC mode, we
26034     // can't accept it.
26035     if (isGlobalStubReference(
26036             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26037       return;
26038
26039     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26040                                         GA->getValueType(0), Offset);
26041     break;
26042   }
26043   }
26044
26045   if (Result.getNode()) {
26046     Ops.push_back(Result);
26047     return;
26048   }
26049   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26050 }
26051
26052 std::pair<unsigned, const TargetRegisterClass*>
26053 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
26054                                                 MVT VT) const {
26055   // First, see if this is a constraint that directly corresponds to an LLVM
26056   // register class.
26057   if (Constraint.size() == 1) {
26058     // GCC Constraint Letters
26059     switch (Constraint[0]) {
26060     default: break;
26061       // TODO: Slight differences here in allocation order and leaving
26062       // RIP in the class. Do they matter any more here than they do
26063       // in the normal allocation?
26064     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26065       if (Subtarget->is64Bit()) {
26066         if (VT == MVT::i32 || VT == MVT::f32)
26067           return std::make_pair(0U, &X86::GR32RegClass);
26068         if (VT == MVT::i16)
26069           return std::make_pair(0U, &X86::GR16RegClass);
26070         if (VT == MVT::i8 || VT == MVT::i1)
26071           return std::make_pair(0U, &X86::GR8RegClass);
26072         if (VT == MVT::i64 || VT == MVT::f64)
26073           return std::make_pair(0U, &X86::GR64RegClass);
26074         break;
26075       }
26076       // 32-bit fallthrough
26077     case 'Q':   // Q_REGS
26078       if (VT == MVT::i32 || VT == MVT::f32)
26079         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26080       if (VT == MVT::i16)
26081         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26082       if (VT == MVT::i8 || VT == MVT::i1)
26083         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26084       if (VT == MVT::i64)
26085         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26086       break;
26087     case 'r':   // GENERAL_REGS
26088     case 'l':   // INDEX_REGS
26089       if (VT == MVT::i8 || VT == MVT::i1)
26090         return std::make_pair(0U, &X86::GR8RegClass);
26091       if (VT == MVT::i16)
26092         return std::make_pair(0U, &X86::GR16RegClass);
26093       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26094         return std::make_pair(0U, &X86::GR32RegClass);
26095       return std::make_pair(0U, &X86::GR64RegClass);
26096     case 'R':   // LEGACY_REGS
26097       if (VT == MVT::i8 || VT == MVT::i1)
26098         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26099       if (VT == MVT::i16)
26100         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26101       if (VT == MVT::i32 || !Subtarget->is64Bit())
26102         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26103       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26104     case 'f':  // FP Stack registers.
26105       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26106       // value to the correct fpstack register class.
26107       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26108         return std::make_pair(0U, &X86::RFP32RegClass);
26109       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26110         return std::make_pair(0U, &X86::RFP64RegClass);
26111       return std::make_pair(0U, &X86::RFP80RegClass);
26112     case 'y':   // MMX_REGS if MMX allowed.
26113       if (!Subtarget->hasMMX()) break;
26114       return std::make_pair(0U, &X86::VR64RegClass);
26115     case 'Y':   // SSE_REGS if SSE2 allowed
26116       if (!Subtarget->hasSSE2()) break;
26117       // FALL THROUGH.
26118     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26119       if (!Subtarget->hasSSE1()) break;
26120
26121       switch (VT.SimpleTy) {
26122       default: break;
26123       // Scalar SSE types.
26124       case MVT::f32:
26125       case MVT::i32:
26126         return std::make_pair(0U, &X86::FR32RegClass);
26127       case MVT::f64:
26128       case MVT::i64:
26129         return std::make_pair(0U, &X86::FR64RegClass);
26130       // Vector types.
26131       case MVT::v16i8:
26132       case MVT::v8i16:
26133       case MVT::v4i32:
26134       case MVT::v2i64:
26135       case MVT::v4f32:
26136       case MVT::v2f64:
26137         return std::make_pair(0U, &X86::VR128RegClass);
26138       // AVX types.
26139       case MVT::v32i8:
26140       case MVT::v16i16:
26141       case MVT::v8i32:
26142       case MVT::v4i64:
26143       case MVT::v8f32:
26144       case MVT::v4f64:
26145         return std::make_pair(0U, &X86::VR256RegClass);
26146       case MVT::v8f64:
26147       case MVT::v16f32:
26148       case MVT::v16i32:
26149       case MVT::v8i64:
26150         return std::make_pair(0U, &X86::VR512RegClass);
26151       }
26152       break;
26153     }
26154   }
26155
26156   // Use the default implementation in TargetLowering to convert the register
26157   // constraint into a member of a register class.
26158   std::pair<unsigned, const TargetRegisterClass*> Res;
26159   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
26160
26161   // Not found as a standard register?
26162   if (!Res.second) {
26163     // Map st(0) -> st(7) -> ST0
26164     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26165         tolower(Constraint[1]) == 's' &&
26166         tolower(Constraint[2]) == 't' &&
26167         Constraint[3] == '(' &&
26168         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26169         Constraint[5] == ')' &&
26170         Constraint[6] == '}') {
26171
26172       Res.first = X86::FP0+Constraint[4]-'0';
26173       Res.second = &X86::RFP80RegClass;
26174       return Res;
26175     }
26176
26177     // GCC allows "st(0)" to be called just plain "st".
26178     if (StringRef("{st}").equals_lower(Constraint)) {
26179       Res.first = X86::FP0;
26180       Res.second = &X86::RFP80RegClass;
26181       return Res;
26182     }
26183
26184     // flags -> EFLAGS
26185     if (StringRef("{flags}").equals_lower(Constraint)) {
26186       Res.first = X86::EFLAGS;
26187       Res.second = &X86::CCRRegClass;
26188       return Res;
26189     }
26190
26191     // 'A' means EAX + EDX.
26192     if (Constraint == "A") {
26193       Res.first = X86::EAX;
26194       Res.second = &X86::GR32_ADRegClass;
26195       return Res;
26196     }
26197     return Res;
26198   }
26199
26200   // Otherwise, check to see if this is a register class of the wrong value
26201   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26202   // turn into {ax},{dx}.
26203   if (Res.second->hasType(VT))
26204     return Res;   // Correct type already, nothing to do.
26205
26206   // All of the single-register GCC register classes map their values onto
26207   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
26208   // really want an 8-bit or 32-bit register, map to the appropriate register
26209   // class and return the appropriate register.
26210   if (Res.second == &X86::GR16RegClass) {
26211     if (VT == MVT::i8 || VT == MVT::i1) {
26212       unsigned DestReg = 0;
26213       switch (Res.first) {
26214       default: break;
26215       case X86::AX: DestReg = X86::AL; break;
26216       case X86::DX: DestReg = X86::DL; break;
26217       case X86::CX: DestReg = X86::CL; break;
26218       case X86::BX: DestReg = X86::BL; break;
26219       }
26220       if (DestReg) {
26221         Res.first = DestReg;
26222         Res.second = &X86::GR8RegClass;
26223       }
26224     } else if (VT == MVT::i32 || VT == MVT::f32) {
26225       unsigned DestReg = 0;
26226       switch (Res.first) {
26227       default: break;
26228       case X86::AX: DestReg = X86::EAX; break;
26229       case X86::DX: DestReg = X86::EDX; break;
26230       case X86::CX: DestReg = X86::ECX; break;
26231       case X86::BX: DestReg = X86::EBX; break;
26232       case X86::SI: DestReg = X86::ESI; break;
26233       case X86::DI: DestReg = X86::EDI; break;
26234       case X86::BP: DestReg = X86::EBP; break;
26235       case X86::SP: DestReg = X86::ESP; break;
26236       }
26237       if (DestReg) {
26238         Res.first = DestReg;
26239         Res.second = &X86::GR32RegClass;
26240       }
26241     } else if (VT == MVT::i64 || VT == MVT::f64) {
26242       unsigned DestReg = 0;
26243       switch (Res.first) {
26244       default: break;
26245       case X86::AX: DestReg = X86::RAX; break;
26246       case X86::DX: DestReg = X86::RDX; break;
26247       case X86::CX: DestReg = X86::RCX; break;
26248       case X86::BX: DestReg = X86::RBX; break;
26249       case X86::SI: DestReg = X86::RSI; break;
26250       case X86::DI: DestReg = X86::RDI; break;
26251       case X86::BP: DestReg = X86::RBP; break;
26252       case X86::SP: DestReg = X86::RSP; break;
26253       }
26254       if (DestReg) {
26255         Res.first = DestReg;
26256         Res.second = &X86::GR64RegClass;
26257       }
26258     }
26259   } else if (Res.second == &X86::FR32RegClass ||
26260              Res.second == &X86::FR64RegClass ||
26261              Res.second == &X86::VR128RegClass ||
26262              Res.second == &X86::VR256RegClass ||
26263              Res.second == &X86::FR32XRegClass ||
26264              Res.second == &X86::FR64XRegClass ||
26265              Res.second == &X86::VR128XRegClass ||
26266              Res.second == &X86::VR256XRegClass ||
26267              Res.second == &X86::VR512RegClass) {
26268     // Handle references to XMM physical registers that got mapped into the
26269     // wrong class.  This can happen with constraints like {xmm0} where the
26270     // target independent register mapper will just pick the first match it can
26271     // find, ignoring the required type.
26272
26273     if (VT == MVT::f32 || VT == MVT::i32)
26274       Res.second = &X86::FR32RegClass;
26275     else if (VT == MVT::f64 || VT == MVT::i64)
26276       Res.second = &X86::FR64RegClass;
26277     else if (X86::VR128RegClass.hasType(VT))
26278       Res.second = &X86::VR128RegClass;
26279     else if (X86::VR256RegClass.hasType(VT))
26280       Res.second = &X86::VR256RegClass;
26281     else if (X86::VR512RegClass.hasType(VT))
26282       Res.second = &X86::VR512RegClass;
26283   }
26284
26285   return Res;
26286 }
26287
26288 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26289                                             Type *Ty) const {
26290   // Scaling factors are not free at all.
26291   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26292   // will take 2 allocations in the out of order engine instead of 1
26293   // for plain addressing mode, i.e. inst (reg1).
26294   // E.g.,
26295   // vaddps (%rsi,%drx), %ymm0, %ymm1
26296   // Requires two allocations (one for the load, one for the computation)
26297   // whereas:
26298   // vaddps (%rsi), %ymm0, %ymm1
26299   // Requires just 1 allocation, i.e., freeing allocations for other operations
26300   // and having less micro operations to execute.
26301   //
26302   // For some X86 architectures, this is even worse because for instance for
26303   // stores, the complex addressing mode forces the instruction to use the
26304   // "load" ports instead of the dedicated "store" port.
26305   // E.g., on Haswell:
26306   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26307   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
26308   if (isLegalAddressingMode(AM, Ty))
26309     // Scale represents reg2 * scale, thus account for 1
26310     // as soon as we use a second register.
26311     return AM.Scale != 0;
26312   return -1;
26313 }
26314
26315 bool X86TargetLowering::isTargetFTOL() const {
26316   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26317 }